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
105const SUBC_CONTROL_OPS: &[&str] = &[
106    "claim.mint",
107    "claim.present",
108    ops::DAEMON_SHUTDOWN_INTENT,
109    ops::ACTIVITY_RECORD,
110    ops::ACTIVITY_QUERY,
111    ops::ACTIVITY_SUBSCRIBE,
112    ops::SERVER_DESCRIBE,
113    ops::CATALOG_LIST,
114    ops::CATALOG_WATCH,
115    ops::ROUTE_OPEN,
116    ops::ROUTE_POLL,
117    ops::ROUTE_CLOSING,
118    ops::ROUTE_CLOSED,
119    ops::SUPERVISOR_LIST,
120    ops::SUPERVISOR_RESTART,
121    ops::SUPERVISOR_SWAP,
122    ops::SUPERVISOR_RELOAD,
123    ops::SUPERVISOR_RESCAN,
124    ops::SUPERVISOR_RELEASE_RESERVED,
125    ops::SUPERVISOR_SET_ENABLED,
126    ops::SUPERVISOR_HEALTH_PROBE,
127    ops::SUPERVISOR_HEALTH,
128    ops::SUPERVISOR_STDERR_TAIL,
129    ops::SUPERVISOR_TERMINALS,
130    ops::SUPERVISOR_ROUTES,
131    ops::SUPERVISOR_PROVENANCE,
132    ops::SUPERVISOR_SPAWN_SNAPSHOT,
133    ops::SUPERVISOR_SPAWN_SUBSCRIBE,
134];
135
136/// Client ops the daemon serves but leaves out of `subc_ops`. Each is
137/// announced by a capability in `server.describe` instead, and clients check
138/// that capability before sending it. `ck daemon --json` prints `subc_ops`
139/// verbatim and scripts read that output, so a new name there would change it.
140/// A malformed body for one of these is still refused `invalid_control_body`
141/// rather than as an unknown op.
142const SUBC_UNADVERTISED_CONTROL_OPS: &[&str] = &[
143    ops::SUPERVISOR_RESCAN_CHECKED,
144    "config.modules",
145    "config.schema",
146    "config.show",
147    "config.watch",
148    "config.status",
149    "config.plan",
150    "config.plan_get",
151    "config.plan_discard",
152    "config.apply",
153    "config.stamp",
154    "config.unstamp",
155    "config.history",
156    "config.rollback",
157];
158
159mod caller_attestation;
160mod channel_operations;
161#[cfg(all(test, unix, feature = "test-support"))]
162#[path = "control/channel_operations_tests.rs"]
163mod channel_operations_tests;
164pub(crate) mod claims;
165#[cfg(test)]
166#[path = "control/config_advertisement_tests.rs"]
167mod config_advertisement_tests;
168mod config_gate;
169#[path = "operator_apps/connection.rs"]
170mod peer_identity;
171use caller_attestation::{caller_for_target, scope_acts_for_another};
172mod activity_reservations;
173#[cfg(all(test, unix, feature = "test-support"))]
174#[path = "control/caller_attestation_tests.rs"]
175mod caller_attestation_tests;
176mod capability_census;
177mod route_bind_settlement;
178mod scope_expiry;
179mod scope_watch;
180mod usage;
181
182mod agent_commands;
183pub(crate) mod catalog;
184mod rescan_checked;
185use rescan_checked::{RescanMode, RescanPlan};
186
187const MODULE_TO_SUBC_CONTROL_OPS: &[&str] = &[
188    "claim.mint",
189    "claim.present",
190    MODULE_TO_SUBC_OP_CATALOG_UPDATE,
191    MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
192    "supervisor.live_roots",
193    "supervisor.agent_commands",
194    SCOPE_SYNC_OP,
195    SCOPE_APPLY_OP,
196    SCOPE_DESCRIBE_OP,
197    ops::SCOPE_WATCH,
198    subc_protocol::scope::ROUTE_AUTHORIZE_OP,
199    "operator.confirm",
200];
201
202/// Module-originated ops the daemon answers but does not advertise in
203/// `HELLO_ACK`. Empty today; an op is served from here while the feature it
204/// belongs to is incomplete, so no module is told it works before it does.
205const MODULE_TO_SUBC_UNADVERTISED_OPS: &[&str] = &[];
206
207const MODULE_BASELINE_CONTROL_OPS: &[&str] = &["route.bind", "route.status"];
208
209/// How long subc waits for a module to ack a relayed route.bind before returning
210/// `module_timeout`. The ack waits on the module's own configure, which for AFT
211/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
212/// and DB-open work — on a cold page cache or a large repo that legitimately
213/// exceeds a couple of seconds. The default is generous because rejecting a VALID
214/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
215/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
216pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
217
218/// How many CONSECUTIVE full-budget relay timeouts against one target module
219/// open that module's bind-relay breaker.
220///
221/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
222/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
223/// so three consecutive full-budget timeouts take ~36s to observe: every client
224/// whose open contributed to opening the breaker had already given up on its
225/// own. That is what makes opening the breaker unable to turn a call that would
226/// have succeeded into a refusal — it can only make an already-failing module
227/// fail faster.
228///
229/// Two would be reachable inside one default deadline. One would convict a
230/// module on a single cold-cache bind, which is exactly the valid-but-slow case
231/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
232pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
233
234/// How long a module's bind-relay breaker stays open before exactly one
235/// `route.open` is let through as a probe.
236///
237/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
238/// re-pays a full-budget stall almost continuously, and the breaker stops being
239/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
240/// deadline: a client that starts retrying after the module recovers has to get
241/// a probe opportunity inside its own deadline, or the breaker converts a
242/// recovered module into a failed call — the failure it exists to prevent,
243/// pointed the other way.
244///
245/// 20s sits between those with room on both sides, and it caps what a wedged
246/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
247/// rather than one per `route.open` per connection. The stall that motivated
248/// this, with its measurements, is written up in
249/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
250/// waited the whole budget out.
251pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
252
253const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
254const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
255
256fn reload_verdict(
257    configured: &Path,
258    spawned_from: Option<&Path>,
259    image: subc_control::RunningImageAgreement,
260) -> PendingReloadVerdict {
261    let path = match spawned_from {
262        Some(spawned_from) if reload_paths_match(configured, spawned_from) => {
263            ReloadPathAgreement::Match
264        }
265        Some(spawned_from) => ReloadPathAgreement::Mismatch {
266            configured: configured.to_path_buf(),
267            spawned_from: spawned_from.to_path_buf(),
268        },
269        None => ReloadPathAgreement::Unavailable {
270            reason: if matches!(
271                image,
272                subc_control::RunningImageAgreement::Unavailable {
273                    reason: subc_control::RunningImageUnavailableReason::NotRunning
274                }
275            ) {
276                ReloadPathUnavailableReason::NotRunning
277            } else {
278                ReloadPathUnavailableReason::SpawnedPathUnavailable
279            },
280        },
281    };
282    PendingReloadVerdict::new(path, image)
283}
284
285fn launch_spec_agreement(
286    configured: &crate::supervise::ModuleSpec,
287    running: bool,
288    spawned: Option<&crate::supervise::LaunchSpecDigest>,
289) -> subc_control::LaunchSpecAgreement {
290    use subc_control::{LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason};
291    if !running {
292        return Agreement::Unavailable {
293            reason: Reason::NotRunning,
294        };
295    }
296    match spawned {
297        None => Agreement::Unavailable {
298            reason: Reason::SpawnedSpecUnavailable,
299        },
300        Some(digest) if *digest == crate::supervise::LaunchSpecDigest::from_spec(configured) => {
301            Agreement::Match
302        }
303        Some(_) => Agreement::Mismatch,
304    }
305}
306
307fn reload_paths_match(configured: &Path, spawned_from: &Path) -> bool {
308    if configured == spawned_from {
309        return true;
310    }
311    #[cfg(windows)]
312    {
313        // Windows spawn records the resolved verbatim path (\\?\...), while
314        // configuration keeps its original spelling. Resolve both with the OS
315        // instead of stripping prefixes or folding case, which could conflate
316        // distinct names in case-sensitive directories. Different resolved
317        // paths still differ even if their files have identical content.
318        match (
319            std::fs::canonicalize(configured),
320            std::fs::canonicalize(spawned_from),
321        ) {
322            (Ok(configured), Ok(spawned_from)) => configured == spawned_from,
323            _ => false,
324        }
325    }
326    #[cfg(not(windows))]
327    {
328        false
329    }
330}
331
332#[derive(Clone)]
333struct DaemonProvenanceFacts {
334    build: DaemonBuildProvenance,
335    pid: Option<u32>,
336    started_at_ms: Option<u64>,
337    start_clock: Option<crate::clock::StartClock>,
338    executable_path: Option<PathBuf>,
339    executable_identity: Option<SpawnedFileIdentity>,
340    process_start_time: Option<u64>,
341    probe: ExecutableIdentityProbe,
342}
343
344impl Default for DaemonProvenanceFacts {
345    fn default() -> Self {
346        Self {
347            build: DaemonBuildProvenance {
348                build_git_sha: None,
349                build_lock_digest: None,
350            },
351            pid: None,
352            started_at_ms: None,
353            start_clock: None,
354            executable_path: None,
355            executable_identity: None,
356            process_start_time: None,
357            probe: ExecutableIdentityProbe::default(),
358        }
359    }
360}
361
362#[derive(Debug, Clone)]
363struct SupervisorRescanContext {
364    supervisor: Supervisor,
365    config_path: PathBuf,
366    configured_port: Option<u16>,
367    storage_config: Option<crate::daemon_config::StorageConfig>,
368    admission_facts_carrier_module_id: Option<String>,
369    admission_facts_targets: Option<Vec<String>>,
370    scope_authority_owners: Vec<String>,
371    federated_scope_owner: String,
372    privileged_operator_prompt: PrivilegedOperatorPrompt,
373    /// Counts executed rescans that set out to change the supervised modules'
374    /// staged or applied configuration, counted before the first change so a
375    /// rescan that fails partway still counts. With the daemon incarnation it
376    /// names the state a `supervisor.rescan_checked` preview was computed
377    /// against.
378    generation: Arc<std::sync::atomic::AtomicU64>,
379    rescan_lock: Arc<tokio::sync::Mutex<()>>,
380    module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
381}
382
383/// Refusal labels passed to `observe_route_open_refusal` that mean the target
384/// module is not serving right now, and so open or extend an outage in the
385/// route outage tracker. Every one of them is only reachable after the target
386/// was found in the registry, which is what keeps an arbitrary client-chosen
387/// id from ever creating tracker state.
388///
389/// Deliberately absent: `not_registered` and `removed` (the id may be
390/// anything a client sent, and a removed module is gone on purpose),
391/// `protocol_none` (such a module never serves routes, so nothing is out),
392/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
393/// capability and admission-facts refusals (they refuse the caller, not a
394/// module outage), and `relay_reservation_failed` (its code ranges over
395/// capacity limits as well as a vanished connection). Capacity, breaker,
396/// relay-timeout and module-rejection refusals do not pass through that
397/// function at all; the breaker logs its own transitions.
398///
399/// The two not-serving refusals that bypass that function record themselves
400/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
401/// `required_capability_unprovided` is not tracked: the module itself is up,
402/// and the outage belongs to the missing provider.
403const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
404    "reloading",
405    "supervisor_not_live",
406    "registration_not_active",
407    "no_forwarding_connection",
408    "relay_send_failed",
409];
410
411/// Observe test request cancellation relative to the connection's cleanup.
412#[cfg(test)]
413struct ActivityRequestPause {
414    connection: ConnectionId,
415    started: tokio::sync::Notify,
416    cancelled: tokio::sync::Notify,
417    cleanup_started: std::sync::atomic::AtomicBool,
418    cancelled_after_cleanup: std::sync::atomic::AtomicBool,
419}
420
421#[cfg(test)]
422struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
423
424#[cfg(test)]
425impl Drop for ActivityRequestCancellation {
426    fn drop(&mut self) {
427        self.0.cancelled_after_cleanup.store(
428            self.0
429                .cleanup_started
430                .load(std::sync::atomic::Ordering::Acquire),
431            std::sync::atomic::Ordering::Release,
432        );
433        self.0.cancelled.notify_one();
434    }
435}
436
437/// A test hold: signal arrival, then wait for release on the holding thread.
438#[cfg(test)]
439type TestPause = (
440    tokio::sync::oneshot::Sender<()>,
441    std::sync::mpsc::Receiver<()>,
442);
443
444/// A test hook run once at a fixed point in a handler.
445#[cfg(test)]
446type TestHook = Box<dyn FnOnce() + Send>;
447
448/// A test hold for async code: signal arrival, then await release.
449#[cfg(test)]
450type AsyncTestPause = (
451    tokio::sync::oneshot::Sender<()>,
452    tokio::sync::oneshot::Receiver<()>,
453);
454
455/// Real channel-0 control handler for subc itself.
456#[derive(Clone)]
457pub struct ControlHandler {
458    #[cfg(test)]
459    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
460    /// Holds connection cleanup at a numbered point: 0 is just after the agent
461    /// declaration queue closes, 1 just after the registration channel is
462    /// forgotten.
463    #[cfg(test)]
464    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
465    /// Runs once in `route.open`'s launch-nonce attestation, right after the
466    /// nonce is resolved, to interleave a nonce withdrawal there.
467    #[cfg(test)]
468    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
469    /// Holds a registration channel's HELLO after its reader resolved the
470    /// channel and before the blocking HELLO handler starts.
471    #[cfg(test)]
472    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
473    /// Holds an agent command declaration at a numbered point in its handler.
474    #[cfg(test)]
475    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
476    claims: Arc<claims::Claims>,
477    registry: Arc<Registry>,
478    control_usage: Arc<Mutex<usage::ControlUsage>>,
479    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
480    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
481    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
482    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
483    config_review_admission_is_default: bool,
484    activity: Option<crate::activity::ActivityLedger>,
485    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
486    activity_reservations: activity_reservations::ActivityReservations,
487    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
488    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
489    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
490    forwarding: Arc<ForwardingTable>,
491    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
492    supervisor: SupervisorHandle,
493    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
494    agent_declarations: agent_commands::Queues,
495    list_admission: Arc<tokio::sync::Semaphore>,
496    subc_capabilities: Arc<[String]>,
497    /// Daemon-wide route.bind relay budget. Used as the fallback when the
498    /// target module has no per-module override in
499    /// `route_bind_relay_timeouts`.
500    route_bind_relay_timeout: Duration,
501    /// Per-module route.bind relay budget overrides, keyed by module id. When
502    /// `handle_route_open` resolves the deadline for a target module, a
503    /// per-module entry wins over the daemon-wide value above.
504    route_bind_relay_timeouts: BTreeMap<String, Duration>,
505    /// Per-target-module bind-relay breaker state. Shared with the forwarding
506    /// table, which is where a new module connection resets it.
507    route_bind_breakers: RouteBindBreakers,
508    /// Live relay admissions keyed by target module. Shared through the
509    /// forwarding table so cloned or separately built handlers enforce one cap.
510    route_bind_concurrency: RouteBindConcurrency,
511    /// Start and end of each module's not-serving period as seen by
512    /// `route.open`, so an outage gets one line at each edge instead of only
513    /// the per-refusal INFO lines. Taken from the forwarding table, so every
514    /// handler built over one table shares it.
515    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
516    route_refusal_log: route_open_refusal_log::RefusalLog,
517    /// Consecutive relay timeouts that open a module's breaker.
518    route_bind_breaker_threshold: u32,
519    /// How long a breaker stays open before one probe is admitted.
520    route_bind_breaker_cooldown: Duration,
521    health_probe_timeout: Duration,
522    /// Central storage policy. When set, each registering module receives its
523    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
524    storage_config: Option<crate::daemon_config::StorageConfig>,
525    /// The machine id established at boot, served on every HELLO_ACK and on
526    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
527    /// changes the file, never this value. `None` serves no id.
528    machine_id: Option<crate::machine_id::MachineId>,
529    admission_facts_carrier_module_id: Option<String>,
530    admission_facts_targets: Option<Vec<String>>,
531    /// Scope records with their sync authorities and tombstones; see
532    /// `crate::scopes`. Shared by clones of this handler, so every connection
533    /// reads and writes one table.
534    scopes: Arc<RwLock<ScopeTable>>,
535    /// Wakes the expiry loop when an accepted scope change may have added a
536    /// deadline, so the loop can wait without ticking while no live scope has
537    /// one. A permit is stored when nothing waits, so no wake is lost.
538    scope_deadline_added: Arc<tokio::sync::Notify>,
539    /// The configured `scope_authority_owners`, kept so a rescan can report a
540    /// changed value as needing a daemon restart; rescan never applies it.
541    scope_authority_owners: Vec<String>,
542    federated_scope_owner: String,
543    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
544    privileged_operator_prompt: PrivilegedOperatorPrompt,
545    /// The local and peer address of each accepted TCP client connection, read
546    /// from the daemon's own socket, so a privileged request can name its caller.
547    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
548    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
549    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
550    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
551    config_desktop_stamps:
552        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
553    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
554    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
555    pub(crate) operator_apps:
556        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
557    /// One launch entry per app, behind a leaf lock: no other lock is taken
558    /// while it is held. Entries are memory-only, so a daemon or
559    /// installed-service restart drops them and a relaunched daemon never
560    /// mistakes an older process for its own launch.
561    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
562    /// Serializes `app.open` launches: the liveness check in the decision and
563    /// the later publish must not interleave across concurrent calls, or two
564    /// calls could both launch and the second publish would orphan the first
565    /// process. Refusals and `already_running` answers share the same lock;
566    /// `app.open` is rare, so the cost is negligible.
567    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
568    // Portable wire samples exercise dispatch without starting an OS process.
569    #[cfg(test)]
570    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
571    #[cfg(test)]
572    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
573    #[cfg(test)]
574    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
575    #[cfg(test)]
576    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
577    #[cfg(test)]
578    recovery_exit_test_completed: Option<fn(u64)>,
579    #[cfg(test)]
580    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
581    #[cfg(test)]
582    recovery_exit_test_quiet_retry: bool,
583    #[cfg(test)]
584    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
585    #[cfg(test)]
586    config_delivery_test_wakes:
587        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
588    #[cfg(all(test, unix))]
589    config_delivery_test_idle:
590        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
591    /// Test-only Windows signature and flash hooks. Production builds carry
592    /// neither: with the publisher unset, the production table never reaches
593    /// verification, and the default attention hook only logs.
594    #[allow(dead_code)]
595    #[cfg(windows)]
596    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
597    #[allow(dead_code)]
598    #[cfg(windows)]
599    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
600    /// Test-only tracking fault hook: makes opening the tracking handle on
601    /// the launched pid fail, so a test can prove an untrackable launch is
602    /// stopped rather than left running.
603    #[allow(dead_code)]
604    #[cfg(windows)]
605    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
606    /// Test-only count of Windows spawn attempts, so a test can prove a
607    /// refused launch started no process. Unit tests only.
608    #[cfg(all(test, windows))]
609    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
610    #[cfg(test)]
611    caller_lookup: Option<TestCallerLookup>,
612    /// The launch nonce each module connection presented at HELLO, which is how
613    /// a `scope.sync` is matched to the owner's current launch.
614    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
615    rescan: Option<SupervisorRescanContext>,
616    connected_clients: ConnectedClients,
617    counters: DaemonCounters,
618    /// Why this daemon serves no local endpoint, when binding one failed. `None`
619    /// when the endpoint is served, and also on a handler that was never told.
620    local_endpoint_unavailable: Option<String>,
621    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
622    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
623    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
624    /// their usual severity (see [`log_requirement_events`]). A handler built
625    /// without one has a flag that is never set.
626    daemon_shutdown: DaemonShutdownFlag,
627    daemon_provenance: DaemonProvenanceFacts,
628    #[cfg(test)]
629    control_dispatch_delay: Option<Duration>,
630    #[cfg(test)]
631    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
632    /// Holds `route.open` after the route.bind is queued to the module and
633    /// before it is marked enqueued, so a test can make the module's reply (or
634    /// a client teardown) land exactly inside that window.
635    #[cfg(test)]
636    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
637    /// Holds a HELLO after its registry entry is reserved and before its
638    /// forwarding endpoint is installed, so a test can read the catalog and
639    /// open routes while the module is registered but not yet routable. A
640    /// blocking barrier because the HELLO handler is synchronous; the test
641    /// runs the HELLO on its own thread.
642    #[cfg(test)]
643    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
644    #[cfg(test)]
645    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
646    #[cfg(test)]
647    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
648    #[cfg(test)]
649    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
650    #[cfg(test)]
651    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
652}
653
654impl fmt::Debug for ControlHandler {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        f.debug_struct("ControlHandler")
657            .field("registry", &self.registry)
658            .field("forwarding", &self.forwarding)
659            .field("process_liveness", &self.process_liveness.is_some())
660            .field("supervisor", &self.supervisor)
661            .field("subc_capabilities", &self.subc_capabilities)
662            .finish()
663    }
664}
665
666struct RouteOpenRequest {
667    target: RouteTarget,
668    identity: BindIdentity,
669    consumer_identity: Option<ConsumerIdentity>,
670    consumer_capabilities: Option<Vec<String>>,
671    role_versions: Option<BTreeMap<String, String>>,
672    busy_refusals: Option<bool>,
673    admission_facts: Option<serde_json::Value>,
674    scope: Option<ScopeSelector>,
675    accepts_close_reasons: Option<Vec<String>>,
676}
677
678#[derive(Clone, Copy)]
679enum RouteOpenPhase {
680    Admission,
681    ProjectRoot,
682    EgressReservation,
683    BindSend,
684    BindAckWait,
685}
686
687/// Store elapsed time for each route-open phase, including attempts that end
688/// in an early refusal or backend error. Admission also includes rechecks and
689/// commit bookkeeping performed between the other timed phases.
690struct RouteOpenTimings {
691    module_id: String,
692    principal: String,
693    admission: Duration,
694    project_root: Duration,
695    egress_reservation: Duration,
696    bind_send: Duration,
697    bind_ack_wait: Duration,
698    phase: Option<RouteOpenPhase>,
699    phase_started_at: Instant,
700}
701
702impl RouteOpenTimings {
703    fn new() -> Self {
704        Self {
705            module_id: String::new(),
706            // Refusals before attestation must not claim a verified principal.
707            principal: "unresolved".to_string(),
708            admission: Duration::ZERO,
709            project_root: Duration::ZERO,
710            egress_reservation: Duration::ZERO,
711            bind_send: Duration::ZERO,
712            bind_ack_wait: Duration::ZERO,
713            phase: Some(RouteOpenPhase::Admission),
714            phase_started_at: Instant::now(),
715        }
716    }
717
718    fn finish(&mut self) {
719        let elapsed = self.phase_started_at.elapsed();
720        match self.phase.take() {
721            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
722            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
723            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
724            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
725            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
726            None => {}
727        }
728    }
729
730    fn enter(&mut self, phase: RouteOpenPhase) {
731        self.finish();
732        self.phase = Some(phase);
733        self.phase_started_at = Instant::now();
734    }
735}
736
737struct RouteBindReservationGuard {
738    forwarding: Arc<ForwardingTable>,
739    endpoint: ModuleEndpointId,
740    relay_corr: u64,
741    armed: bool,
742}
743
744struct ModuleControlRpcGuard {
745    forwarding: Arc<ForwardingTable>,
746    endpoint: ModuleEndpointId,
747    corr: u64,
748    armed: bool,
749}
750
751impl ModuleControlRpcGuard {
752    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
753        Self {
754            forwarding,
755            endpoint,
756            corr,
757            armed: true,
758        }
759    }
760
761    fn disarm(&mut self) {
762        self.armed = false;
763    }
764}
765
766impl Drop for ModuleControlRpcGuard {
767    fn drop(&mut self) {
768        if self.armed {
769            let _ = self
770                .forwarding
771                .cancel_module_control_rpc(self.endpoint, self.corr);
772        }
773    }
774}
775
776impl RouteBindReservationGuard {
777    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
778        Self {
779            forwarding,
780            endpoint,
781            relay_corr,
782            armed: true,
783        }
784    }
785
786    fn release_and_disarm(&mut self) {
787        if !self.armed {
788            return;
789        }
790        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
791            self.endpoint,
792            self.relay_corr,
793            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
794        ) {
795            send_goodbye_target_best_effort(
796                &self.forwarding.counters(),
797                &target,
798                "canceled route.bind",
799            );
800        }
801        self.armed = false;
802    }
803
804    fn disarm(&mut self) {
805        self.armed = false;
806    }
807}
808
809impl Drop for RouteBindReservationGuard {
810    fn drop(&mut self) {
811        self.release_and_disarm();
812    }
813}
814
815/// Per-target-module circuit breaker around the `route.bind` relay.
816///
817/// The connection reader is serial per connection, so a module whose `on_bind`
818/// sits on the ack blocks every LATER frame on the connections that call it,
819/// including calls to unrelated modules. This does not make any module's bind
820/// fast; it stops the daemon paying the full budget again and again for a
821/// condition it has already observed.
822///
823/// State is keyed by TARGET MODULE and shared by every connection: a wedged
824/// module wedges everyone, so what one connection learned should protect the
825/// rest.
826///
827/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
828/// relay to that module has actually timed out, and is removed again when a
829/// relay is accepted or the module reconnects, so it cannot grow with traffic
830/// or with modules that behave.
831///
832/// # Why a `std` mutex here is not the head-of-line defect again
833///
834/// Acquisition never awaits. The critical section is a hash lookup plus a few
835/// integer updates, with no I/O and no `.await` inside it, so a reader task
836/// cannot be descheduled behind it the way it can behind
837/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
838/// primitive, held for the same kind of work, as the refusal counter this very
839/// path already increments.
840///
841/// It is also NOT on the data-plane splice path: only `route.open` and module
842/// registration touch it, so bound-route frames gain no state check and no
843/// contention.
844#[derive(Debug, Clone, Default)]
845pub(crate) struct RouteBindBreakers {
846    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
847}
848
849#[derive(Debug, Clone, Default)]
850pub(crate) struct RouteBindConcurrency {
851    modules: Arc<Mutex<HashMap<String, usize>>>,
852}
853
854struct RouteBindConcurrencyGuard {
855    concurrency: RouteBindConcurrency,
856    module_id: String,
857}
858
859impl RouteBindConcurrency {
860    /// Admit without waiting. Waiting here would move the bind stall from the
861    /// module reply to a semaphore and restore reader head-of-line blocking.
862    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
863        let mut modules = self
864            .modules
865            .lock()
866            .expect("route.bind concurrency mutex poisoned");
867        let in_flight = modules.entry(module_id.to_string()).or_default();
868        if *in_flight >= limit {
869            return Err(*in_flight);
870        }
871        *in_flight += 1;
872        Ok(RouteBindConcurrencyGuard {
873            concurrency: self.clone(),
874            module_id: module_id.to_string(),
875        })
876    }
877}
878
879impl Drop for RouteBindConcurrencyGuard {
880    fn drop(&mut self) {
881        let mut modules = self
882            .concurrency
883            .modules
884            .lock()
885            .expect("route.bind concurrency mutex poisoned");
886        let remove = {
887            let in_flight = modules
888                .get_mut(&self.module_id)
889                .expect("admitted route.bind has a concurrency entry");
890            *in_flight -= 1;
891            *in_flight == 0
892        };
893        if remove {
894            modules.remove(&self.module_id);
895        }
896    }
897}
898
899#[derive(Debug, Default)]
900struct ModuleBreakerState {
901    /// Relay timeouts observed with no accepted relay in between.
902    consecutive_timeouts: u32,
903    /// `Some` while the breaker is open: the instant the cooldown expires and
904    /// the next arrival may probe. `None` means closed.
905    cooldown_until: Option<Instant>,
906    /// A half-open probe has been admitted and has not settled yet. This is
907    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
908    /// that read the cooldown, so concurrent opens arriving at the moment the
909    /// cooldown expires cannot all decide that they are the probe.
910    probe_in_flight: Option<Arc<()>>,
911}
912
913/// What the breaker decided for one `route.open`, before any relay work.
914enum RouteBindAdmission<'a> {
915    Admitted {
916        guard: RouteBindBreakerGuard<'a>,
917        /// This open is the single half-open probe, so the transition is worth
918        /// one log line.
919        probe: bool,
920    },
921    Refused {
922        consecutive_timeouts: u32,
923        /// What is left of the cooldown. Zero when the refusal is because the
924        /// one probe is already in flight rather than because the cooldown has
925        /// not elapsed.
926        retry_in: Duration,
927        probe_in_flight: bool,
928    },
929}
930
931/// An outstanding admission, which must be told how its relay settled.
932///
933/// `Drop` settles it as inconclusive, so an early return between admission and
934/// the relay -- or the whole handler being cancelled when the client
935/// disconnects -- releases a half-open probe slot instead of leaving the
936/// breaker wedged half-open with no further probes.
937struct RouteBindBreakerGuard<'a> {
938    breakers: RouteBindBreakers,
939    module_id: &'a str,
940    probe_token: Option<Arc<()>>,
941    settled: bool,
942}
943
944impl RouteBindBreakerGuard<'_> {
945    /// The module answered within the budget and took the bind. THE ONLY
946    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
947    /// breaker, which is a transition worth logging.
948    fn record_accepted(&mut self) -> bool {
949        self.settled = true;
950        self.breakers.record_accepted(self.module_id)
951    }
952
953    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
954    /// COUNTS TOWARD OPENING.
955    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
956        self.settled = true;
957        self.breakers.record_timeout(
958            self.module_id,
959            self.probe_token.as_ref(),
960            threshold,
961            cooldown,
962        )
963    }
964
965    /// Everything else: the module REJECTED the bind, its connection went away
966    /// mid-relay, or the waiter was cancelled.
967    ///
968    /// None of these is evidence that a module is slow, and each already has
969    /// its own refusal with its own code. A module that rejects a bind in
970    /// microseconds is healthy and must never be convicted for it; a module
971    /// that died has said nothing about the module that replaces it. So these
972    /// neither increment nor reset the count -- they only release a probe slot.
973    fn record_inconclusive(&mut self) {
974        self.settled = true;
975        self.breakers
976            .record_inconclusive(self.module_id, self.probe_token.as_ref());
977    }
978}
979
980impl Drop for RouteBindBreakerGuard<'_> {
981    fn drop(&mut self) {
982        if !self.settled {
983            self.breakers
984                .record_inconclusive(self.module_id, self.probe_token.as_ref());
985        }
986    }
987}
988
989/// The breaker moved to open, reported so the caller can log it outside the
990/// lock. Opening is rare and load-bearing; the refusals that follow are
991/// frequent and are counted rather than logged.
992struct BreakerOpened {
993    consecutive_timeouts: u32,
994    /// True when a failed probe re-opened an already-open breaker, which reads
995    /// very differently in a log from a first opening.
996    reopened_after_probe: bool,
997}
998
999impl RouteBindBreakers {
1000    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
1001        self.modules
1002            .lock()
1003            .expect("route.bind breaker mutex poisoned")
1004    }
1005
1006    /// Decide whether this `route.open` may attempt its relay. Takes the map
1007    /// lock and nothing else, and never awaits.
1008    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
1009        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
1010            probe: probe_token.is_some(),
1011            guard: RouteBindBreakerGuard {
1012                breakers: self.clone(),
1013                module_id,
1014                probe_token,
1015                settled: false,
1016            },
1017        };
1018
1019        let mut modules = self.lock();
1020        let Some(state) = modules.get_mut(module_id) else {
1021            return admitted(None);
1022        };
1023        let Some(cooldown_until) = state.cooldown_until else {
1024            return admitted(None);
1025        };
1026        if state.probe_in_flight.is_some() {
1027            return RouteBindAdmission::Refused {
1028                consecutive_timeouts: state.consecutive_timeouts,
1029                retry_in: Duration::ZERO,
1030                probe_in_flight: true,
1031            };
1032        }
1033        let now = Instant::now();
1034        if now < cooldown_until {
1035            return RouteBindAdmission::Refused {
1036                consecutive_timeouts: state.consecutive_timeouts,
1037                retry_in: cooldown_until - now,
1038                probe_in_flight: false,
1039            };
1040        }
1041        let token = Arc::new(());
1042        state.probe_in_flight = Some(Arc::clone(&token));
1043        admitted(Some(token))
1044    }
1045
1046    fn record_accepted(&self, module_id: &str) -> bool {
1047        self.lock()
1048            .remove(module_id)
1049            .is_some_and(|state| state.cooldown_until.is_some())
1050    }
1051
1052    fn record_timeout(
1053        &self,
1054        module_id: &str,
1055        probe_token: Option<&Arc<()>>,
1056        threshold: u32,
1057        cooldown: Duration,
1058    ) -> Option<BreakerOpened> {
1059        let mut modules = self.lock();
1060        let state = modules.entry(module_id.to_string()).or_default();
1061        let was_open = state.cooldown_until.is_some();
1062        let was_probe = Self::owns_probe(state, probe_token);
1063        if was_probe {
1064            state.probe_in_flight = None;
1065        }
1066        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
1067        if state.consecutive_timeouts < threshold {
1068            return None;
1069        }
1070        state.cooldown_until = Some(Instant::now() + cooldown);
1071        Some(BreakerOpened {
1072            consecutive_timeouts: state.consecutive_timeouts,
1073            reopened_after_probe: was_open && was_probe,
1074        })
1075    }
1076
1077    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
1078        // A relay can finish after the breaker was reset or after it opened
1079        // again and started a new probe. Only the guard whose token matches the
1080        // active probe may release it, so a late relay never frees a newer probe.
1081        state
1082            .probe_in_flight
1083            .as_ref()
1084            .zip(token)
1085            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
1086    }
1087
1088    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
1089        if let Some(state) = self.lock().get_mut(module_id) {
1090            if Self::owns_probe(state, probe_token) {
1091                state.probe_in_flight = None;
1092            }
1093        }
1094    }
1095
1096    /// Discard what was learned about a module, because the process it was
1097    /// learned about is gone. Returns the discarded count when it was non-zero.
1098    ///
1099    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
1100    /// `module_id` is a configuration identity that outlives any particular
1101    /// child; what the breaker observed was the process behind the module
1102    /// connection of the moment. When a new connection registers under that id
1103    /// the verdict's subject no longer exists, so the verdict is stale by
1104    /// construction rather than merely likely to be wrong. Keeping it would
1105    /// apply a dead process's record to a live one, which is the same defect
1106    /// class this breaker exists to stop the daemon committing.
1107    ///
1108    /// A half-open probe in flight is discarded with the rest: it was a
1109    /// question about the old process.
1110    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
1111        self.lock()
1112            .remove(module_id)
1113            .map(|state| state.consecutive_timeouts)
1114            .filter(|discarded| *discarded > 0)
1115    }
1116
1117    /// Open breakers, for the `server.describe` counters object. `None` when
1118    /// none is open, so the key stays absent rather than present-and-empty.
1119    ///
1120    /// This is the operator's answer to "is this module refusing instantly or
1121    /// is it fine?", which look identical from a client that retries and then
1122    /// succeeds.
1123    fn open_snapshot(&self) -> Option<serde_json::Value> {
1124        let now = Instant::now();
1125        let modules = self.lock();
1126        let open = modules
1127            .iter()
1128            .filter_map(|(module_id, state)| {
1129                let cooldown_until = state.cooldown_until?;
1130                Some((
1131                    module_id.clone(),
1132                    serde_json::json!({
1133                        "consecutive_timeouts": state.consecutive_timeouts,
1134                        "cooldown_remaining_ms":
1135                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
1136                        "probe_in_flight": state.probe_in_flight.is_some(),
1137                    }),
1138                ))
1139            })
1140            .collect::<serde_json::Map<String, serde_json::Value>>();
1141        (!open.is_empty()).then_some(serde_json::Value::Object(open))
1142    }
1143}
1144
1145impl ControlHandler {
1146    pub(crate) fn install_registration_service(
1147        &self,
1148        router: std::sync::Weak<crate::Router>,
1149        auth: crate::server::ServerAuth,
1150    ) {
1151        self.supervisor.install_registration_service(router, auth);
1152    }
1153    pub fn new(registry: Arc<Registry>) -> Self {
1154        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
1155    }
1156
1157    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
1158        let counters = forwarding.counters();
1159        // Taken from the forwarding table rather than created here, so that the
1160        // breaker a `route.open` consults is the same one a module's
1161        // registration resets, however many handlers are built over one table.
1162        let route_bind_breakers = forwarding.route_bind_breakers();
1163        let route_bind_concurrency = forwarding.route_bind_concurrency();
1164        let route_outages = forwarding.route_outages();
1165        Self {
1166            registry,
1167            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
1168            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
1169            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1170            #[cfg(test)]
1171            activity_request_pause: Arc::new(Mutex::new(None)),
1172            #[cfg(test)]
1173            cleanup_pause: Arc::new(Mutex::new(None)),
1174            #[cfg(test)]
1175            after_nonce_attestation: Arc::new(Mutex::new(None)),
1176            #[cfg(test)]
1177            hello_ingress_pause: Arc::new(Mutex::new(None)),
1178            #[cfg(test)]
1179            agent_commands_pause: Arc::new(Mutex::new(None)),
1180            claims: Arc::new(claims::Claims::default()),
1181            config_runtime: None,
1182            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
1183            config_review_admission_is_default: true,
1184            activity: None,
1185            activity_streams: Arc::new(Mutex::new(HashMap::new())),
1186            activity_reservations: Default::default(),
1187            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
1188            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
1189            scope_streams: Arc::new(Mutex::new(HashMap::new())),
1190            forwarding,
1191            process_liveness: None,
1192            supervisor: SupervisorHandle::new(),
1193            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
1194                env!("CARGO_PKG_VERSION").to_owned(),
1195            )),
1196            agent_declarations: agent_commands::Queues::default(),
1197            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
1198            subc_capabilities: Arc::from([
1199                CAP_MANIFEST_REGISTRATION.to_string(),
1200                CAP_CHANNEL_LIFECYCLE.to_string(),
1201                CAP_PING_PONG.to_string(),
1202                CAP_SESSION_ATTACH.to_string(),
1203                CAP_ADMISSION_FACTS_RELAY.to_string(),
1204                CAP_SCOPES_V1.to_string(),
1205                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
1206                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
1207                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1208                PEER_BUILD_CAPABILITY.to_string(),
1209                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1210                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1211                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1212                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1213                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1214                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1215                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1216                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1217                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1218                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1219                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1220                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1221            ]),
1222            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1223            route_bind_relay_timeouts: BTreeMap::new(),
1224            route_bind_breakers,
1225            route_bind_concurrency,
1226            route_outages,
1227            route_refusal_log: Default::default(),
1228            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1229            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1230            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1231            storage_config: None,
1232            machine_id: None,
1233            admission_facts_carrier_module_id: None,
1234            admission_facts_targets: None,
1235            scopes: Arc::new(RwLock::new(ScopeTable::new(
1236                crate::daemon_config::default_scope_authority_owners(),
1237            ))),
1238            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1239            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1240            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1241            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1242            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1243            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1244            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1245            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1246            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1247            local_connections: Arc::new(Mutex::new(HashSet::new())),
1248            operator_app_policy: Default::default(),
1249            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1250            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1251            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1252            #[cfg(test)]
1253            app_open_test_platform: None,
1254            #[cfg(test)]
1255            app_open_test_launch: None,
1256            #[cfg(test)]
1257            config_review_test_reply: None,
1258            #[cfg(test)]
1259            recovery_exit_test_after_step: None,
1260            #[cfg(test)]
1261            recovery_exit_test_completed: None,
1262            #[cfg(test)]
1263            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1264            #[cfg(test)]
1265            recovery_exit_test_quiet_retry: false,
1266            #[cfg(test)]
1267            recovery_exit_test_retry_pause: None,
1268            #[cfg(test)]
1269            config_delivery_test_wakes: None,
1270            #[cfg(all(test, unix))]
1271            config_delivery_test_idle: None,
1272            #[cfg(windows)]
1273            windows_verify: None,
1274            #[cfg(windows)]
1275            windows_flash: None,
1276            #[cfg(windows)]
1277            windows_track: None,
1278            #[cfg(all(test, windows))]
1279            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1280            #[cfg(test)]
1281            caller_lookup: None,
1282            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1283            rescan: None,
1284            connected_clients: ConnectedClients::new(),
1285            local_endpoint_unavailable: None,
1286            counters,
1287            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1288            daemon_shutdown: DaemonShutdownFlag::default(),
1289            daemon_provenance: DaemonProvenanceFacts::default(),
1290            #[cfg(test)]
1291            control_dispatch_delay: None,
1292            #[cfg(test)]
1293            provenance_probe_override: None,
1294            #[cfg(test)]
1295            route_bind_relay_sent_hold: None,
1296            #[cfg(test)]
1297            hello_registry_to_forwarding_hold: None,
1298            #[cfg(test)]
1299            hello_ack_to_publication_hold: None,
1300            #[cfg(test)]
1301            hello_before_publication_hold: None,
1302            #[cfg(test)]
1303            hello_after_launch_check_hold: None,
1304            #[cfg(test)]
1305            hello_inside_publication_hold: None,
1306        }
1307    }
1308
1309    /// Set the central storage policy: registering modules then receive their
1310    /// resolved storage descriptor in HELLO_ACK.
1311    pub fn with_storage_config(
1312        mut self,
1313        storage_config: Option<crate::daemon_config::StorageConfig>,
1314    ) -> Self {
1315        self.storage_config = storage_config;
1316        self
1317    }
1318
1319    /// Open the ledger on its own writer thread; an unavailable sink does not
1320    /// prevent the daemon from serving routing or supervisor requests.
1321    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1322        self.activity = Some(crate::activity::ActivityLedger::open(
1323            run_dir.join("activity.jsonl"),
1324            incarnation,
1325        ));
1326        self.supervisor.set_activity(self.activity.clone());
1327        self
1328    }
1329
1330    /// Set the machine id served to every registering module (HELLO_ACK) and on
1331    /// `server.describe`.
1332    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1333        self.machine_id = machine_id;
1334        self
1335    }
1336
1337    /// Configure the exact reserved module and target ids permitted to relay
1338    /// opaque admission facts. Config-file loading validates this authority;
1339    /// this builder keeps the same policy available to embedded test daemons.
1340    pub fn with_admission_facts_config(
1341        mut self,
1342        carrier_module_id: Option<String>,
1343        targets: Option<Vec<String>>,
1344    ) -> Self {
1345        self.admission_facts_carrier_module_id = carrier_module_id;
1346        self.admission_facts_targets = targets;
1347        self
1348    }
1349
1350    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1351    /// Replaces the scope table with an empty one under the new list, so call it
1352    /// while building the handler, before any module can sync.
1353    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1354        self.scopes = Arc::new(RwLock::new(
1355            ScopeTable::new(owners.iter().cloned())
1356                .with_federated_owner(self.federated_scope_owner.clone()),
1357        ));
1358        self.scope_authority_owners = owners;
1359        self
1360    }
1361
1362    /// Set the exclusive federated owner while building the handler, before syncs.
1363    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1364        self.scopes = Arc::new(RwLock::new(
1365            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1366                .with_federated_owner(owner.clone()),
1367        ));
1368        self.federated_scope_owner = owner;
1369        self
1370    }
1371
1372    /// Set the startup policy before installing the rescan context or serving requests.
1373    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1374        self.privileged_operator_prompt = mode;
1375        self
1376    }
1377
1378    /// Override the route.bind relay timeout. Used by tests that assert the
1379    /// timeout path so they don't block on the production-safe default.
1380    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1381        self.route_bind_relay_timeout = timeout;
1382        self
1383    }
1384
1385    /// Install per-module route.bind relay budget overrides. A module id
1386    /// listed here wins over the daemon-wide default set via
1387    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1388    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1389    /// the same `Duration` the bind path will use.
1390    pub fn with_route_bind_relay_timeouts(
1391        mut self,
1392        timeouts: impl IntoIterator<Item = (String, Duration)>,
1393    ) -> Self {
1394        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1395        self
1396    }
1397
1398    /// Resolve the route.bind relay budget for a specific target module id.
1399    /// Per-module overrides win; the daemon-wide value (set via
1400    /// `with_route_bind_relay_timeout` or the built-in default) is the
1401    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1402    /// the same resolution `handle_route_open` will use.
1403    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1404        self.route_bind_relay_timeouts
1405            .get(module_id)
1406            .copied()
1407            .unwrap_or(self.route_bind_relay_timeout)
1408    }
1409
1410    /// Override the per-module bind-relay breaker policy.
1411    ///
1412    /// Used by tests, which cannot spend three production budgets opening a
1413    /// breaker or twenty seconds waiting for its cooldown. The production
1414    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1415    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1416    /// reasoning for the numbers.
1417    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1418        self.route_bind_breaker_threshold = threshold.max(1);
1419        self.route_bind_breaker_cooldown = cooldown;
1420        self
1421    }
1422
1423    #[cfg(test)]
1424    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1425        self.health_probe_timeout = timeout;
1426        self
1427    }
1428
1429    #[cfg(test)]
1430    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1431        self.control_dispatch_delay = Some(delay);
1432        self
1433    }
1434
1435    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1436    /// announce it is parked, once to be released. Build the barrier for two
1437    /// parties, the test being the other one.
1438    #[cfg(test)]
1439    pub(crate) fn with_route_bind_relay_sent_hold(
1440        mut self,
1441        hold: Arc<tokio::sync::Barrier>,
1442    ) -> Self {
1443        self.route_bind_relay_sent_hold = Some(hold);
1444        self
1445    }
1446
1447    /// A HELLO waits on `hold` twice between reserving its registry entry and
1448    /// installing its forwarding endpoint: once to announce it is parked, once
1449    /// to be released. Build the barrier for two parties, the test being the
1450    /// other one, and run the HELLO on a thread of its own.
1451    #[cfg(test)]
1452    pub(crate) fn with_hello_registry_to_forwarding_hold(
1453        mut self,
1454        hold: Arc<std::sync::Barrier>,
1455    ) -> Self {
1456        self.hello_registry_to_forwarding_hold = Some(hold);
1457        self
1458    }
1459
1460    #[cfg(test)]
1461    fn hold_between_registry_and_forwarding(&self) {
1462        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1463            hold.wait();
1464            hold.wait();
1465        }
1466    }
1467
1468    /// Park after the ACK is queued and forwarding is installed, until a test
1469    /// has read the ACK and issued a registry lookup from another connection.
1470    #[cfg(test)]
1471    fn hold_between_ack_and_publication(&self) {
1472        if let Some(hold) = &self.hello_ack_to_publication_hold {
1473            hold.wait();
1474            hold.wait();
1475        }
1476    }
1477
1478    #[cfg(all(test, unix))]
1479    pub(crate) fn with_hello_before_publication_hold(
1480        mut self,
1481        hold: Arc<std::sync::Barrier>,
1482    ) -> Self {
1483        self.hello_before_publication_hold = Some(hold);
1484        self
1485    }
1486
1487    #[cfg(all(test, unix))]
1488    pub(crate) fn with_hello_after_launch_check_hold(
1489        mut self,
1490        hold: Arc<std::sync::Barrier>,
1491    ) -> Self {
1492        self.hello_after_launch_check_hold = Some(hold);
1493        self
1494    }
1495
1496    #[cfg(all(test, unix))]
1497    pub(crate) fn with_hello_inside_publication_hold(
1498        mut self,
1499        hold: Arc<std::sync::Barrier>,
1500    ) -> Self {
1501        self.hello_inside_publication_hold = Some(hold);
1502        self
1503    }
1504
1505    pub fn with_process_liveness(
1506        mut self,
1507        process_liveness: Arc<dyn ModuleProcessLiveness>,
1508    ) -> Self {
1509        self.process_liveness = Some(process_liveness);
1510        self
1511    }
1512
1513    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1514        self.supervisor = supervisor;
1515        if let Some(owner) = &self.config_runtime {
1516            self.supervisor.install_binding_retirement(owner);
1517        }
1518        self.supervisor.set_activity(self.activity.clone());
1519        self
1520    }
1521
1522    pub fn with_daemon_provenance(
1523        mut self,
1524        pid: u32,
1525        started_at_ms: u64,
1526        executable_path: Option<PathBuf>,
1527        build_git_sha: Option<String>,
1528        build_lock_digest: Option<String>,
1529    ) -> Self {
1530        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1531        let process_start_time = process_start_time(pid);
1532        self.daemon_provenance = DaemonProvenanceFacts {
1533            build: DaemonBuildProvenance {
1534                build_git_sha,
1535                build_lock_digest,
1536            },
1537            pid: Some(pid),
1538            started_at_ms: Some(started_at_ms),
1539            start_clock: None,
1540            executable_path,
1541            executable_identity,
1542            process_start_time,
1543            probe: ExecutableIdentityProbe::default(),
1544        };
1545        self
1546    }
1547
1548    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1549        self.daemon_provenance.start_clock = Some(clock);
1550        self
1551    }
1552
1553    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1554    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1555        self.scopes
1556            .write()
1557            .unwrap_or_else(|poisoned| poisoned.into_inner())
1558            .set_wall_clock(Arc::new(clock));
1559        self
1560    }
1561
1562    #[cfg(test)]
1563    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1564        self.provenance_probe_override = Some(result);
1565        self
1566    }
1567
1568    /// Install the configured module set and its reserved capability bindings.
1569    /// Bindings are configuration-scoped and may point at a provider that has not
1570    /// been installed yet, so this does not require the bound module to exist.
1571    pub fn with_capability_config(
1572        self,
1573        modules: impl IntoIterator<Item = (String, bool)>,
1574        reserved_capabilities: BTreeMap<String, String>,
1575    ) -> Self {
1576        self.capability_evaluator
1577            .configure(modules, reserved_capabilities);
1578        self
1579    }
1580
1581    /// Share the supervisor's daemon-shutdown flag with this handler, so
1582    /// requirement changes after the daemon has begun its announced shutdown
1583    /// are not reported as faults.
1584    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1585        self.daemon_shutdown = flag;
1586        self
1587    }
1588
1589    pub fn with_supervisor_rescan(
1590        mut self,
1591        supervisor: Supervisor,
1592        config_path: impl Into<PathBuf>,
1593        configured_port: Option<u16>,
1594    ) -> Self {
1595        self.rescan = Some(SupervisorRescanContext {
1596            supervisor,
1597            config_path: config_path.into(),
1598            configured_port,
1599            storage_config: self.storage_config.clone(),
1600            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1601            admission_facts_targets: self.admission_facts_targets.clone(),
1602            scope_authority_owners: self.scope_authority_owners.clone(),
1603            federated_scope_owner: self.federated_scope_owner.clone(),
1604            privileged_operator_prompt: self.privileged_operator_prompt,
1605            generation: Arc::default(),
1606            rescan_lock: Arc::default(),
1607            module_entries: Arc::default(),
1608        });
1609        self
1610    }
1611
1612    pub(crate) fn with_supervisor_rescan_entries(
1613        self,
1614        modules: &[crate::daemon_config::ConfiguredModule],
1615    ) -> Self {
1616        if let Some(context) = &self.rescan {
1617            let mut entries = context
1618                .module_entries
1619                .lock()
1620                .unwrap_or_else(|e| e.into_inner());
1621            entries.seed(modules);
1622        }
1623        self
1624    }
1625
1626    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1627        self.connected_clients = connected_clients;
1628        self
1629    }
1630
1631    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1632    /// an operator can see a bind failure without reading the daemon log.
1633    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1634        self.local_endpoint_unavailable = reason;
1635        self
1636    }
1637
1638    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1639        Arc::clone(&self.forwarding)
1640    }
1641
1642    pub(crate) fn counters(&self) -> DaemonCounters {
1643        self.counters.clone()
1644    }
1645
1646    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1647    /// requirement event without depending on an operator polling a status command.
1648    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1649        let handler = Arc::downgrade(&self);
1650        let evaluator = self.capability_evaluator.clone();
1651        tokio::spawn(async move {
1652            loop {
1653                evaluator.wait_for_change_or_deadline().await;
1654                let Some(handler) = handler.upgrade() else {
1655                    break;
1656                };
1657                handler.refresh_capability_requirements();
1658            }
1659        });
1660    }
1661
1662    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1663    /// deadline passed during sleep is enforced on the first tick after wake.
1664    /// While no live scope carries a deadline the loop waits for an accepted
1665    /// scope change instead of ticking, so a daemon without deadlines never
1666    /// wakes for expiry.
1667    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1668        let context = scope_expiry::ScopeExpiryContext::new(&self);
1669        let deadline_added = self.scope_deadline_added.clone();
1670        tokio::spawn(async move {
1671            loop {
1672                if !context.has_deadlines() {
1673                    deadline_added.notified().await;
1674                    continue;
1675                }
1676                tokio::time::sleep(Duration::from_secs(1)).await;
1677                if let Err(error) = context.sweep() {
1678                    warn!(%error, "scope expiry sweep failed");
1679                }
1680            }
1681        });
1682    }
1683
1684    #[cfg(test)]
1685    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1686        scope_expiry::ScopeExpiryContext::new(self).sweep()
1687    }
1688
1689    fn publish_scope_changes(
1690        &self,
1691        changes: &[crate::scopes::ScopeTagChange],
1692        expired: &[crate::scopes::ScopeExpired],
1693    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1694        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1695    }
1696
1697    fn runtime_capability_snapshot(
1698        &self,
1699    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1700        let runtime = self
1701            .supervisor
1702            .list()
1703            .into_iter()
1704            .map(|module| {
1705                let status = module.status().map_err(|err| {
1706                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1707                })?;
1708                Ok(RuntimeModule {
1709                    module_id: status.module_id,
1710                    state: status.state,
1711                    enabled: status.enabled,
1712                })
1713            })
1714            .collect::<Result<Vec<_>, RouterError>>()?;
1715        // Include every registration, published or not. The capability
1716        // evaluator counts a module as providing its capabilities as soon as it
1717        // has registered, even before `catalog.list` shows it, so a HELLO in
1718        // progress does not change other modules' required-capability
1719        // verdicts. See `Registry::list_registered_modules`.
1720        let registrations = self.registry.list_registered_modules().map_err(|err| {
1721            RouterError::backend(
1722                0,
1723                0,
1724                format!("failed to list capability registrations: {err}"),
1725            )
1726        })?;
1727        let registrations = registrations
1728            .into_iter()
1729            .map(|registration| RegisteredModule {
1730                module_id: registration.manifest.module_id,
1731                module_version: registration.manifest.module_version,
1732                capabilities: registration.manifest.capabilities,
1733            })
1734            .collect();
1735        Ok((runtime, registrations))
1736    }
1737
1738    /// The capability side effects of a module becoming the active registration
1739    /// for its id: cache its manifest (logging how it differs from the cached
1740    /// one), run the deny census when its declarations call for one, and recompute the
1741    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1742    /// candidate's does not, and the supervisor does it at promotion instead,
1743    /// through [`crate::supervise::SwapPromotionObserver`].
1744    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1745        let cached_registration = RegisteredModule {
1746            module_id: registration.manifest.module_id.clone(),
1747            module_version: registration.manifest.module_version.clone(),
1748            capabilities: registration.manifest.capabilities.clone(),
1749        };
1750        let change = self.capability_evaluator.record_hello(&cached_registration);
1751        log_manifest_change(&cached_registration.module_id, &change);
1752        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1753            self.enforce_capability_denies();
1754        }
1755        self.refresh_capability_requirements();
1756    }
1757
1758    /// Point the shared supervisor handle at this handler for swap promotions.
1759    /// Called wherever a handler is put behind the `Arc` the router serves, so
1760    /// it can be held weakly.
1761    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1762        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1763            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1764        self.supervisor.set_swap_promotion_observer(observer);
1765    }
1766
1767    pub fn refresh_capability_requirements(&self) {
1768        match self.runtime_capability_snapshot() {
1769            Ok((runtime, registrations)) => {
1770                let events = self
1771                    .capability_evaluator
1772                    .evaluate_now(&runtime, &registrations);
1773                if !events.is_empty() {
1774                    self.catalog_readiness_revision
1775                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1776                }
1777                log_requirement_events(events, &self.daemon_shutdown);
1778            }
1779            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1780        }
1781    }
1782
1783    /// Why a registered module is not accepting new route binds, or `None` when
1784    /// it is. This is the module's effective readiness: its declared readiness
1785    /// first, then every `need: required` capability it declares evaluating to
1786    /// `provided`. `route.open` and `catalog.list` both read it here so the
1787    /// catalog never reports a module routable that `route.open` would refuse.
1788    fn not_ready_reason(
1789        &self,
1790        registration: &crate::registry::ModuleRegistration,
1791    ) -> Option<NotReadyReason> {
1792        if !registration.ready {
1793            return Some(NotReadyReason {
1794                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1795                capability: None,
1796            });
1797        }
1798        self.first_unprovided_required_capability(registration)
1799            .map(|capability| NotReadyReason {
1800                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1801                capability: Some(capability),
1802            })
1803    }
1804
1805    /// The lexicographically first capability this registration declares
1806    /// `need: required` whose evaluator verdict is not `provided`.
1807    ///
1808    /// The verdicts are the capability evaluator's own; nothing here decides
1809    /// what "provided" means. The evaluator counts a capability provided as
1810    /// soon as a module claiming it has REGISTERED, not once that module is
1811    /// ready. That distinction is what keeps two modules that require each
1812    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1813    /// is ready", each would wait for the other to become ready first and
1814    /// neither ever would. Do not tighten it to readiness.
1815    ///
1816    /// A required capability with no verdict at all means this registration's
1817    /// HELLO or catalog.update landed after the last recompute; recompute once
1818    /// rather than let a missing verdict read as either answer. If it is still
1819    /// missing (the recompute itself failed) the capability counts as
1820    /// unprovided: the refusal is retryable, and routing a module whose
1821    /// required provider is unknown is the outcome this check exists to stop.
1822    fn first_unprovided_required_capability(
1823        &self,
1824        registration: &crate::registry::ModuleRegistration,
1825    ) -> Option<String> {
1826        self.first_unprovided_required_capability_for(
1827            &registration.manifest.module_id,
1828            registration.manifest.capabilities.as_ref(),
1829        )
1830    }
1831
1832    fn first_unprovided_required_capability_for(
1833        &self,
1834        module_id: &str,
1835        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1836    ) -> Option<String> {
1837        let required = capabilities
1838            .into_iter()
1839            .flat_map(|declarations| declarations.requires.iter())
1840            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1841            .map(|requirement| requirement.capability.as_str())
1842            .collect::<BTreeSet<_>>();
1843        if required.is_empty() {
1844            return None;
1845        }
1846        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1847        if required
1848            .iter()
1849            .any(|capability| verdict(capability).is_none())
1850        {
1851            self.refresh_capability_requirements();
1852        }
1853        required
1854            .into_iter()
1855            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1856            .map(str::to_string)
1857    }
1858
1859    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1860        self.capability_evaluator
1861            .statuses()
1862            .into_iter()
1863            .map(RequirementStatus::into_wire)
1864            .collect()
1865    }
1866
1867    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1868    /// registration-release watch. The signal is what the supervisor waits on
1869    /// before spawning a replacement, so it must only fire once forwarding
1870    /// teardown is also done (see [`Self::cleanup_connection`] /
1871    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1872    /// registry-only path below because publication already owns the spawn lock.
1873    fn deregister_connection(
1874        &self,
1875        connection_id: ConnectionId,
1876        reason: RegistrationEndReason,
1877    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1878        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1879            spawn.end_primary_registration();
1880        }
1881        self.registry
1882            .deregister_connection_with_reason(connection_id, reason)
1883    }
1884
1885    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1886    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1887    // or claim-bound consumers to revoke. Remove only its unpublished registry
1888    // entry without re-entering primary-registration teardown.
1889    fn rollback_unpublished_hello(
1890        &self,
1891        connection: ConnectionId,
1892    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1893        self.registry.deregister_connection_with_reason(
1894            connection,
1895            RegistrationEndReason::RegistrationFailed,
1896        )
1897    }
1898
1899    fn request_refusal_close(
1900        &self,
1901        connection: ConnectionId,
1902        sink: Option<&crate::FrameSink>,
1903        reason: CloseReason,
1904    ) {
1905        if let Some(sink) = sink {
1906            sink.terminate_ingress();
1907        }
1908        if self.claims.close_notifications_enabled() {
1909            self.forwarding.request_connection_close(connection, reason);
1910        }
1911    }
1912
1913    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
1914        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
1915            return None;
1916        }
1917        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
1918            parse_client_control_request(&frame.body)
1919        else {
1920            return None;
1921        };
1922        Some(target_module_id(&target).to_string())
1923    }
1924
1925    pub(crate) fn route_open_capacity_refusal(
1926        &self,
1927        ctx: &RouteCtx,
1928        frame: &Frame,
1929        target_module_id: &str,
1930        in_flight: usize,
1931        limit: usize,
1932    ) -> Result<Frame, RouterError> {
1933        // Sent before the request reaches `handle_route_open`, so the caller
1934        // fields come from the raw frame here.
1935        let caller = self.route_open_caller_from_frame(ctx, frame);
1936        self.route_open_admission_refusal_frame(
1937            ctx,
1938            &caller,
1939            frame,
1940            target_module_id,
1941            "open_admission_full",
1942            (in_flight, limit),
1943            format!(
1944                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
1945            ),
1946        )
1947    }
1948
1949    fn route_open_target_capacity_refusal(
1950        &self,
1951        ctx: &RouteCtx,
1952        caller: &RouteOpenCaller,
1953        frame: &Frame,
1954        target_module_id: &str,
1955        in_flight: usize,
1956    ) -> Result<Frame, RouterError> {
1957        self.route_open_admission_refusal_frame(
1958            ctx,
1959            caller,
1960            frame,
1961            target_module_id,
1962            "target_binds_full",
1963            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
1964            format!(
1965                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
1966            ),
1967        )
1968    }
1969
1970    /// Admission pressure clears as existing binds settle, so its refusal must
1971    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
1972    /// `module_reloading`, `module_warming`, `target_unavailable`, or
1973    /// `module_timeout`. `target_unavailable` is honest for an attempt that
1974    /// cannot currently reach its target; `module_timeout` would falsely claim
1975    /// that a wait expired. A new, cleaner code would be terminal to deployed
1976    /// clients, so it requires a client-tolerance rollout before daemon emission.
1977    #[allow(clippy::too_many_arguments)]
1978    fn route_open_admission_refusal_frame(
1979        &self,
1980        ctx: &RouteCtx,
1981        caller: &RouteOpenCaller,
1982        frame: &Frame,
1983        target_module_id: &str,
1984        reason: &'static str,
1985        (in_flight, limit): (usize, usize),
1986        message: impl Into<String>,
1987    ) -> Result<Frame, RouterError> {
1988        let code = error_codes::TARGET_UNAVAILABLE;
1989        self.counters.increment_route_open_refused(code);
1990        info!(
1991            target: "control",
1992            code,
1993            reason,
1994            module_id = ?target_module_id,
1995            connection_id = ctx.connection_id.get(),
1996            principal = %caller.principal,
1997            scope = %caller.scope,
1998            harness = %caller.harness,
1999            in_flight,
2000            limit,
2001            "route.open refused"
2002        );
2003        control_error_frame(frame, code, message.into())
2004    }
2005
2006    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
2007    ///
2008    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
2009    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
2010    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
2011    #[cfg(test)]
2012    pub fn handle_control(
2013        &self,
2014        connection_id: ConnectionId,
2015        frame: Frame,
2016    ) -> Result<Vec<Frame>, RouterError> {
2017        match frame.header.ty {
2018            FrameType::Ping => Ok(vec![pong(&frame)?]),
2019            FrameType::Hello => self.handle_hello(connection_id, None, frame),
2020            FrameType::Goodbye => self.handle_goodbye(connection_id),
2021            ty => Ok(vec![control_error_frame(
2022                &frame,
2023                "unsupported_control_frame",
2024                format!("unsupported channel-0 frame {ty:?}"),
2025            )?]),
2026        }
2027    }
2028
2029    pub async fn handle_control_frame(
2030        &self,
2031        ctx: &RouteCtx,
2032        frame: Frame,
2033    ) -> Result<Vec<Frame>, RouterError> {
2034        self.handle_control_frame_timed(ctx, frame, None).await
2035    }
2036
2037    #[cfg(any(test, feature = "test-support"))]
2038    pub fn with_test_operator_app_policy(
2039        mut self,
2040        policy: crate::operator_apps::TestOperatorAppPolicy,
2041    ) -> Self {
2042        self.operator_app_policy = policy.into();
2043        self
2044    }
2045
2046    /// Inject the Windows signature check for tests. The injected check
2047    /// answers the verified version string or the rejection reason; the
2048    /// daemon enforces the floor itself on the returned version.
2049    #[cfg(all(windows, any(test, feature = "test-support")))]
2050    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
2051        self.windows_verify = Some(verify);
2052        self
2053    }
2054
2055    /// Record which pids the daemon would flash for `already_running`.
2056    #[cfg(all(windows, any(test, feature = "test-support")))]
2057    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
2058        self.windows_flash = Some(flash);
2059        self
2060    }
2061
2062    /// Inject a tracking failure for tests: makes `track_launched_process`
2063    /// fail so a test can prove a launch that cannot be tracked is stopped,
2064    /// never left running.
2065    #[cfg(all(windows, any(test, feature = "test-support")))]
2066    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2067        self.windows_track = Some(track);
2068        self
2069    }
2070
2071    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2072        self.local_connections
2073            .lock()
2074            .unwrap_or_else(|p| p.into_inner())
2075            .insert(connection);
2076    }
2077
2078    // Keep the connection-level delivery decision shared with route.bind. The
2079    // target's capability opt-in is separate from recognition of the caller.
2080    fn connection_operator_app(
2081        &self,
2082        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2083    ) -> Option<subc_protocol::peer::OperatorApp> {
2084        stamp
2085            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2086            .map(|stamp| stamp.app.clone())
2087    }
2088
2089    pub(crate) fn record_observed_peer(
2090        &self,
2091        connection: ConnectionId,
2092        peer: subc_os::local_peer::ObservedPeer,
2093    ) {
2094        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2095        let peer = match peer {
2096            OsPeer::Unobserved => ObservedPeer::unobserved(),
2097            OsPeer::Observed(peer) => {
2098                let observed = match peer.user {
2099                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2100                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2101                };
2102                observed
2103                    .with_exe(
2104                        peer.exe
2105                            .and_then(|path| path.into_os_string().into_string().ok()),
2106                    )
2107                    .with_signing_id(peer.signing_id)
2108            }
2109        };
2110        self.observed_peers
2111            .lock()
2112            .unwrap_or_else(|p| p.into_inner())
2113            .insert(connection, peer);
2114    }
2115
2116    pub(crate) fn record_caller_endpoints(
2117        &self,
2118        connection: ConnectionId,
2119        endpoints: Option<(SocketAddr, SocketAddr)>,
2120    ) {
2121        let mut callers = self
2122            .caller_endpoints
2123            .lock()
2124            .unwrap_or_else(|p| p.into_inner());
2125        callers.remove(&connection);
2126        if let Some(endpoints) = endpoints {
2127            callers.insert(connection, endpoints);
2128        }
2129    }
2130
2131    #[cfg(test)]
2132    pub(crate) fn with_caller_lookup_for_test(
2133        mut self,
2134        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2135    ) -> Self {
2136        self.caller_lookup = Some(Arc::new(lookup));
2137        self
2138    }
2139
2140    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2141        let endpoints = self
2142            .caller_endpoints
2143            .lock()
2144            .unwrap_or_else(|p| p.into_inner())
2145            .get(&connection)
2146            .copied();
2147        #[cfg(test)]
2148        let lookup = self.caller_lookup.clone();
2149        tokio::task::spawn_blocking(move || {
2150            #[cfg(test)]
2151            if let Some(lookup) = lookup {
2152                return lookup(endpoints);
2153            }
2154            endpoints
2155                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2156                .unwrap_or_default()
2157        })
2158        .await
2159        .unwrap_or_default()
2160    }
2161
2162    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2163        frame.header.channel == 0
2164            && frame.header.ty == FrameType::Request
2165            && self
2166                .forwarding
2167                .module_endpoint_for_connection(ctx.connection_id)
2168                .is_ok_and(|endpoint| endpoint.is_none())
2169            && parse_client_control_request(&frame.body)
2170                .ok()
2171                .is_some_and(|request| privileged_operation(&request).is_some())
2172    }
2173
2174    pub(crate) async fn handle_control_frame_timed(
2175        &self,
2176        ctx: &RouteCtx,
2177        frame: Frame,
2178        dispatch_started_at: Option<StdInstant>,
2179    ) -> Result<Vec<Frame>, RouterError> {
2180        let first = ctx.egress.first_ingress_frame();
2181        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2182            .await
2183    }
2184
2185    pub(crate) async fn handle_control_frame_ingress(
2186        &self,
2187        ctx: &RouteCtx,
2188        frame: Frame,
2189        dispatch_started_at: Option<StdInstant>,
2190        first: bool,
2191    ) -> Result<Vec<Frame>, RouterError> {
2192        if ctx.egress.ingress_terminal() {
2193            return Ok(Vec::new());
2194        }
2195        #[cfg(test)]
2196        self.claims.record_dispatch(frame.header.corr);
2197        let claim_binding = self.claims.binding(ctx.connection_id);
2198        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2199            && claim_binding
2200                .as_ref()
2201                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2202        .then(|| self.prefix_hello_attempt(ctx));
2203        if claim_binding
2204            .as_ref()
2205            .is_some_and(|binding| binding.prefix_module_id().is_some())
2206        {
2207            let registered = self
2208                .forwarding
2209                .module_endpoint_for_connection(ctx.connection_id)
2210                .map_err(RouterError::Forwarding)?
2211                .is_some();
2212            if !registered && frame.header.ty != FrameType::Hello {
2213                return self
2214                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2215                    .await;
2216            }
2217            if registered && frame.header.ty == FrameType::Goodbye {
2218                ctx.egress.terminate_ingress();
2219                let result = self.handle_goodbye(ctx.connection_id);
2220                self.claims.connection_closed(ctx.connection_id);
2221                self.request_refusal_close(
2222                    ctx.connection_id,
2223                    Some(&ctx.egress),
2224                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2225                );
2226                return result;
2227            }
2228            if registered && frame.header.ty == FrameType::Request {
2229                let allowed =
2230                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2231                        matches!(
2232                            probe.op.as_str(),
2233                            "catalog.update"
2234                                | "catalog.update_role_declarations"
2235                                | "scope.describe"
2236                                | "scope.watch"
2237                                | "supervisor.live_roots"
2238                                | "activity.record"
2239                        )
2240                    });
2241                if !allowed {
2242                    return Ok(vec![control_error_frame(
2243                        &frame,
2244                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2245                        "prefix registrations have only brokered module operations",
2246                    )?]);
2247                }
2248            }
2249            if registered
2250                && frame.header.ty == FrameType::Push
2251                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2252                    .is_ok_and(|probe| probe.op == "route.status")
2253            {
2254                return Ok(vec![control_error_frame(
2255                    &frame,
2256                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2257                    "prefix registrations may push only route.status for routes they serve",
2258                )?]);
2259            }
2260        }
2261        match frame.header.ty {
2262            FrameType::Ping => Ok(vec![pong(&frame)?]),
2263            FrameType::Hello => {
2264                if claim_binding
2265                    .as_ref()
2266                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2267                {
2268                    return self
2269                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2270                        .await;
2271                }
2272                // Resolved once, here: the blocking HELLO below may outlive this
2273                // reader and run after cleanup has forgotten the channel, and it
2274                // must still be judged as this channel's HELLO.
2275                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2276                if let Some(spawn) = &channel_spawn {
2277                    spawn.wait_launch().await;
2278                    // Refused launches close the channel. Leave their pending
2279                    // HELLO unanswered instead of racing a reply against shutdown.
2280                    if !spawn.launch_ready() {
2281                        ctx.egress.terminate_ingress();
2282                        return Ok(Vec::new());
2283                    }
2284                    #[cfg(test)]
2285                    self.pause_hello_ingress_for_test().await;
2286                } else if claim_binding.is_none() {
2287                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2288                        if let (Some(module), Some(nonce)) = (
2289                            hello
2290                                .get("manifest")
2291                                .and_then(|value| value.get("module_id"))
2292                                .and_then(|value| value.as_str()),
2293                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2294                        ) {
2295                            if !self
2296                                .config_runtime
2297                                .as_ref()
2298                                .is_some_and(|owner| owner.module_is_gated(module))
2299                                && !self.supervisor.wait_program_binding(module, nonce).await
2300                            {
2301                                self.request_refusal_close(
2302                                    ctx.connection_id,
2303                                    Some(&ctx.egress),
2304                                    CloseReason::new(
2305                                        "program_refused",
2306                                        "the spawned program binding failed",
2307                                    ),
2308                                );
2309                                return Ok(vec![control_error_frame(
2310                                    &frame,
2311                                    if self
2312                                        .config_runtime
2313                                        .as_ref()
2314                                        .is_some_and(|owner| owner.is_recovering())
2315                                    {
2316                                        "config_gated"
2317                                    } else {
2318                                        "program_refused"
2319                                    },
2320                                    "the spawned program binding failed",
2321                                )?]);
2322                            }
2323                        }
2324                    }
2325                }
2326                let handler = self.clone();
2327                let connection = ctx.connection_id;
2328                let egress = ctx.egress.clone();
2329                let correlation = frame.header.corr;
2330                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2331                let span = tracing::Span::current();
2332                let hello_binding = claim_binding.clone();
2333                let replies = tokio::task::spawn_blocking(move || {
2334                    tracing::dispatcher::with_default(&dispatcher, || {
2335                        span.in_scope(|| {
2336                            handler.handle_hello_checked(
2337                                connection,
2338                                Some(egress),
2339                                frame,
2340                                true,
2341                                hello_binding,
2342                                channel_spawn,
2343                            )
2344                        })
2345                    })
2346                })
2347                .await
2348                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2349                #[cfg(test)]
2350                if prefix_attempt.is_some() {
2351                    self.claims.pause_prefix_commit_for_test(false).await;
2352                }
2353                if let Some(attempt) = &mut prefix_attempt {
2354                    let accepted = !replies
2355                        .iter()
2356                        .any(|reply| reply.header.ty == FrameType::Error)
2357                        && self
2358                            .registry
2359                            .get_module_by_connection(ctx.connection_id)
2360                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2361                            .is_some();
2362                    if accepted {
2363                        attempt.accepted = true;
2364                    } else {
2365                        ctx.egress.terminate_ingress();
2366                        for reply in replies {
2367                            ctx.egress.send_flushed(reply).await?;
2368                        }
2369                        return Ok(Vec::new());
2370                    }
2371                }
2372                Ok(replies)
2373            }
2374            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2375            FrameType::Cancel => {
2376                // Channel-0 cancellation withdraws approvals and subscriptions
2377                // and fences pending agent declarations;
2378                // successful cancellation has no ordinary reply.
2379                // A config Apply may also own an OS prompt. Cancel that prompt
2380                // before config cancellation can report the request handled.
2381                if self
2382                    .agent_declarations
2383                    .cancel(ctx.connection_id, frame.header.corr)
2384                    || self
2385                        .forwarding
2386                        .operator_confirms()
2387                        .cancel(ctx.connection_id, frame.header.corr)
2388                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2389                    || self
2390                        .supervisor
2391                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2392                    || self.cancel_activity_subscription(ctx, &frame)?
2393                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2394                    || self
2395                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2396                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2397                {
2398                    Ok(Vec::new())
2399                } else {
2400                    Ok(vec![control_error_frame(
2401                        &frame,
2402                        "unknown_subscription",
2403                        "no subscription has this correlation id",
2404                    )?])
2405                }
2406            }
2407            FrameType::Request => {
2408                // This additive operation is not part of the existing exhaustive
2409                // module-control enum. Probe the op before decoding that enum.
2410                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2411                if let Some(probe) = &op {
2412                    self.record_control_usage(ctx.connection_id, &probe.op);
2413                }
2414                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2415                if let Some(refusal) = self
2416                    .recovery_request_refusal(
2417                        ctx,
2418                        &frame,
2419                        op.as_ref().map(|probe| probe.op.as_str()),
2420                    )
2421                    .await?
2422                {
2423                    if claim_present {
2424                        self.reclaim_presented_expiry(&frame);
2425                        return self
2426                            .refuse_claim_connection(ctx, &frame, "config_gated")
2427                            .await;
2428                    }
2429                    return Ok(vec![refusal]);
2430                }
2431                if claim_present {
2432                    return self.handle_claim_present(ctx, &frame, first).await;
2433                }
2434                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2435                    return self.handle_claim_mint(ctx, &frame).await;
2436                }
2437                if let Some(refusal) = self.registration_operation_refusal(
2438                    ctx,
2439                    &frame,
2440                    op.as_ref().map(|probe| probe.op.as_str()),
2441                )? {
2442                    return Ok(vec![refusal]);
2443                }
2444                if op
2445                    .as_ref()
2446                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2447                {
2448                    return self.handle_catalog_watch(ctx, frame);
2449                }
2450                if op
2451                    .as_ref()
2452                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2453                {
2454                    return self.handle_scope_watch(ctx, frame);
2455                }
2456                if op
2457                    .as_ref()
2458                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2459                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2460                        .unwrap_or(false)
2461                {
2462                    return Ok(vec![control_error_frame(
2463                        &frame,
2464                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2465                        "provider_declarations are fixed at HELLO; restart the module to change them",
2466                    )?]);
2467                }
2468                if let Some(probe) = op
2469                    .as_ref()
2470                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2471                {
2472                    return self
2473                        .handle_module_config_request(ctx, frame, &probe.op)
2474                        .await;
2475                }
2476                if op
2477                    .as_ref()
2478                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2479                {
2480                    return self.handle_config_gate_request(ctx, frame).await;
2481                }
2482                if op
2483                    .as_ref()
2484                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2485                {
2486                    return self.handle_activity_record(ctx, frame).await;
2487                }
2488                if op.as_ref().is_some_and(|probe| {
2489                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2490                }) {
2491                    // A refusal and a CANCEL that won must not both end the stream.
2492                    let key = (ctx.connection_id, frame.header.corr);
2493                    let replies = self.handle_activity_read(ctx, frame).await?;
2494                    return Ok(self.activity_reservations.settle(key, replies));
2495                }
2496                if op
2497                    .as_ref()
2498                    .is_some_and(|probe| probe.op == "operator.confirm")
2499                {
2500                    return self.handle_operator_confirm(ctx, frame).await;
2501                }
2502                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2503                    return self
2504                        .observe_control_wait(
2505                            ctx,
2506                            None,
2507                            ops::APP_OPEN,
2508                            self.handle_app_open(ctx, frame),
2509                        )
2510                        .await;
2511                }
2512                if op
2513                    .as_ref()
2514                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2515                {
2516                    return self.handle_connection_describe(ctx, frame).await;
2517                }
2518                if op
2519                    .as_ref()
2520                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2521                {
2522                    return self.handle_scope_served_by(ctx.connection_id, frame);
2523                }
2524                if self
2525                    .forwarding
2526                    .module_endpoint_for_connection(ctx.connection_id)
2527                    .map_err(RouterError::Forwarding)?
2528                    .is_some()
2529                {
2530                    if !is_known_module_request_op(&frame.body) {
2531                        return Ok(vec![control_error_frame(
2532                            &frame,
2533                            "unsupported_control_frame",
2534                            "module-originated channel-0 REQUEST is not supported",
2535                        )?]);
2536                    }
2537                    let request = match parse_module_control_request_from_module(&frame.body) {
2538                        Ok(request) => request,
2539                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2540                            return Ok(vec![control_error_frame(
2541                                &frame,
2542                                "unsupported_control_frame",
2543                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2544                            )?])
2545                        }
2546                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2547                            return Ok(vec![control_error_frame(
2548                                &frame,
2549                                "invalid_control_body",
2550                                format!("malformed module control body: {err}"),
2551                            )?])
2552                        }
2553                    };
2554                    let op = module_control_request_op(&request);
2555                    let corr = frame.header.corr;
2556                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2557                    if let ModuleControlRequestFromModule::AgentCommands {
2558                        started,
2559                        finished,
2560                        known,
2561                    } = request
2562                    {
2563                        return self
2564                            .agent_declarations
2565                            .enqueue(
2566                                self,
2567                                ctx,
2568                                frame,
2569                                crate::resource_totals::Declaration {
2570                                    started,
2571                                    finished,
2572                                    known,
2573                                },
2574                            )
2575                            .await;
2576                    }
2577                    let result =
2578                        self.handle_module_control_request(ctx.connection_id, frame, request);
2579                    log_slow_control_dispatch(
2580                        dispatch_started_at,
2581                        op,
2582                        ctx.connection_id,
2583                        corr,
2584                        None,
2585                    );
2586                    return result;
2587                }
2588
2589                if is_known_module_request_op(&frame.body) {
2590                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2591                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2592                    let code = if is_agents {
2593                        "not_supervised"
2594                    } else if op
2595                        .as_ref()
2596                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2597                    {
2598                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2599                    } else {
2600                        "not_registered"
2601                    };
2602                    return Ok(vec![control_error_frame(
2603                        &frame,
2604                        code,
2605                        "module-originated control requests require the module's own registered connection",
2606                    )?]);
2607                }
2608
2609                let request = match parse_client_control_request(&frame.body) {
2610                    Ok(request) => request,
2611                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2612                        return Ok(vec![control_error_frame(
2613                            &frame,
2614                            "unknown_control_op",
2615                            format!("unknown client control op: {err}"),
2616                        )?])
2617                    }
2618                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2619                        return Ok(vec![control_error_frame(
2620                            &frame,
2621                            "invalid_control_body",
2622                            format!("malformed client control body: {err}"),
2623                        )?])
2624                    }
2625                };
2626                let op = client_control_request_op(&request);
2627                let corr = frame.header.corr;
2628                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2629                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2630                #[cfg(test)]
2631                if let Some(delay) = self.control_dispatch_delay {
2632                    tokio::time::sleep(delay).await;
2633                }
2634                let result = self
2635                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2636                    .await;
2637                if let Some(timings) = route_open_timings.as_mut() {
2638                    timings.finish();
2639                }
2640                log_slow_control_dispatch(
2641                    dispatch_started_at,
2642                    op,
2643                    ctx.connection_id,
2644                    corr,
2645                    route_open_timings.as_ref(),
2646                );
2647                result
2648            }
2649            FrameType::Push => {
2650                let Some(endpoint) = self
2651                    .forwarding
2652                    .module_endpoint_for_connection(ctx.connection_id)
2653                    .map_err(RouterError::Forwarding)?
2654                else {
2655                    return Ok(vec![control_error_frame(
2656                        &frame,
2657                        "unsupported_control_frame",
2658                        "client-originated channel-0 PUSH is not supported",
2659                    )?]);
2660                };
2661                self.handle_status_update(endpoint, frame)
2662            }
2663            FrameType::Response | FrameType::Error
2664                if self
2665                    .forwarding
2666                    .module_endpoint_for_connection(ctx.connection_id)
2667                    .map_err(RouterError::Forwarding)?
2668                    .is_some() =>
2669            {
2670                self.handle_module_relay_response(ctx.connection_id, frame)
2671            }
2672            ty => Ok(vec![control_error_frame(
2673                &frame,
2674                "unsupported_control_frame",
2675                format!("unsupported channel-0 frame {ty:?}"),
2676            )?]),
2677        }
2678    }
2679
2680    #[cfg(test)]
2681    fn pause_cleanup_for_test(&self, stage: u8) {
2682        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2683        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2684            let (_, (reached, release)) = slot.take().unwrap();
2685            drop(slot);
2686            let _ = reached.send(());
2687            let _ = release.recv_timeout(Duration::from_secs(5));
2688        }
2689    }
2690
2691    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2692    /// right after the nonce is resolved.
2693    #[cfg(all(test, unix, feature = "test-support"))]
2694    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2695        *self
2696            .after_nonce_attestation
2697            .lock()
2698            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2699    }
2700
2701    #[cfg(test)]
2702    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2703        let hook = self
2704            .after_nonce_attestation
2705            .lock()
2706            .unwrap_or_else(|p| p.into_inner())
2707            .take();
2708        if let Some(hook) = hook {
2709            hook();
2710        }
2711    }
2712
2713    #[cfg(test)]
2714    async fn pause_hello_ingress_for_test(&self) {
2715        let pause = self
2716            .hello_ingress_pause
2717            .lock()
2718            .unwrap_or_else(|p| p.into_inner())
2719            .take();
2720        if let Some((reached, release)) = pause {
2721            let _ = reached.send(());
2722            let _ = release.await;
2723        }
2724    }
2725
2726    pub fn cleanup_connection(
2727        &self,
2728        connection_id: ConnectionId,
2729    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2730        // The server loop joins its offloaded request tasks (route opens,
2731        // privileged requests and activity reads) before this cleanup runs, and
2732        // inline dispatch has ended. Two kinds of work are not joined. Agent
2733        // command declarations run on their queue's detached worker, so the
2734        // queue is closed first: every declaration still queued or validating
2735        // has its commit fence cancelled before anything below can change how
2736        // the connection resolves. A HELLO whose reader was dropped keeps
2737        // running on its blocking thread. It carries the channel spawn its
2738        // reader resolved at ingress instead of re-reading the index forgotten
2739        // below, so it is still judged as that channel's HELLO: the retired
2740        // spawn refuses it before it records anything, and a channel HELLO
2741        // never records a launch nonce, so it cannot leave this connection any
2742        // nonce authority.
2743        self.agent_declarations.close(connection_id);
2744        self.close_catalog_subscriptions(connection_id);
2745        self.close_config_settings_subscriptions(connection_id);
2746        self.close_scope_subscriptions(connection_id);
2747        #[cfg(test)]
2748        self.pause_cleanup_for_test(0);
2749        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2750            spawn.retire_registration_channel();
2751        }
2752        self.supervisor
2753            .forget_registration_connection(connection_id);
2754        #[cfg(test)]
2755        self.pause_cleanup_for_test(1);
2756        self.local_connections
2757            .lock()
2758            .unwrap_or_else(|p| p.into_inner())
2759            .remove(&connection_id);
2760        self.caller_endpoints
2761            .lock()
2762            .unwrap_or_else(|p| p.into_inner())
2763            .remove(&connection_id);
2764        self.build_class_warned
2765            .lock()
2766            .unwrap_or_else(|p| p.into_inner())
2767            .remove(&connection_id);
2768        // Retire the capture before its published facts so an in-flight
2769        // verification cannot recreate them after cleanup.
2770        self.captured_peers
2771            .lock()
2772            .unwrap_or_else(|p| p.into_inner())
2773            .remove(&connection_id);
2774        self.observed_peers
2775            .lock()
2776            .unwrap_or_else(|p| p.into_inner())
2777            .remove(&connection_id);
2778        self.config_desktop_stamps
2779            .lock()
2780            .unwrap_or_else(|p| p.into_inner())
2781            .remove(&connection_id);
2782        self.operator_apps
2783            .lock()
2784            .unwrap_or_else(|p| p.into_inner())
2785            .remove(&connection_id);
2786        self.forwarding
2787            .operator_confirms()
2788            .connection_closed(connection_id);
2789        let cleanup = self.cleanup_connection_with_end_reason(
2790            connection_id,
2791            RegistrationEndReason::ConnectionClosed,
2792        );
2793        // A draining writer can still be reached by a route until forwarding
2794        // cleanup finishes. Keep its claim sink visible to launch retirement.
2795        self.claims.connection_closed(connection_id);
2796        cleanup
2797    }
2798
2799    fn cleanup_connection_with_end_reason(
2800        &self,
2801        connection_id: ConnectionId,
2802        requested_reason: RegistrationEndReason,
2803    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2804        #[cfg(test)]
2805        if let Some(pause) = self
2806            .activity_request_pause
2807            .lock()
2808            .unwrap()
2809            .as_ref()
2810            .filter(|pause| pause.connection == connection_id)
2811        {
2812            pause
2813                .cleanup_started
2814                .store(true, std::sync::atomic::Ordering::Release);
2815        }
2816        if let Some(runtime) = &self.config_runtime {
2817            runtime.disconnected(connection_id);
2818        }
2819        self.agent_declarations.close(connection_id);
2820        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2821            self.registry
2822                .get_module_by_connection(connection_id)?
2823                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2824                .and_then(|module| module.registration_end_reason().ok().flatten())
2825                .unwrap_or(requested_reason)
2826        } else {
2827            requested_reason
2828        };
2829        let crash_closed = self
2830            .registry
2831            .get_module_by_connection(connection_id)?
2832            .and_then(|registration| {
2833                self.forwarding
2834                    .module_endpoint_for_connection(connection_id)
2835                    .ok()
2836                    .flatten()
2837                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2838                    .map(|routes| (registration.manifest.module_id, routes))
2839            });
2840        let crash_closed = crash_closed.map(|(module_id, routes)| {
2841            let terminal = match self.supervisor.get(&module_id) {
2842                None => false,
2843                Some(module) => match module.will_recover_after_connection_loss() {
2844                    Ok(will_recover) => !will_recover,
2845                    Err(err) => {
2846                        warn!(
2847                            %module_id,
2848                            error = %err,
2849                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2850                        );
2851                        false
2852                    }
2853                },
2854            };
2855            // The forwarding table gates all providers at the start of daemon
2856            // shutdown, before their connections are closed. An ordinary
2857            // module disconnect still reports crash if that gate is not set.
2858            let (reason, drained) = match self
2859                .forwarding
2860                .daemon_drain_result_for_connection(connection_id)
2861            {
2862                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
2863                Ok(None) => (RouteCloseReason::Crash, false),
2864                Err(err) => {
2865                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
2866                    (RouteCloseReason::Crash, false)
2867                }
2868            };
2869            (module_id, routes, reason, drained, terminal)
2870        });
2871        let registrations = self.deregister_connection(connection_id, end_reason);
2872        // Read before teardown: the spawn whose registration this connection
2873        // was. Its registration ending is an authority change for it.
2874        let ended_authority = self
2875            .forwarding
2876            .target_authority_for_connection(connection_id)
2877            .ok()
2878            .flatten();
2879        let cleanup = if crash_closed.is_some() {
2880            self.forwarding.cleanup_connection_counted(connection_id)
2881        } else {
2882            // A module connection's teardown needs the count of abandoned
2883            // route.bind relays for its route.closed notice below. Any other
2884            // connection, such as a client's, sends no such notice and needs
2885            // only its routes released, so it uses the route-only wrapper and
2886            // reports zero.
2887            self.forwarding
2888                .cleanup_connection(connection_id)
2889                .map(|released| crate::forwarding::ConnectionCleanup {
2890                    released,
2891                    abandoned_relays: 0,
2892                })
2893        };
2894        // The route.closed push waits for forwarding teardown because only
2895        // teardown knows how many pending route.bind relays it aborted. It still
2896        // goes out before the GOODBYEs for the released routes, and its targets
2897        // were captured above, before teardown removed those routes.
2898        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
2899            let abandoned = cleanup
2900                .as_ref()
2901                .map_or(0, |cleanup| cleanup.abandoned_relays);
2902            send_route_control_pushes(
2903                &self.forwarding,
2904                routes,
2905                ClientControlPush::RouteClosed {
2906                    module_id,
2907                    channels: Vec::new(),
2908                    reason,
2909                    drained,
2910                    abandoned,
2911                    excluded_subscriptions: 0,
2912                    terminal: Some(terminal),
2913                },
2914            );
2915        }
2916        if let Ok(cleanup) = cleanup {
2917            self.emit_route_goodbyes(cleanup.released);
2918        }
2919        if let Some(record) = ended_authority {
2920            self.change_spawn_authority(&record);
2921        }
2922        // Signal the registration-release watch only now that BOTH registry and
2923        // forwarding teardown are done, so a supervisor waiting to spawn a
2924        // replacement never observes release while old routes still exist.
2925        if matches!(&registrations, Ok(r) if !r.is_empty()) {
2926            crate::supervise::notify_registration_release();
2927            self.capability_evaluator.wake_deadline_loop();
2928            self.refresh_capability_requirements();
2929        }
2930        self.supervisor.remove_spawn_subscribers(connection_id);
2931        self.activity_streams
2932            .lock()
2933            .unwrap_or_else(|p| p.into_inner())
2934            .retain(|(id, _), task| {
2935                if *id == connection_id {
2936                    task.abort();
2937                    false
2938                } else {
2939                    true
2940                }
2941            });
2942        // Sync authority dies with its connection, so the owner's next
2943        // connection can take it; the owner's scopes stay as they are.
2944        self.hello_launch_nonces
2945            .lock()
2946            .unwrap_or_else(|poisoned| poisoned.into_inner())
2947            .forget(connection_id);
2948        self.scopes
2949            .write()
2950            .unwrap_or_else(|poisoned| poisoned.into_inner())
2951            .release_connection(connection_id);
2952        registrations
2953    }
2954
2955    pub(crate) fn handle_route_goodbye(
2956        &self,
2957        connection_id: ConnectionId,
2958        route_channel: u16,
2959        route_epoch: u32,
2960    ) -> Result<bool, RouterError> {
2961        debug!(
2962            connection_id = connection_id.get(),
2963            route_channel, route_epoch, "handling route GOODBYE"
2964        );
2965        let RouteRelease::Removed(released_route) = self
2966            .forwarding
2967            .release_client_route(connection_id, route_channel, route_epoch)
2968            .map_err(RouterError::Forwarding)?
2969        else {
2970            return Ok(false);
2971        };
2972        self.emit_route_goodbyes(vec![released_route]);
2973        Ok(true)
2974    }
2975
2976    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
2977        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
2978    }
2979
2980    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
2981    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
2982    /// own commit failed after the module had already accepted). Without this, a
2983    /// module that accepts late keeps a binding subc has torn down, so a later
2984    /// frame on that module channel could misdeliver if the channel is reused.
2985    ///
2986    /// Never closes the shared module connection on failure: a dropped notification
2987    /// only wastes a bounded amount of warm module-side state, which the module's
2988    /// own idle reaper reclaims. Only call this once the route.bind relay was
2989    /// actually enqueued to the module — if the relay send itself failed, the
2990    /// module never created a binding and there is nothing to tear down.
2991    fn send_abandoned_route_bind_goodbye(
2992        &self,
2993        module_sink: &crate::FrameSink,
2994        negotiated_ver: u8,
2995        module_channel: u16,
2996        module_epoch: u32,
2997    ) {
2998        let frame = match Frame::build_with_version(
2999            negotiated_ver,
3000            FrameType::Goodbye,
3001            control_flags(),
3002            module_channel,
3003            module_epoch,
3004            0,
3005            Vec::new(),
3006        ) {
3007            Ok(frame) => frame,
3008            Err(err) => {
3009                warn!(
3010                    route_channel = module_channel,
3011                    error = %err,
3012                    "failed to build GOODBYE for abandoned route.bind"
3013                );
3014                return;
3015            }
3016        };
3017        crate::forwarding::send_module_route_goodbye(
3018            &self.counters,
3019            module_sink,
3020            frame,
3021            None,
3022            "abandoned route.bind",
3023        );
3024    }
3025
3026    #[cfg(test)]
3027    fn handle_hello(
3028        &self,
3029        connection_id: ConnectionId,
3030        egress: Option<crate::router::FrameSink>,
3031        frame: Frame,
3032    ) -> Result<Vec<Frame>, RouterError> {
3033        let binding = self.claims.binding(connection_id);
3034        let channel_spawn = self.supervisor.registration_spawn(connection_id);
3035        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
3036    }
3037
3038    fn handle_hello_checked(
3039        &self,
3040        connection_id: ConnectionId,
3041        sink: Option<crate::FrameSink>,
3042        frame: Frame,
3043        wait_for_gate: bool,
3044        prefix_binding: Option<claims::ClaimBinding>,
3045        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3046    ) -> Result<Vec<Frame>, RouterError> {
3047        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
3048        #[cfg(test)]
3049        if prefix_binding.is_some() {
3050            self.claims.pause_prefix_hello_for_test(5);
3051            match self.claims.take_prefix_hello_failure_for_test() {
3052                Some("error") => {
3053                    return Err(RouterError::backend(
3054                        0,
3055                        frame.header.corr,
3056                        "injected HELLO failure",
3057                    ))
3058                }
3059                Some("panic") => panic!("injected HELLO task panic"),
3060                _ => {}
3061            }
3062        }
3063        if let Some(binding) = &prefix_binding {
3064            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3065            let module = value
3066                .as_ref()
3067                .and_then(|value| value["manifest"]["module_id"].as_str());
3068            if !binding.admit_prefix_hello(module)
3069                || !self.prefix_binding_live(binding, connection_id)
3070                || !module.is_some_and(|module| {
3071                    self.supervisor
3072                        .prefix_claim_authorized(&binding.registration.module_id, module)
3073                })
3074                || binding.registration.check().is_err()
3075            {
3076                return Ok(vec![control_error_frame(
3077                    &frame,
3078                    "claim_prefix_refused",
3079                    "HELLO must name the prefix claim's exact module id once",
3080                )?]);
3081            }
3082        }
3083        struct RefuseUnregisteredChannel {
3084            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3085            sink: Option<crate::FrameSink>,
3086        }
3087        impl Drop for RefuseUnregisteredChannel {
3088            fn drop(&mut self) {
3089                if let Some(spawn) = &self.spawn {
3090                    if !spawn.registered() {
3091                        if let Some(sink) = &self.sink {
3092                            sink.terminate_ingress();
3093                        }
3094                        spawn.retire_registration_channel();
3095                    }
3096                }
3097            }
3098        }
3099        let _channel_attempt = RefuseUnregisteredChannel {
3100            spawn: channel_spawn.clone(),
3101            sink: sink.clone(),
3102        };
3103        if let Some(spawn) = &channel_spawn {
3104            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3105            if let Err(code) = spawn.admit_hello(
3106                value
3107                    .as_ref()
3108                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3109            ) {
3110                return Ok(vec![control_error_frame(
3111                    &frame,
3112                    code,
3113                    "registration channel HELLO refused",
3114                )?]);
3115            }
3116        }
3117        debug!(
3118            connection_id = connection_id.get(),
3119            corr = frame.header.corr,
3120            "handling HELLO"
3121        );
3122        // A module connection has one identity for its entire lifetime. A second
3123        // registration would leave the old registry owner behind while replacing
3124        // its forwarding endpoint and launch nonce.
3125        if self
3126            .registry
3127            .get_module_by_connection(connection_id)
3128            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3129            .is_some()
3130        {
3131            return Ok(vec![control_error_frame(
3132                &frame,
3133                "invalid_hello",
3134                "connection is already registered as a module",
3135            )?]);
3136        }
3137        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3138            Ok(value) => value,
3139            Err(err) => {
3140                return Ok(vec![control_error_frame(
3141                    &frame,
3142                    "invalid_hello",
3143                    format!("malformed HELLO body: {err}"),
3144                )?])
3145            }
3146        };
3147        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3148            return Ok(vec![control_error_frame(
3149                &frame,
3150                error_codes::INVALID_PROVIDER_DECLARATIONS,
3151                detail,
3152            )?]);
3153        }
3154        if let Some(module) = hello_value
3155            .get("manifest")
3156            .and_then(|value| value.get("module_id"))
3157            .and_then(|value| value.as_str())
3158        {
3159            let recovering = self
3160                .config_runtime
3161                .as_ref()
3162                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3163            // Defence in depth: RuntimeOwner::module_is_gated in
3164            // config_gate/admission.rs already gates every id during recovery.
3165            // A registration channel still never uses the nonce fallback.
3166            if recovering
3167                && channel_spawn.as_ref().is_none_or(|spawn| {
3168                    !self.supervisor.has_live_verified_channel_binding(spawn)
3169                        || spawn.check().is_err()
3170                })
3171                && !(channel_spawn.is_none()
3172                    && hello_value
3173                        .get("launch_nonce")
3174                        .and_then(|value| value.as_str())
3175                        .is_some_and(|nonce| {
3176                            self.supervisor.spawned_consumer_authorized(module, nonce)
3177                                && self
3178                                    .supervisor
3179                                    .has_live_verified_program_binding(module, nonce)
3180                        }))
3181            {
3182                return Ok(vec![control_error_frame(
3183                    &frame,
3184                    "config_gated",
3185                    "recovery admits only previously bound supervised launches",
3186                )?]);
3187            }
3188            if self
3189                .config_runtime
3190                .as_ref()
3191                .is_some_and(|owner| owner.module_is_gated(module))
3192                && (channel_spawn
3193                    .as_ref()
3194                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3195                    || self.config_runtime.as_ref().is_some_and(|owner| {
3196                        !recovering && owner.check_module_hold(module).is_err()
3197                    }))
3198            {
3199                return Ok(vec![control_error_frame(
3200                    &frame,
3201                    "reserved_module",
3202                    "a gated identity belongs only to its supervised child",
3203                )?]);
3204            }
3205        }
3206        if channel_spawn.is_none() {
3207            if let (Some(module), Some(nonce)) = (
3208                hello_value
3209                    .get("manifest")
3210                    .and_then(|value| value.get("module_id"))
3211                    .and_then(|value| value.as_str()),
3212                hello_value
3213                    .get("launch_nonce")
3214                    .and_then(|value| value.as_str()),
3215            ) {
3216                let binding = self.supervisor.has_program_binding_record(module, nonce);
3217                let required = self
3218                    .config_runtime
3219                    .as_ref()
3220                    .is_some_and(|owner| owner.module_is_gated(module));
3221                if let Some(error) = (binding || required)
3222                    .then(|| {
3223                        self.supervisor
3224                            .check_current_program_binding(module, nonce)
3225                            .err()
3226                    })
3227                    .flatten()
3228                {
3229                    let code = if error.code == "program_refused" {
3230                        "program_refused"
3231                    } else {
3232                        "config_delivery_deferred"
3233                    };
3234                    self.request_refusal_close(
3235                        connection_id,
3236                        sink.as_ref(),
3237                        CloseReason::new(code, error.detail.clone()),
3238                    );
3239                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3240                }
3241            }
3242        }
3243        if let Err(err) = validate_hello_display_name(&hello_value) {
3244            return Ok(vec![control_error_frame(
3245                &frame,
3246                "invalid_manifest",
3247                err.to_string(),
3248            )?]);
3249        }
3250        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3251            return Ok(vec![control_error_frame(
3252                &frame,
3253                "invalid_capability_grammar",
3254                err.to_string(),
3255            )?]);
3256        }
3257        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3258            return Ok(vec![control_error_frame(
3259                &frame,
3260                "invalid_manifest",
3261                err.to_string(),
3262            )?]);
3263        }
3264        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3265            return Ok(vec![control_error_frame(
3266                &frame,
3267                "invalid_event_declaration",
3268                err.to_string(),
3269            )?]);
3270        }
3271        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3272            return Ok(vec![control_error_frame(
3273                &frame,
3274                "invalid_manifest",
3275                err.to_string(),
3276            )?]);
3277        }
3278        if let Some(provenance) = hello_value
3279            .get("manifest")
3280            .and_then(|manifest| manifest.get("provenance"))
3281        {
3282            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3283                return Ok(vec![control_error_frame(
3284                    &frame,
3285                    "invalid_manifest",
3286                    format!("malformed manifest provenance: {err}"),
3287                )?]);
3288            }
3289        }
3290        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3291            let module_id = hello_value["manifest"]["module_id"]
3292                .as_str()
3293                .unwrap_or("<unknown>");
3294            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3295        }
3296        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3297            let module_id = hello_value
3298                .get("manifest")
3299                .and_then(|m| m.get("module_id"))
3300                .and_then(serde_json::Value::as_str)
3301                .unwrap_or("unknown");
3302            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3303        }
3304        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3305            let module_id = hello_value["manifest"]["module_id"]
3306                .as_str()
3307                .unwrap_or("<unknown>");
3308            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3309        }
3310        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3311            let module_id = hello_value["manifest"]["module_id"]
3312                .as_str()
3313                .unwrap_or("<unknown>");
3314            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3315        }
3316        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3317            Ok(hello) => hello,
3318            Err(err) => {
3319                return Ok(vec![control_error_frame(
3320                    &frame,
3321                    "invalid_hello",
3322                    format!("malformed HELLO body: {err}"),
3323                )?])
3324            }
3325        };
3326
3327        if hello.protocol_ver != hello.manifest.protocol_ver {
3328            return Ok(vec![control_error_frame(
3329                &frame,
3330                "invalid_manifest",
3331                format!(
3332                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3333                    hello.protocol_ver, hello.manifest.protocol_ver
3334                ),
3335            )?]);
3336        }
3337
3338        if hello.manifest.module_id.trim().is_empty() {
3339            return Ok(vec![control_error_frame(
3340                &frame,
3341                "invalid_manifest",
3342                "manifest module_id must not be empty",
3343            )?]);
3344        }
3345
3346        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3347            Ok(negotiated_ver) => negotiated_ver,
3348            Err(message) => {
3349                return Ok(vec![control_error_frame(
3350                    &frame,
3351                    "version_unsupported",
3352                    message,
3353                )?])
3354            }
3355        };
3356
3357        // Registration and forwarding publication use the same module gate as
3358        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3359        // precede those transitions. A program-refusal hold blocks future
3360        // spawns, but does not take this gate or revoke a HELLO whose supervised
3361        // child's image has already passed the check.
3362        let _publication_gate = if let Some(owner) = &self.config_runtime {
3363            let gate = owner
3364                .module_gate(&hello.manifest.module_id)
3365                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3366            Some(if wait_for_gate {
3367                gate.blocking_lock_owned()
3368            } else {
3369                match gate.try_lock_owned() {
3370                    Ok(guard) => guard,
3371                    Err(_) => {
3372                        return Ok(vec![control_error_frame(
3373                            &frame,
3374                            "config_delivery_deferred",
3375                            "module admission is busy",
3376                        )?])
3377                    }
3378                }
3379            })
3380        } else {
3381            None
3382        };
3383        #[cfg(test)]
3384        if let Some(hold) = &self.hello_before_publication_hold {
3385            hold.wait();
3386            hold.wait();
3387        }
3388        let module = &hello.manifest.module_id;
3389        let required = self
3390            .config_runtime
3391            .as_ref()
3392            .is_some_and(|owner| owner.module_is_gated(module));
3393        let recovering = self
3394            .config_runtime
3395            .as_ref()
3396            .is_some_and(|owner| owner.is_recovering());
3397        // Both entry paths (handle_control -> handle_hello and
3398        // handle_control_frame_timed -> spawn_blocking) enter this same
3399        // handle_hello_checked function. Its fresh, fail-closed store check
3400        // precedes parsing and this publication-gate check; this cached read
3401        // also observes any recovery transition published during that work.
3402        // The nonce-connection-only fallback is defence in depth alongside
3403        // RuntimeOwner::module_is_gated's all-id recovery gate.
3404        if recovering
3405            && channel_spawn.as_ref().is_none_or(|spawn| {
3406                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3407            })
3408            && !(channel_spawn.is_none()
3409                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3410                    self.supervisor.spawned_consumer_authorized(module, nonce)
3411                        && self
3412                            .supervisor
3413                            .has_live_verified_program_binding(module, nonce)
3414                }))
3415        {
3416            return Ok(vec![control_error_frame(
3417                &frame,
3418                "config_gated",
3419                "recovery admits only previously bound supervised launches",
3420            )?]);
3421        }
3422        if required
3423            && (channel_spawn
3424                .as_ref()
3425                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3426                || self
3427                    .config_runtime
3428                    .as_ref()
3429                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3430        {
3431            return Ok(vec![control_error_frame(
3432                &frame,
3433                "reserved_module",
3434                "gated admission requires the current supervised child's registration channel and verified image binding",
3435            )?]);
3436        }
3437        if let Some(spawn) = &channel_spawn {
3438            if let Err(code) = spawn.check() {
3439                return Ok(vec![control_error_frame(
3440                    &frame,
3441                    code,
3442                    "registration launch is no longer live",
3443                )?]);
3444            }
3445        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3446            if required || self.supervisor.has_program_binding_record(module, nonce) {
3447                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3448                    let code = if error.code == "program_refused" {
3449                        "program_refused"
3450                    } else {
3451                        "config_delivery_deferred"
3452                    };
3453                    self.request_refusal_close(
3454                        connection_id,
3455                        sink.as_ref(),
3456                        CloseReason::new(code, error.detail.clone()),
3457                    );
3458                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3459                }
3460            }
3461        }
3462
3463        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3464        // swap is open for this id, the only HELLO admitted as a second process
3465        // is the one carrying the candidate's launch nonce (the swap token), and
3466        // it registers into the candidate slot rather than being refused as a
3467        // duplicate. Run after the reserved gate, a reserved module's candidate
3468        // would be refused `reserved_module` for presenting a nonce that gate
3469        // does not know. See `SupervisorHandle::swap_hello_admission`.
3470        let swap_admission = match &channel_spawn {
3471            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3472            Some(_) => SwapHelloAdmission::NotSwapping,
3473            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3474            None => self
3475                .supervisor
3476                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3477        };
3478        if swap_admission == SwapHelloAdmission::ProtocolNone {
3479            warn!(
3480                module_id = %hello.manifest.module_id,
3481                connection_id = connection_id.get(),
3482                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3483            );
3484            // The code stays `swap_token_invalid` for existing callers; only the
3485            // explanation names the actual reason.
3486            return Ok(vec![control_error_frame(
3487                &frame,
3488                "swap_token_invalid",
3489                format!(
3490                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3491                    hello.manifest.module_id
3492                ),
3493            )?]);
3494        }
3495        if swap_admission == SwapHelloAdmission::ChannelRequired {
3496            warn!(
3497                module_id = %hello.manifest.module_id,
3498                connection_id = connection_id.get(),
3499                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3500            );
3501            // The code stays `swap_token_invalid` for existing callers; only the
3502            // explanation names the actual reason.
3503            return Ok(vec![control_error_frame(
3504                &frame,
3505                "swap_token_invalid",
3506                format!(
3507                    "module_id '{}' is gated; it must register over its supervised registration channel",
3508                    hello.manifest.module_id
3509                ),
3510            )?]);
3511        }
3512        if swap_admission == SwapHelloAdmission::Refused {
3513            warn!(
3514                module_id = %hello.manifest.module_id,
3515                connection_id = connection_id.get(),
3516                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3517            );
3518            return Ok(vec![control_error_frame(
3519                &frame,
3520                "swap_token_invalid",
3521                format!(
3522                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3523                    hello.manifest.module_id
3524                ),
3525            )?]);
3526        }
3527        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3528
3529        // A swap candidate proves its identity with the candidate nonce above.
3530        // Other registrations receive this catalog fact only when reserved-module
3531        // policy required and accepted a nonce; unreserved registrations require
3532        // no nonce check.
3533        let verification = if swap_candidate && channel_spawn.is_none() {
3534            ReservedHelloVerification {
3535                nonce_verified: true,
3536                prefix_owner: None,
3537            }
3538        } else {
3539            let verification = if let Some(binding) = &prefix_binding {
3540                if !self.supervisor.prefix_claim_authorized(
3541                    &binding.registration.module_id,
3542                    &hello.manifest.module_id,
3543                ) {
3544                    return Ok(vec![control_error_frame(
3545                        &frame,
3546                        "claim_prefix_refused",
3547                        "prefix ownership changed",
3548                    )?]);
3549                }
3550                Ok(ReservedHelloVerification {
3551                    nonce_verified: true,
3552                    prefix_owner: Some(binding.registration.module_id.clone()),
3553                })
3554            } else if channel_spawn.is_some() {
3555                self.supervisor
3556                    .channel_hello_verification(&hello.manifest.module_id)
3557            } else {
3558                self.supervisor.reserved_hello_verification(
3559                    &hello.manifest.module_id,
3560                    hello.launch_nonce.as_deref(),
3561                )
3562            };
3563            match verification {
3564                Ok(verified) => verified,
3565                Err(rejection) => {
3566                    let message = match rejection {
3567                        ReservedHelloRejection::Exact { module_id } => format!(
3568                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3569                        ),
3570                        ReservedHelloRejection::Prefix {
3571                            prefix,
3572                            owner_module_id,
3573                        } => format!(
3574                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3575                            hello.manifest.module_id
3576                        ),
3577                    };
3578                    return Ok(vec![control_error_frame(
3579                        &frame,
3580                        "reserved_module",
3581                        message,
3582                    )?]);
3583                }
3584            }
3585        };
3586
3587        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3588            &hello.manifest.module_id,
3589            hello.manifest.capabilities.as_ref(),
3590        );
3591        if let Some(refusal) = reserved_capability_refusals.first() {
3592            let capability = refusal.capability.clone();
3593            let bound_module = refusal.claimants[0].clone();
3594            log_duplicate_claim_events(reserved_capability_refusals);
3595            return Ok(vec![control_error_frame(
3596                &frame,
3597                "reserved_capability",
3598                format!(
3599                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3600                    capability, bound_module, hello.manifest.module_id
3601                ),
3602            )?]);
3603        }
3604
3605        // A connection that already opened client routes must not also register as
3606        // a module: cleanup would then release only one side and leak the other.
3607        if self
3608            .forwarding
3609            .connection_has_client_routes(connection_id)
3610            .map_err(RouterError::Forwarding)?
3611        {
3612            return Ok(vec![control_error_frame(
3613                &frame,
3614                "invalid_hello",
3615                "connection has open client routes and cannot also register as a module",
3616            )?]);
3617        }
3618
3619        // Kept for scope sync authority, which goes only to the connection that
3620        // presented the module's current launch nonce. Recorded before the
3621        // registration is attempted: a connection whose registration then fails
3622        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3623        // A registration channel's authority is the channel itself, never a
3624        // nonce it also presented, and a prefix registration's is its claim:
3625        // neither records one, so neither can fall back to nonce authority.
3626        self.hello_launch_nonces
3627            .lock()
3628            .unwrap_or_else(|poisoned| poisoned.into_inner())
3629            .record(
3630                connection_id,
3631                if prefix_binding.is_some() || channel_spawn.is_some() {
3632                    None
3633                } else {
3634                    hello.launch_nonce.as_deref()
3635                },
3636            );
3637        let control_ops = effective_module_control_ops(hello.control_ops);
3638        let prefix_submodule = verification.prefix_owner.is_some();
3639        // Built before anything is registered so an encoding failure leaves no
3640        // registry or forwarding state behind.
3641        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3642        #[cfg(test)]
3643        struct PublicationFinished(Arc<std::sync::Barrier>);
3644        #[cfg(test)]
3645        impl Drop for PublicationFinished {
3646            fn drop(&mut self) {
3647                self.0.wait();
3648            }
3649        }
3650        #[cfg(test)]
3651        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3652            hold.wait();
3653            hold.wait();
3654            PublicationFinished(hold.clone())
3655        });
3656        let publication_spawn = channel_spawn
3657            .as_ref()
3658            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3659        #[cfg(test)]
3660        if prefix_binding.is_some() {
3661            self.claims.pause_prefix_hello_for_test(7);
3662        }
3663        let _registration_publication = match publication_spawn {
3664            Some(spawn) => Some(match spawn.begin_publication() {
3665                Ok(guard) => guard,
3666                Err(code) => {
3667                    return Ok(vec![control_error_frame(
3668                        &frame,
3669                        code,
3670                        "registration ended before HELLO publication",
3671                    )?])
3672                }
3673            }),
3674            None => None,
3675        };
3676        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3677            let live = self.claims.lock_prefix_binding(binding, connection_id);
3678            let ownership = self.supervisor.prefix_claim_publication(
3679                &binding.registration.module_id,
3680                &hello.manifest.module_id,
3681            );
3682            if live.is_none()
3683                || ownership.is_none()
3684                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3685                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3686            {
3687                return Ok(vec![control_error_frame(
3688                    &frame,
3689                    "claim_prefix_refused",
3690                    "prefix authority ended before publication",
3691                )?]);
3692            }
3693            (live, ownership)
3694        } else {
3695            (None, None)
3696        };
3697        if let Some(spawn) = publication_spawn {
3698            self.forwarding
3699                .bind_spawn(connection_id, spawn)
3700                .map_err(RouterError::Forwarding)?;
3701        }
3702        // The spawn whose own registration this HELLO is, for `target` on
3703        // the route.open reply: its channel, or the launch its nonce was
3704        // minted for. A prefix child's HELLO names no spawn of its own. It is
3705        // only looked up here. The connection is bound to it and its
3706        // requested declarations are frozen once the registry has accepted
3707        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3708        // duplicate, or for any other reason, leaves the spawn untouched: its
3709        // closing connection is then no registration of the spawn and ends
3710        // none of the spawn's routes.
3711        let hello_authority = match (&channel_spawn, &prefix_binding) {
3712            (Some(spawn), _) => Some(spawn.authority.clone()),
3713            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3714                self.supervisor
3715                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3716            }),
3717            (None, Some(_)) => None,
3718        }
3719        .map(|record| HelloAuthority {
3720            record,
3721            requested: hello
3722                .manifest
3723                .provider_declarations
3724                .clone()
3725                .unwrap_or_default(),
3726            froze: Default::default(),
3727        });
3728        #[cfg(test)]
3729        if prefix_binding.is_some() {
3730            self.claims.pause_prefix_hello_for_test(8);
3731        }
3732        if swap_candidate {
3733            let module_id = hello.manifest.module_id.clone();
3734            let mut differing_declarations = Default::default();
3735            let reply = self.register_swap_candidate(
3736                connection_id,
3737                sink,
3738                &frame,
3739                hello.manifest,
3740                negotiated_ver,
3741                control_ops,
3742                hello_ack,
3743                hello_authority.as_ref(),
3744                &mut differing_declarations,
3745                #[cfg(windows)]
3746                hello.launch_nonce.as_deref(),
3747            )?;
3748            if let Some(spawn) = &channel_spawn {
3749                if self
3750                    .registry
3751                    .get_module_by_connection(connection_id)
3752                    .ok()
3753                    .flatten()
3754                    .is_some()
3755                {
3756                    if let Some(sink) = primary_sink {
3757                        spawn.bind_primary_sink(sink);
3758                    }
3759                    spawn.hello_accepted();
3760                }
3761            } else if self
3762                .registry
3763                .get_module_by_connection(connection_id)
3764                .ok()
3765                .flatten()
3766                .is_some()
3767            {
3768                self.supervisor
3769                    .retire_unused_registration_channel(&module_id, true);
3770            }
3771            if self
3772                .registry
3773                .get_module_by_connection(connection_id)
3774                .ok()
3775                .flatten()
3776                .is_some()
3777            {
3778                self.file_development_widening(
3779                    hello_authority.map(|authority| authority.record),
3780                    differing_declarations,
3781                );
3782            }
3783            return Ok(reply);
3784        }
3785        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3786        // is refused, but `catalog.list` does not show the module and the
3787        // catalog generation does not move until it is published below, once
3788        // its forwarding endpoint exists. Listing it now would advertise a
3789        // module that `route.open` still refuses for having no forwarding
3790        // connection.
3791        let registration = match self
3792            .registry
3793            .register_unpublished_verified_with_control_ops(
3794                hello.manifest,
3795                negotiated_ver,
3796                connection_id,
3797                control_ops,
3798                verification.nonce_verified,
3799            ) {
3800            Ok(registration) => registration,
3801            Err(RegistryError::DuplicateModuleId { module_id }) => {
3802                return Ok(vec![control_error_frame(
3803                    &frame,
3804                    "duplicate_module_id",
3805                    format!(
3806                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3807                    ),
3808                )?])
3809            }
3810            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3811                return Ok(vec![control_error_frame(
3812                    &frame,
3813                    "invalid_module_id",
3814                    err.to_string(),
3815                )?])
3816            }
3817            Err(err) => {
3818                return Ok(vec![control_error_frame(
3819                    &frame,
3820                    "registry_error",
3821                    err.to_string(),
3822                )?])
3823            }
3824        };
3825        let differing_declarations =
3826            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3827                Ok(differing) => differing,
3828                Err(err) => {
3829                    if matches!(
3830                        self.rollback_unpublished_hello(connection_id),
3831                        Ok(r) if !r.is_empty()
3832                    ) {
3833                        crate::supervise::notify_registration_release();
3834                    }
3835                    return Err(RouterError::Forwarding(err));
3836                }
3837            };
3838        #[cfg(test)]
3839        self.hold_between_registry_and_forwarding();
3840
3841        let mut reply = Vec::new();
3842        // Registry readers must wait from before the ACK can be read until
3843        // publication. Nest forwarding inside the registry lock, never reverse.
3844        let publication = self
3845            .registry
3846            .publish_registration_after(connection_id, || {
3847                if let Some(sink) = sink {
3848                    // The forwarding table's module store is also the daemon-to-module
3849                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3850                    // manifest has no routable provider role. Non-routable modules still
3851                    // cannot receive route.bind in production: `handle_route_open` checks
3852                    // the registry manifest with `target_has_required_role` before the
3853                    // only production call to `begin_route_bind_relay_for` below that
3854                    // route.open path. The remaining direct relay callers are unit tests
3855                    // and benchmark harnesses that construct forwarding state explicitly.
3856                    //
3857                    // The HELLO_ACK is queued by the forwarding table itself, before the
3858                    // endpoint becomes visible, and is NOT returned as a reply. A module
3859                    // reads HELLO_ACK first and exits on anything else; a reply is only
3860                    // written after this handler returns, by which time a route.open on
3861                    // another connection could already have queued a route.bind request
3862                    // for this module ahead of it.
3863                    let concurrency = manifest_concurrency(&registration.manifest);
3864                    self.forwarding.register_module_connection_acked(
3865                        connection_id,
3866                        registration.manifest.module_id.clone(),
3867                        negotiated_ver,
3868                        concurrency,
3869                        sink,
3870                        crate::forwarding::ModuleHelloAck {
3871                            frame: hello_ack,
3872                            verified_prefix_owner: verification.prefix_owner,
3873                        },
3874                    )?;
3875                } else {
3876                    // No sink means no forwarding endpoint, so nothing can be routed
3877                    // ahead of the ack; it goes out as the reply.
3878                    reply.push(hello_ack);
3879                }
3880                #[cfg(test)]
3881                self.hold_between_ack_and_publication();
3882                Ok(())
3883            })
3884            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3885        let published = match publication {
3886            Ok(published) => published,
3887            Err(err) => {
3888                // The registry lock has been released, so rollback can take it
3889                // again. No forwarding endpoint or route was published. Keep
3890                // forwarding's weak connection-to-spawn association until the
3891                // connection's read loop ends and removes its remaining routes.
3892                // Removing this unpublished entry does not advance the catalog
3893                // generation.
3894                if matches!(
3895                    self.rollback_unpublished_hello(connection_id),
3896                    Ok(r) if !r.is_empty()
3897                ) {
3898                    crate::supervise::notify_registration_release();
3899                }
3900                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3901                return Ok(vec![control_error_frame(
3902                    &frame,
3903                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
3904                        "invalid_hello"
3905                    } else {
3906                        forwarding_error_code(&err)
3907                    },
3908                    err.to_string(),
3909                )?]);
3910            }
3911        };
3912        if !published {
3913            debug!(
3914                module_id = %registration.manifest.module_id,
3915                connection_id = connection_id.get(),
3916                "registration was removed before it could be published"
3917            );
3918            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3919            return Ok(reply);
3920        }
3921
3922        drop(_prefix_ownership);
3923        drop(_prefix_live);
3924
3925        // Exposure over assumption: Concurrency's serde default is pinned to the
3926        // pre-field behavior (ModuleManaged), so a management surface that is
3927        // genuinely Serial and just never declared it inherits concurrent
3928        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
3929        // turns "no module has been bitten yet" into the checkable claim "no
3930        // module is exposed" -- one read of the boot log instead of a fleet
3931        // audit. Detected from the raw HELLO bytes because the serde default
3932        // deliberately erases the absent/declared distinction from the type.
3933        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
3934            info!(
3935                module_id = %registration.manifest.module_id,
3936                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
3937            );
3938        }
3939        if registration.manifest.registration_channel == Some(false)
3940            && self
3941                .supervisor
3942                .module_is_gated(&registration.manifest.module_id)
3943            && self
3944                .config_runtime
3945                .as_ref()
3946                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
3947                .as_deref()
3948                == Some("declared")
3949        {
3950            warn!(module_id = %registration.manifest.module_id,
3951                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
3952        }
3953
3954        self.apply_registration_capabilities(&registration);
3955
3956        self.supervisor
3957            .record_activity_registration(&registration.manifest.module_id);
3958
3959        info!(
3960            module_id = %registration.manifest.module_id,
3961            module_version = %registration.manifest.module_version,
3962            negotiated_ver,
3963            routable_provider = manifest_provides_routable_role(&registration.manifest),
3964            connection_id = connection_id.get(),
3965            "module registered"
3966        );
3967
3968        if let Some(spawn) = &channel_spawn {
3969            if let Some(sink) = primary_sink {
3970                spawn.bind_primary_sink(sink);
3971            }
3972            spawn.hello_accepted();
3973        } else if !prefix_submodule {
3974            self.supervisor
3975                .retire_unused_registration_channel(&registration.manifest.module_id, false);
3976        }
3977        self.file_development_widening(
3978            hello_authority.map(|authority| authority.record),
3979            differing_declarations,
3980        );
3981        #[cfg(windows)]
3982        if let Some(nonce) = hello.launch_nonce.as_deref() {
3983            self.supervisor
3984                .program_hello_accepted(&registration.manifest.module_id, nonce);
3985        }
3986
3987        #[cfg(test)]
3988        if let Some(hold) = &self.hello_inside_publication_hold {
3989            hold.wait();
3990            hold.wait();
3991        }
3992
3993        Ok(reply)
3994    }
3995
3996    /// Register a HELLO the swap gate admitted into the candidate slot of the
3997    /// registry and of forwarding, where it is reachable over its own
3998    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
3999    /// nothing routes to it until the supervisor cuts over.
4000    ///
4001    /// Registry first (unpublished), then forwarding, then publication, the
4002    /// same order as an ordinary HELLO; a forwarding failure removes the
4003    /// registry entry again. The swap supervisor treats a published, ready
4004    /// candidate as registered and promotes it, and promotion needs the
4005    /// candidate's forwarding endpoint, so the candidate is published only
4006    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
4007    /// recompute capability verdicts or run the capability deny census
4008    /// (`enforce_capability_denies`): both are about the module in the active
4009    /// slot, which `route.open` can target. A candidate sits in the candidate
4010    /// slot, so it neither provides capabilities to other modules nor can be
4011    /// routed to until promotion moves it into the active slot.
4012    #[allow(clippy::too_many_arguments)]
4013    fn register_swap_candidate(
4014        &self,
4015        connection_id: ConnectionId,
4016        sink: Option<crate::FrameSink>,
4017        frame: &Frame,
4018        manifest: ModuleManifest,
4019        negotiated_ver: u8,
4020        control_ops: Vec<String>,
4021        hello_ack: Frame,
4022        hello_authority: Option<&HelloAuthority>,
4023        differing_declarations: &mut ProviderDeclarations,
4024        #[cfg(windows)] launch_nonce: Option<&str>,
4025    ) -> Result<Vec<Frame>, RouterError> {
4026        let module_id = manifest.module_id.clone();
4027        // Closing a swap and publishing its candidate must be ordered. The
4028        // spawn role proves which slot is intended, not that the slot is open.
4029        self.supervisor
4030            .with_swap_candidate_admission(&module_id, || {
4031                let reply = self.publish_swap_candidate(
4032                    connection_id,
4033                    sink,
4034                    frame,
4035                    manifest,
4036                    negotiated_ver,
4037                    control_ops,
4038                    hello_ack,
4039                    hello_authority,
4040                    differing_declarations,
4041                    #[cfg(windows)]
4042                    launch_nonce,
4043                );
4044                let admitted = self
4045                    .registry
4046                    .get_candidate(&module_id)
4047                    .ok()
4048                    .flatten()
4049                    .is_some_and(|candidate| candidate.connection_id == connection_id);
4050                (reply, admitted)
4051            })
4052            .unwrap_or_else(|| {
4053                Ok(vec![control_error_frame(
4054                    frame,
4055                    "swap_token_invalid",
4056                    "swap ended before candidate HELLO publication",
4057                )?])
4058            })
4059    }
4060
4061    #[allow(clippy::too_many_arguments)]
4062    fn publish_swap_candidate(
4063        &self,
4064        connection_id: ConnectionId,
4065        sink: Option<crate::FrameSink>,
4066        frame: &Frame,
4067        manifest: ModuleManifest,
4068        negotiated_ver: u8,
4069        control_ops: Vec<String>,
4070        hello_ack: Frame,
4071        hello_authority: Option<&HelloAuthority>,
4072        differing_declarations: &mut ProviderDeclarations,
4073        #[cfg(windows)] launch_nonce: Option<&str>,
4074    ) -> Result<Vec<Frame>, RouterError> {
4075        let module_id = manifest.module_id.clone();
4076        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4077            manifest,
4078            negotiated_ver,
4079            connection_id,
4080            control_ops,
4081        ) {
4082            Ok(registration) => registration,
4083            Err(RegistryError::DuplicateModuleId { module_id }) => {
4084                return Ok(vec![control_error_frame(
4085                    frame,
4086                    "duplicate_module_id",
4087                    format!(
4088                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4089                    ),
4090                )?])
4091            }
4092            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4093                return Ok(vec![control_error_frame(
4094                    frame,
4095                    "invalid_module_id",
4096                    err.to_string(),
4097                )?])
4098            }
4099            Err(err) => {
4100                return Ok(vec![control_error_frame(
4101                    frame,
4102                    "registry_error",
4103                    err.to_string(),
4104                )?])
4105            }
4106        };
4107        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4108            Ok(differing) => differing,
4109            Err(err) => {
4110                if matches!(
4111                    self.rollback_unpublished_hello(connection_id),
4112                    Ok(r) if !r.is_empty()
4113                ) {
4114                    crate::supervise::notify_registration_release();
4115                }
4116                return Err(RouterError::Forwarding(err));
4117            }
4118        };
4119        #[cfg(test)]
4120        self.hold_between_registry_and_forwarding();
4121        let mut reply = Vec::new();
4122        let publication = self
4123            .registry
4124            .publish_registration_after(connection_id, || {
4125                if let Some(sink) = sink {
4126                    // Same ordering as an ordinary HELLO: queue the ACK before
4127                    // inserting the endpoint, and keep registry readers excluded
4128                    // until the candidate is published.
4129                    let concurrency = manifest_concurrency(&registration.manifest);
4130                    self.forwarding.register_candidate_module_connection_acked(
4131                        connection_id,
4132                        module_id.clone(),
4133                        negotiated_ver,
4134                        concurrency,
4135                        sink,
4136                        hello_ack,
4137                    )?;
4138                } else {
4139                    reply.push(hello_ack);
4140                }
4141                #[cfg(test)]
4142                self.hold_between_ack_and_publication();
4143                Ok(())
4144            })
4145            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4146        let published = match publication {
4147            Ok(published) => published,
4148            Err(err) => {
4149                if matches!(
4150                    self.rollback_unpublished_hello(connection_id),
4151                    Ok(r) if !r.is_empty()
4152                ) {
4153                    crate::supervise::notify_registration_release();
4154                }
4155                self.refuse_hello_authority(connection_id, hello_authority);
4156                return Ok(vec![control_error_frame(
4157                    frame,
4158                    forwarding_error_code(&err),
4159                    err.to_string(),
4160                )?]);
4161            }
4162        };
4163        if !published {
4164            debug!(
4165                module_id = %module_id,
4166                connection_id = connection_id.get(),
4167                "swap candidate registration was removed before it could be published"
4168            );
4169            self.refuse_hello_authority(connection_id, hello_authority);
4170            return Ok(reply);
4171        }
4172        info!(
4173            module_id = %module_id,
4174            module_version = %registration.manifest.module_version,
4175            negotiated_ver,
4176            ready = registration.ready,
4177            connection_id = connection_id.get(),
4178            "swap candidate registered; not routable until cutover"
4179        );
4180        #[cfg(windows)]
4181        if let Some(nonce) = launch_nonce {
4182            self.supervisor.program_hello_accepted(&module_id, nonce);
4183        }
4184        Ok(reply)
4185    }
4186
4187    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4188    /// spawn's requested provider declarations. Runs only once the registry
4189    /// has accepted the HELLO, before its endpoint is published, so a route
4190    /// reserved on the endpoint always finds the spawn. Returns the requested
4191    /// entries that differ from the saved approvals, for a widening request.
4192    fn admit_hello_authority(
4193        &self,
4194        connection: ConnectionId,
4195        authority: Option<&HelloAuthority>,
4196    ) -> Result<ProviderDeclarations, ForwardingError> {
4197        let Some(authority) = authority else {
4198            return Ok(ProviderDeclarations::new());
4199        };
4200        let froze = authority
4201            .record
4202            .freeze_declarations(authority.requested.clone());
4203        authority
4204            .froze
4205            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4206        self.forwarding
4207            .bind_target_authority(connection, authority.record.clone())
4208            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4209        Ok(froze.unwrap_or_default())
4210    }
4211
4212    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4213    /// registry accepted it, so the refused connection is no registration of
4214    /// the spawn and the spawn's declarations are left for the HELLO that
4215    /// does register it to freeze.
4216    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4217        let Some(authority) = authority else {
4218            return;
4219        };
4220        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4221            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4222        }
4223        if authority
4224            .froze
4225            .swap(false, std::sync::atomic::Ordering::Relaxed)
4226        {
4227            authority.record.unfreeze_refused_declarations();
4228        }
4229    }
4230
4231    fn build_hello_ack(
4232        &self,
4233        frame: &Frame,
4234        negotiated_ver: u8,
4235        module_id: &str,
4236    ) -> Result<Frame, RouterError> {
4237        let ack = ModuleHelloAckBody {
4238            negotiated_ver,
4239            subc_ops: module_subc_ops(),
4240            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4241            storage: self
4242                .storage_config
4243                .as_ref()
4244                .map(|cfg| cfg.descriptor_for(module_id)),
4245            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4246        };
4247        let body = serde_json::to_vec(&ack).map_err(|err| {
4248            RouterError::backend(
4249                0,
4250                frame.header.corr,
4251                format!("failed to encode HELLO_ACK: {err}"),
4252            )
4253        })?;
4254
4255        Frame::build_with_version(
4256            negotiated_ver,
4257            FrameType::HelloAck,
4258            control_flags(),
4259            0,
4260            0,
4261            frame.header.corr,
4262            body,
4263        )
4264        .map_err(RouterError::FrameBuild)
4265    }
4266
4267    async fn handle_client_control_request(
4268        &self,
4269        ctx: &RouteCtx,
4270        frame: Frame,
4271        request: ClientControlRequest,
4272        route_open_timings: &mut Option<RouteOpenTimings>,
4273    ) -> Result<Vec<Frame>, RouterError> {
4274        if let Some(owner) = &self.config_runtime {
4275            let module = match &request {
4276                ClientControlRequest::SupervisorRestart { module_id, .. }
4277                | ClientControlRequest::SupervisorReload { module_id }
4278                | ClientControlRequest::SupervisorSwap { module_id, .. }
4279                | ClientControlRequest::SupervisorSetEnabled {
4280                    module_id,
4281                    enabled: true,
4282                } => Some(module_id.as_str()),
4283                _ => None,
4284            };
4285            let rescan = matches!(
4286                &request,
4287                ClientControlRequest::SupervisorRescan { preview: false }
4288                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4289            );
4290            let held = if module.is_some() || rescan {
4291                let module = module.map(str::to_owned);
4292                owner
4293                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4294                    .await
4295            } else {
4296                Ok(())
4297            };
4298            if let Err(error) = held {
4299                if error.code != "config_delivery_deferred" {
4300                    let code = if error.code == "store_tampered" {
4301                        "store_tampered"
4302                    } else {
4303                        "config_gated"
4304                    };
4305                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4306                }
4307            }
4308        }
4309        if let Some(operation) = privileged_operation(&request) {
4310            let caller = self.resolve_caller(ctx.connection_id).await;
4311            let op = client_control_request_op(&request);
4312            let text = prompt_text(operation, &caller);
4313            match self.privileged_operator_prompt {
4314                PrivilegedOperatorPrompt::Log => {
4315                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4316                        target = ?operation, caller = %caller.description(), summary = %text,
4317                        "privileged request would prompt the operator");
4318                }
4319                PrivilegedOperatorPrompt::Enforce => {
4320                    let key =
4321                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4322                    let shortcut =
4323                        self.operator_shortcut_stamp(ctx.connection_id)
4324                            .await
4325                            .map(|stamp| {
4326                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
4327                            });
4328                    let outcome = self
4329                        .forwarding
4330                        .operator_confirms()
4331                        .approve_privileged_with_shortcut(
4332                            ctx,
4333                            &frame,
4334                            op,
4335                            text,
4336                            caller.description(),
4337                            key,
4338                            shortcut,
4339                        )
4340                        .await;
4341                    if outcome.code != "confirmed" {
4342                        return Ok(vec![outcome.frame(&frame)]);
4343                    }
4344                }
4345            }
4346        }
4347        match request {
4348            ClientControlRequest::DaemonShutdownIntent { intent } => {
4349                if intent.as_str() != Some("restart") {
4350                    return Ok(vec![control_error_frame(
4351                        &frame,
4352                        "invalid_params",
4353                        "intent must be 'restart'",
4354                    )?]);
4355                }
4356                // A stamped daemon boots a newer approved generation only from a
4357                // durable restart intent, written here before the daemon exits.
4358                // Failing to write it never blocks the restart: the next start
4359                // then boots the last active generation and the newer one waits.
4360                if let Some(owner) = &self.config_runtime {
4361                    match owner
4362                        .on_blocking(|owner| owner.assign_daemon_restart())
4363                        .await
4364                    {
4365                        Ok(Some(generation)) => {
4366                            info!(
4367                                generation,
4368                                "daemon restart will warm up approved generation"
4369                            )
4370                        }
4371                        Ok(None) => {}
4372                        Err(error) => warn!(
4373                            %error,
4374                            "daemon restart intent not recorded; the next start boots the last active generation"
4375                        ),
4376                    }
4377                }
4378                let response = ClientControlResponse::DaemonShutdownIntent {
4379                    intent: "restart".to_owned(),
4380                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4381                };
4382                Ok(vec![control_response_body_frame(
4383                    &frame,
4384                    &response,
4385                    "ClientControlResponse::DaemonShutdownIntent",
4386                )?])
4387            }
4388            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4389            ClientControlRequest::CatalogList { module_id } => {
4390                self.handle_catalog_list(frame, module_id)
4391            }
4392            ClientControlRequest::RouteOpen {
4393                target,
4394                identity,
4395                consumer_identity,
4396                consumer_capabilities,
4397                role_versions,
4398                busy_refusals,
4399                admission_facts,
4400                scope,
4401                ..
4402            } => {
4403                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4404                    &frame.body,
4405                ) {
4406                    Ok(extensions) => extensions,
4407                    Err(err) => {
4408                        return Ok(vec![control_error_frame(
4409                            &frame,
4410                            "invalid_control_body",
4411                            format!("malformed route.open extensions: {err}"),
4412                        )?]);
4413                    }
4414                };
4415                self.handle_route_open(
4416                    ctx,
4417                    frame,
4418                    RouteOpenRequest {
4419                        target,
4420                        identity,
4421                        consumer_identity,
4422                        consumer_capabilities,
4423                        role_versions,
4424                        busy_refusals,
4425                        admission_facts,
4426                        scope,
4427                        accepts_close_reasons: extensions.accepts_close_reasons,
4428                    },
4429                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4430                )
4431                .await
4432            }
4433            ClientControlRequest::RoutePoll {
4434                route_channel,
4435                route_epoch,
4436                kind,
4437            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4438            ClientControlRequest::SupervisorList {} => {
4439                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4440                    self.agent_declarations.refuse(
4441                        self,
4442                        ctx,
4443                        control_error_frame(
4444                            &frame,
4445                            "busy",
4446                            "supervisor list work is at capacity; retry",
4447                        )?,
4448                    );
4449                    return Ok(Vec::new());
4450                };
4451                // Filesystem-backed diagnostics must not hold up this connection's reader.
4452                let handler = self.clone();
4453                let sink = ctx.egress.clone();
4454                tokio::spawn(
4455                    async move {
4456                        let _permit = permit;
4457                        let result = handler.handle_supervisor_list(frame.clone()).await;
4458                        let replies = match result {
4459                            Ok(replies) => replies,
4460                            Err(error) => {
4461                                control_error_frame(&frame, "backend_error", error.to_string())
4462                                    .into_iter()
4463                                    .collect()
4464                            }
4465                        };
4466                        for reply in replies {
4467                            if !matches!(
4468                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4469                                    .await,
4470                                Ok(Ok(()))
4471                            ) {
4472                                break;
4473                            }
4474                        }
4475                    }
4476                    .with_current_subscriber(),
4477                );
4478                Ok(Vec::new())
4479            }
4480            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4481                self.handle_supervisor_spawn_snapshot(frame)
4482            }
4483            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4484                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4485            }
4486            ClientControlRequest::SupervisorRestart {
4487                module_id,
4488                drain_timeout_ms,
4489            } => {
4490                self.log_supervisor_request_received(
4491                    ctx,
4492                    frame.header.corr,
4493                    ops::SUPERVISOR_RESTART,
4494                    Some(&module_id),
4495                    None,
4496                )?;
4497                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4498                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4499                    .await
4500            }
4501            ClientControlRequest::SupervisorSwap {
4502                module_id,
4503                ready_timeout_ms,
4504            } => {
4505                self.log_supervisor_request_received(
4506                    ctx,
4507                    frame.header.corr,
4508                    ops::SUPERVISOR_SWAP,
4509                    Some(&module_id),
4510                    None,
4511                )?;
4512                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4513                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4514                    .await
4515            }
4516            ClientControlRequest::SupervisorReload { module_id } => {
4517                self.log_supervisor_request_received(
4518                    ctx,
4519                    frame.header.corr,
4520                    ops::SUPERVISOR_RELOAD,
4521                    Some(&module_id),
4522                    None,
4523                )?;
4524                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4525                self.handle_supervisor_reload(frame, module_id, requester)
4526                    .await
4527            }
4528            ClientControlRequest::SupervisorRescan { preview } => {
4529                if !preview {
4530                    self.log_supervisor_request_received(
4531                        ctx,
4532                        frame.header.corr,
4533                        ops::SUPERVISOR_RESCAN,
4534                        None,
4535                        None,
4536                    )?;
4537                }
4538                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4539                let operation = self.handle_supervisor_rescan(
4540                    frame,
4541                    if preview {
4542                        RescanMode::Preview
4543                    } else {
4544                        RescanMode::Execute
4545                    },
4546                    requester,
4547                );
4548                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4549                    .await
4550            }
4551            ClientControlRequest::SupervisorRescanChecked {
4552                preview,
4553                candidate,
4554                expect,
4555            } => {
4556                self.observe_control_wait(
4557                    ctx,
4558                    None,
4559                    ops::SUPERVISOR_RESCAN,
4560                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4561                )
4562                .await
4563            }
4564            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4565                self.log_supervisor_request_received(
4566                    ctx,
4567                    frame.header.corr,
4568                    ops::SUPERVISOR_RELEASE_RESERVED,
4569                    Some(&module_id),
4570                    None,
4571                )?;
4572                self.handle_supervisor_release_reserved(frame, module_id)
4573                    .await
4574            }
4575            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4576                self.log_supervisor_request_received(
4577                    ctx,
4578                    frame.header.corr,
4579                    ops::SUPERVISOR_SET_ENABLED,
4580                    Some(&module_id),
4581                    Some(enabled),
4582                )?;
4583                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4584                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4585                    .await
4586            }
4587            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4588                self.handle_supervisor_health_probe(ctx, frame, module_id)
4589                    .await
4590            }
4591            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4592            ClientControlRequest::SupervisorRoutes { module_id } => {
4593                self.handle_supervisor_routes(frame, module_id)
4594            }
4595            ClientControlRequest::SupervisorProvenance { module_id } => {
4596                self.handle_supervisor_provenance(ctx, frame, module_id)
4597                    .await
4598            }
4599            ClientControlRequest::SupervisorStderrTail {
4600                module_id,
4601                max_lines,
4602                max_bytes,
4603            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4604            ClientControlRequest::SupervisorTerminals { module_id } => {
4605                self.handle_supervisor_terminals(ctx, frame, module_id)
4606                    .await
4607            }
4608        }
4609    }
4610
4611    fn log_supervisor_request_received(
4612        &self,
4613        ctx: &RouteCtx,
4614        corr: u64,
4615        op: &'static str,
4616        module_id: Option<&str>,
4617        enabled: Option<bool>,
4618    ) -> Result<(), RouterError> {
4619        let caller = self.supervisor_requester(ctx, corr)?;
4620        let caller = principal_label(&caller);
4621        // `Option` fields are recorded only when present, so a request with no
4622        // module id (rescan) or no enabled flag simply omits that field.
4623        info!(
4624            target: "control",
4625            op,
4626            module_id,
4627            enabled,
4628            connection_id = ctx.connection_id.get(),
4629            caller = %caller,
4630            "supervisor request received"
4631        );
4632        Ok(())
4633    }
4634
4635    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4636        Ok(self
4637            .registry
4638            .get_module_by_connection(ctx.connection_id)
4639            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4640            .map(|registration| Principal::Reserved {
4641                module_id: registration.manifest.module_id,
4642            })
4643            .unwrap_or(Principal::Direct))
4644    }
4645
4646    fn handle_module_control_request(
4647        &self,
4648        connection_id: ConnectionId,
4649        frame: Frame,
4650        request: ModuleControlRequestFromModule,
4651    ) -> Result<Vec<Frame>, RouterError> {
4652        match request {
4653            ModuleControlRequestFromModule::RouteAuthorize {
4654                principal,
4655                scope,
4656                target,
4657                expected,
4658            } => self.handle_route_authorize(
4659                connection_id,
4660                frame,
4661                principal,
4662                scope,
4663                target,
4664                expected,
4665            ),
4666            ModuleControlRequestFromModule::CatalogUpdate {
4667                provides,
4668                capabilities,
4669                ready,
4670            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4671            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4672                self.handle_catalog_update_role_declarations(
4673                    connection_id,
4674                    frame,
4675                    role_declarations,
4676                )
4677            }
4678            ModuleControlRequestFromModule::LiveRoots {} => {
4679                let registered = self
4680                    .registry
4681                    .get_module_by_connection(connection_id)
4682                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4683                let Some(registration) = registered else {
4684                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4685                };
4686                let response = self
4687                    .forwarding
4688                    .live_roots(&registration.manifest.module_id)
4689                    .map_err(RouterError::Forwarding)?;
4690                Ok(vec![control_response_body_frame(
4691                    &frame,
4692                    &response,
4693                    "ModuleControlResponseToModule::LiveRoots",
4694                )?])
4695            }
4696            ModuleControlRequestFromModule::AgentCommands {
4697                started,
4698                finished,
4699                known,
4700            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4701            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4702                self.handle_scope_sync(connection_id, frame, generation, scopes)
4703            }
4704            ModuleControlRequestFromModule::ScopeApply {
4705                generation,
4706                upsert,
4707                end,
4708            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4709            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4710                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4711            }
4712            _ => Ok(vec![control_error_frame(
4713                &frame,
4714                "unsupported_control_frame",
4715                "unsupported module control operation",
4716            )?]),
4717        }
4718    }
4719
4720    fn handle_scope_served_by(
4721        &self,
4722        connection_id: ConnectionId,
4723        frame: Frame,
4724    ) -> Result<Vec<Frame>, RouterError> {
4725        let registered = self
4726            .registry
4727            .get_module_by_connection(connection_id)
4728            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4729        let Some(registered) = registered else {
4730            return Ok(vec![control_error_frame(
4731                &frame,
4732                "not_registered",
4733                "scope.served_by requires an active module registration owned by this connection",
4734            )?]);
4735        };
4736        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4737        {
4738            Ok(request) => request,
4739            Err(err) => {
4740                return Ok(vec![control_error_frame(
4741                    &frame,
4742                    "invalid_control_body",
4743                    format!("malformed scope.served_by body: {err}"),
4744                )?])
4745            }
4746        };
4747        let answer = self
4748            .scopes
4749            .read()
4750            .unwrap_or_else(|poisoned| poisoned.into_inner())
4751            .served_by(
4752                &registered.manifest.module_id,
4753                &request.scope_ref,
4754                request.scope_epoch,
4755                &request.module_id,
4756            );
4757        let reply = subc_control::ScopeServedByReply::new(
4758            answer,
4759            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4760        );
4761        Ok(vec![control_response_body_frame(
4762            &frame,
4763            &reply,
4764            "ScopeServedByReply",
4765        )?])
4766    }
4767
4768    /// Explicit test-only phone policy; daemon configuration cannot select it.
4769    #[cfg(any(test, feature = "test-support"))]
4770    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
4771        self.operator_app_policy.phone_enabled = enabled;
4772        self
4773    }
4774
4775    /// Resolve folders before taking the scope-table lock: a slow filesystem
4776    /// must not hold up admissions for unrelated scoped routes.
4777    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
4778        let mut scopes = ScopeRecords::from(scopes);
4779        for (index, record) in scopes.records.iter_mut().enumerate() {
4780            if let Some(refusal) = Self::canonicalize_workdir(record) {
4781                scopes.refusals.insert(index, refusal);
4782            }
4783        }
4784        scopes
4785    }
4786
4787    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
4788        let workdir = record.workdir.as_mut()?;
4789        let path = std::path::Path::new(workdir);
4790        if !path.is_absolute() {
4791            return Some((
4792                error_codes::INVALID_WORKDIR,
4793                "workdir must be absolute".to_string(),
4794            ));
4795        }
4796        match ProjectRootId::from_path_allowing_missing(path) {
4797            Ok(root) => match root.as_path().to_str() {
4798                Some(canonical) => {
4799                    *workdir = canonical.to_string();
4800                    None
4801                }
4802                None => Some((
4803                    error_codes::INVALID_WORKDIR,
4804                    "canonical workdir is not UTF-8".to_string(),
4805                )),
4806            },
4807            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
4808        }
4809    }
4810
4811    /// `scope.sync`: the owner is the module registered on this connection.
4812    /// A connection with no registration (every client connection, `direct`
4813    /// included) is refused `not_registered` before the table is consulted.
4814    fn handle_scope_sync(
4815        &self,
4816        connection_id: ConnectionId,
4817        frame: Frame,
4818        generation: u64,
4819        scopes: Vec<ScopeRecord>,
4820    ) -> Result<Vec<Frame>, RouterError> {
4821        self.handle_scope_change(connection_id, frame, generation, scopes, None)
4822    }
4823
4824    fn handle_scope_change(
4825        &self,
4826        connection_id: ConnectionId,
4827        frame: Frame,
4828        generation: u64,
4829        scopes: Vec<ScopeRecord>,
4830        end: Option<Vec<ScopeEnd>>,
4831    ) -> Result<Vec<Frame>, RouterError> {
4832        let is_apply = end.is_some();
4833        let Some(registration) = self
4834            .registry
4835            .get_module_by_connection(connection_id)
4836            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4837        else {
4838            return Ok(vec![control_error_frame(
4839                &frame,
4840                "not_registered",
4841                "scope.sync and scope.apply require an active module registration owned by this connection",
4842            )?]);
4843        };
4844        let owner = registration.manifest.module_id;
4845        let scopes = Self::prepare_scope_records(scopes);
4846        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
4847        let is_current_launch = |connection: ConnectionId| {
4848            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
4849        };
4850        // Lock order is the scope table, then the forwarding table: the new
4851        // tags are published, and the routes the change closes are selected,
4852        // while the scope table is still write-locked, so no admission can read
4853        // a record whose tag is not yet published.
4854        let mut table = self
4855            .scopes
4856            .write()
4857            .unwrap_or_else(|poisoned| poisoned.into_inner());
4858        let outcome = match end {
4859            Some(end) => table.apply(
4860                &owner,
4861                connection_id,
4862                is_current_launch,
4863                generation,
4864                scopes,
4865                end,
4866            ),
4867            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
4868        };
4869        let drained = match &outcome {
4870            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
4871            Err(_) => Vec::new(),
4872        };
4873        let has_deadlines = outcome.is_ok() && table.has_deadlines();
4874        drop(table);
4875        if has_deadlines {
4876            self.scope_deadline_added.notify_one();
4877        }
4878        match outcome {
4879            Ok(applied) => {
4880                let counts = ScopeOutcomeCounts::of(&applied.results);
4881                info!(
4882                    owner = %owner,
4883                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4884                    generation,
4885                    records = applied.results.len(),
4886                    created = counts.created,
4887                    replaced = counts.replaced,
4888                    updated = counts.updated,
4889                    unchanged = counts.unchanged,
4890                    refused = counts.refused,
4891                    ended = applied.ended.len(),
4892                    tag_changes = applied.tag_changes.len(),
4893                    routes_closed = drained.len(),
4894                    "scope change accepted"
4895                );
4896                // An accepted scope change can still refuse individual records, and the
4897                // owner is the only party that sees the reply. Name them here so
4898                // an operator can tell a refused session from a missing one
4899                // without the owner's logs. Capped so a call that refuses
4900                // thousands cannot flood the log; the count above is complete.
4901                for refused in applied
4902                    .results
4903                    .iter()
4904                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
4905                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
4906                {
4907                    warn!(
4908                        owner = %owner,
4909                        generation,
4910                        scope_ref = %refused.scope_ref,
4911                        scope_epoch = refused.scope_epoch,
4912                        code = refused.code.as_deref().unwrap_or(""),
4913                        "scope record refused"
4914                    );
4915                }
4916                self.close_scope_drained_routes(drained);
4917                let response = if is_apply {
4918                    ModuleControlResponseToModule::ScopeApply {
4919                        generation,
4920                        results: applied.results,
4921                        end_results: applied.end_results,
4922                        ended: applied.ended,
4923                    }
4924                } else {
4925                    ModuleControlResponseToModule::ScopeSync {
4926                        generation,
4927                        results: applied.results,
4928                        ended: applied.ended,
4929                    }
4930                };
4931                Ok(vec![control_response_body_frame(
4932                    &frame,
4933                    &response,
4934                    "scope change response",
4935                )?])
4936            }
4937            Err(refusal) => {
4938                info!(
4939                    owner = %owner,
4940                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4941                    generation,
4942                    code = refusal.code,
4943                    "scope change refused"
4944                );
4945                Ok(vec![control_error_frame(
4946                    &frame,
4947                    refusal.code,
4948                    refusal.message,
4949                )?])
4950            }
4951        }
4952    }
4953
4954    /// Notify both endpoints of routes drained by a scope change.
4955    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
4956        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
4957    }
4958
4959    /// Re-authorize a stored source on a principal the module supplies.
4960    ///
4961    /// That principal carries no spawn or authority epoch, so this reply never
4962    /// conveys a caller attestation or a first-party mark, and a provider must
4963    /// not apply automatic grants on anything it authorizes.
4964    fn handle_route_authorize(
4965        &self,
4966        connection_id: ConnectionId,
4967        frame: Frame,
4968        principal: Principal,
4969        scope: subc_protocol::scope::RouteAuthorizeScope,
4970        target: String,
4971        expected: subc_protocol::scope::RouteAuthorizeExpected,
4972    ) -> Result<Vec<Frame>, RouterError> {
4973        use crate::scopes::admission::{admit_route, AdmissionMode};
4974        use subc_protocol::scope::{
4975            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
4976        };
4977        let registry = self
4978            .registry
4979            .route_admission_snapshot()
4980            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4981        let owner_configured = match &scope.owner {
4982            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
4983            _ => false,
4984        };
4985        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
4986        let answer = {
4987            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
4988            let permitted = registry
4989                .iter()
4990                .find(|r| r.connection_id == connection_id)
4991                .is_some_and(|r| {
4992                    scopes.is_federated_owner(&Principal::Reserved {
4993                        module_id: r.module_id.clone(),
4994                    }) && r.capabilities.as_ref().is_some_and(|caps| {
4995                        caps.provides
4996                            .iter()
4997                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
4998                    })
4999                });
5000            if !permitted {
5001                drop(scopes);
5002                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
5003                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
5004            }
5005            admit_route(
5006                &scopes,
5007                &registry,
5008                &principal,
5009                &target,
5010                Some(&selector),
5011                owner_configured,
5012                AdmissionMode::Authorize(&expected),
5013            )
5014        };
5015        let response = match answer {
5016            Ok(admission) => {
5017                let mut response = RouteAuthorizeResponse::new(
5018                    RouteAuthorizeOutcome::Authorized,
5019                    "route admission authorized",
5020                );
5021                response.content_version = admission.content_version;
5022                response
5023            }
5024            Err(refusal) => refusal.response(),
5025        };
5026        Ok(vec![control_response_body_frame(
5027            &frame,
5028            &response,
5029            "RouteAuthorizeResponse",
5030        )?])
5031    }
5032
5033    /// `scope.describe`: any registered module may read any scope, because a
5034    /// provider must read the scope a route it serves is stamped with.
5035    fn handle_scope_describe(
5036        &self,
5037        connection_id: ConnectionId,
5038        frame: Frame,
5039        owner: Principal,
5040        scope_ref: String,
5041    ) -> Result<Vec<Frame>, RouterError> {
5042        let registered = self
5043            .registry
5044            .get_module_by_connection(connection_id)
5045            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5046        let Some(registered) = registered else {
5047            return Ok(vec![control_error_frame(
5048                &frame,
5049                "not_registered",
5050                "scope.describe requires an active module registration owned by this connection",
5051            )?]);
5052        };
5053        let scopes = self
5054            .scopes
5055            .read()
5056            .unwrap_or_else(|poisoned| poisoned.into_inner());
5057        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5058            return Ok(vec![control_error_frame(
5059                &frame,
5060                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5061                "scope.describe of the federated owner requires scope-federated/v1",
5062            )?]);
5063        }
5064        let mut description = scopes.describe(&owner, &scope_ref);
5065        drop(scopes);
5066        if owner
5067            != (Principal::Reserved {
5068                module_id: registered.manifest.module_id.clone(),
5069            })
5070        {
5071            if let Some(facts) = description
5072                .stamp
5073                .as_mut()
5074                .and_then(|stamp| stamp.attributes.federated.as_mut())
5075            {
5076                facts.stamp_required = false;
5077            }
5078        }
5079        // Describe readers also decode strict ScopeAttributes. Attribution is
5080        // safe to omit unless the requesting module declares it understands it.
5081        if !registered
5082            .manifest
5083            .capabilities
5084            .as_ref()
5085            .is_some_and(|caps| {
5086                caps.provides
5087                    .iter()
5088                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5089            })
5090        {
5091            if let Some(stamp) = description.stamp.as_mut() {
5092                stamp.attributes.on_behalf_of_agent = None;
5093            }
5094        }
5095        if !registered
5096            .manifest
5097            .capabilities
5098            .as_ref()
5099            .is_some_and(|caps| {
5100                caps.provides
5101                    .iter()
5102                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5103            })
5104        {
5105            if let Some(stamp) = description.stamp.as_mut() {
5106                stamp.attributes.flow_version = None;
5107                stamp.attributes.flow_code_hash = None;
5108                stamp.attributes.flow_install_id = None;
5109            }
5110        }
5111        let owner_configured = match &owner {
5112            // Ask whether the owner is configured (`is_configured`), not
5113            // whether it is on the roster (`get(..).is_some()`): a supervised
5114            // module's process can register and describe a scope before the
5115            // supervisor has put it on the roster.
5116            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5117            _ => false,
5118        };
5119        let response = ModuleControlResponseToModule::ScopeDescribe {
5120            status: description.status,
5121            scope_epoch: description.scope_epoch,
5122            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5123            owner_synced: description.owner_synced,
5124            owner_configured,
5125            scope: description.stamp,
5126        };
5127        Ok(vec![control_response_body_frame(
5128            &frame,
5129            &response,
5130            "ModuleControlResponseToModule::ScopeDescribe",
5131        )?])
5132    }
5133
5134    fn handle_catalog_update_role_declarations(
5135        &self,
5136        connection_id: ConnectionId,
5137        frame: Frame,
5138        role_declarations: serde_json::Value,
5139    ) -> Result<Vec<Frame>, RouterError> {
5140        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5141            return Ok(vec![control_error_frame(
5142                &frame,
5143                "invalid_role_declarations",
5144                err.to_string(),
5145            )?]);
5146        }
5147        let declarations = serde_json::from_value(role_declarations)
5148            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5149        if self
5150            .registry
5151            .replace_role_declarations_for_connection(connection_id, declarations)
5152            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5153            .is_none()
5154        {
5155            return Ok(vec![control_error_frame(
5156                &frame,
5157                "not_registered",
5158                "catalog.update_role_declarations requires an active module registration owned by this connection",
5159            )?]);
5160        }
5161        control_response_body_frame(
5162            &frame,
5163            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5164            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5165        )
5166        .map(|frame| vec![frame])
5167    }
5168
5169    fn handle_catalog_update(
5170        &self,
5171        connection_id: ConnectionId,
5172        frame: Frame,
5173        provides: Vec<ProviderRole>,
5174        capabilities: Option<CapabilityDeclarations>,
5175        ready: Option<bool>,
5176    ) -> Result<Vec<Frame>, RouterError> {
5177        self.refresh_capability_requirements();
5178        let Some(registration) = self
5179            .registry
5180            .get_module_by_connection(connection_id)
5181            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5182        else {
5183            return Ok(vec![control_error_frame(
5184                &frame,
5185                "not_registered",
5186                "catalog.update requires an active module registration owned by this connection",
5187            )?]);
5188        };
5189
5190        if let Some(message) =
5191            catalog_update_frozen_field_message(&registration.manifest, &provides)
5192        {
5193            return Ok(vec![control_error_frame(
5194                &frame,
5195                "catalog_update_frozen_field",
5196                message,
5197            )?]);
5198        }
5199
5200        let mut candidate = registration.manifest.clone();
5201        candidate.provides = provides.clone();
5202        candidate.capabilities = capabilities
5203            .clone()
5204            .or_else(|| registration.manifest.capabilities.clone());
5205        if let Some(rich_ui) = &candidate.rich_ui {
5206            if let Err(err) = rich_ui.validate() {
5207                return Ok(vec![control_error_frame(
5208                    &frame,
5209                    "invalid_manifest",
5210                    err.to_string(),
5211                )?]);
5212            }
5213        }
5214        if let Err(err) = candidate.validate_capability_grammar() {
5215            return Ok(vec![control_error_frame(
5216                &frame,
5217                "invalid_capability_grammar",
5218                err.to_string(),
5219            )?]);
5220        }
5221
5222        // Updates must honor the same reserved owner as initial registration;
5223        // otherwise an empty HELLO could acquire the claim after admission.
5224        let mut conflicts = self
5225            .capability_evaluator
5226            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5227        if let Some(conflict) = conflicts.first() {
5228            let message = format!(
5229                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5230                conflict.capability, conflict.claimants[0], candidate.module_id
5231            );
5232            for conflict in &mut conflicts {
5233                conflict.source = DuplicateClaimSource::CatalogUpdate;
5234            }
5235            log_duplicate_claim_events(conflicts);
5236            return Ok(vec![control_error_frame(
5237                &frame,
5238                "reserved_capability",
5239                message,
5240            )?]);
5241        }
5242
5243        let updated = match self.registry.replace_catalog_for_connection(
5244            connection_id,
5245            provides,
5246            capabilities,
5247            ready,
5248        ) {
5249            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5250                return Ok(vec![control_error_frame(
5251                    &frame,
5252                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5253                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5254                )?])
5255            }
5256            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5257                return Ok(vec![control_error_frame(
5258                    &frame,
5259                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5260                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5261                )?])
5262            }
5263            result => {
5264                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5265            }
5266        };
5267        if updated.is_none() {
5268            return Ok(vec![control_error_frame(
5269                &frame,
5270                "not_registered",
5271                "catalog.update requires an active module registration owned by this connection",
5272            )?]);
5273        }
5274        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5275            log_duplicate_claim_events(
5276                self.capability_evaluator
5277                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5278            );
5279        }
5280        if capability_census_trigger(
5281            registration.manifest.capabilities.as_ref(),
5282            updated
5283                .as_ref()
5284                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5285        ) {
5286            self.enforce_capability_denies();
5287        }
5288        self.refresh_capability_requirements();
5289
5290        let response = ModuleControlResponseToModule::CatalogUpdate {};
5291        control_response_body_frame(
5292            &frame,
5293            &response,
5294            "ModuleControlResponseToModule::CatalogUpdate",
5295        )
5296        .map(|frame| vec![frame])
5297    }
5298
5299    pub(crate) fn with_activity_ledger_config(
5300        mut self,
5301        run_dir: &Path,
5302        incarnation: String,
5303        config: crate::activity::ActivityConfig,
5304    ) -> Self {
5305        self.activity = Some(crate::activity::ActivityLedger::open_config(
5306            run_dir.join("activity.jsonl"),
5307            incarnation,
5308            config,
5309        ));
5310        self.supervisor.set_activity(self.activity.clone());
5311        self
5312    }
5313
5314    pub(crate) async fn configure_activity(
5315        &self,
5316        config: crate::activity::ActivityConfig,
5317    ) -> Result<(), &'static str> {
5318        match &self.activity {
5319            Some(ledger) => ledger.configure(config).await,
5320            None => Ok(()),
5321        }
5322    }
5323
5324    fn cancel_activity_subscription(
5325        &self,
5326        ctx: &RouteCtx,
5327        frame: &Frame,
5328    ) -> Result<bool, RouterError> {
5329        let key = (ctx.connection_id, frame.header.corr);
5330        let mut streams = self
5331            .activity_streams
5332            .lock()
5333            .unwrap_or_else(|p| p.into_inner());
5334        // A subscription still being set up is cancelled through the
5335        // reservation the reader made, under the same stream lock.
5336        match streams.remove(&key) {
5337            Some(task) => task.abort(),
5338            None if self.activity_reservations.cancel(key) => {}
5339            None => return Ok(false),
5340        }
5341        drop(streams);
5342        let end = Frame::build_with_version(
5343            response_version(frame),
5344            FrameType::StreamEnd,
5345            control_flags(),
5346            0,
5347            0,
5348            frame.header.corr,
5349            Vec::new(),
5350        )
5351        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5352        let sink = ctx.egress.clone();
5353        tokio::spawn(async move {
5354            let _ = sink.send(end).await;
5355        });
5356        Ok(true)
5357    }
5358
5359    async fn handle_activity_read(
5360        &self,
5361        ctx: &RouteCtx,
5362        frame: Frame,
5363    ) -> Result<Vec<Frame>, RouterError> {
5364        #[cfg(test)]
5365        {
5366            let pause = self
5367                .activity_request_pause
5368                .lock()
5369                .unwrap()
5370                .clone()
5371                .filter(|pause| pause.connection == ctx.connection_id);
5372            if let Some(pause) = pause {
5373                let _cancelled = ActivityRequestCancellation(pause.clone());
5374                pause.started.notify_one();
5375                std::future::pending::<()>().await;
5376            }
5377        }
5378        use subc_control::{
5379            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5380            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5381        };
5382        #[derive(Deserialize)]
5383        struct Identity {
5384            #[serde(default)]
5385            consumer_identity: Option<ConsumerIdentity>,
5386        }
5387        // A registration channel or claim-bound connection carries its module in
5388        // its binding, so no request field can name another principal, and its
5389        // subscription ends when the bound spawn's authority does.
5390        let mut bound_spawn = None;
5391        let legacy = match self.activity_reader(ctx.connection_id) {
5392            channel_operations::ActivityReader::Module { module_id, spawn } => {
5393                bound_spawn = Some(spawn);
5394                Some(Ok(Principal::Reserved { module_id }))
5395            }
5396            // Refused outright: falling back to `direct` would admit it.
5397            channel_operations::ActivityReader::Refused => {
5398                return Ok(vec![control_error_frame(
5399                    &frame,
5400                    ACTIVITY_READ_FORBIDDEN,
5401                    "helper, relay and retired connections cannot read activity",
5402                )?]);
5403            }
5404            channel_operations::ActivityReader::Legacy => None,
5405        };
5406        // A registered module connection already identifies its caller. Ignore
5407        // consumer_identity there so a module cannot borrow a mirror's identity.
5408        // Only separate consumer connections use the Direct/nonce trust boundary.
5409        let principal = match legacy {
5410            Some(principal) => principal,
5411            None => match self
5412                .forwarding
5413                .module_id_for_connection(ctx.connection_id)
5414                .map_err(RouterError::Forwarding)?
5415            {
5416                Some(module_id) => Ok(Principal::Reserved { module_id }),
5417                None => {
5418                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5419                        Ok(identity) => identity,
5420                        Err(_) => {
5421                            return Ok(vec![control_error_frame(
5422                                &frame,
5423                                ACTIVITY_MALFORMED,
5424                                "malformed activity read",
5425                            )?])
5426                        }
5427                    };
5428                    self.route_open_principal(
5429                        ctx.connection_id,
5430                        &frame,
5431                        identity.consumer_identity,
5432                    )?
5433                }
5434            },
5435        };
5436        let admitted = matches!(principal, Ok(Principal::Direct))
5437            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5438        if !admitted {
5439            return Ok(vec![control_error_frame(
5440                &frame,
5441                ACTIVITY_READ_FORBIDDEN,
5442                "activity reads require an operator or trusted mirror principal",
5443            )?]);
5444        }
5445        let Some(ledger) = &self.activity else {
5446            return Ok(vec![control_error_frame(
5447                &frame,
5448                ACTIVITY_UNAVAILABLE,
5449                "activity ledger unavailable",
5450            )?]);
5451        };
5452        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5453            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5454        {
5455            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5456                Ok(request) => ledger.query(request).await,
5457                Err(_) => Err(ACTIVITY_MALFORMED),
5458            };
5459            return match result {
5460                Ok(reply) => Ok(vec![control_response_body_frame(
5461                    &frame,
5462                    &reply,
5463                    ops::ACTIVITY_QUERY,
5464                )?]),
5465                Err(code) => Ok(vec![control_error_frame(
5466                    &frame,
5467                    code,
5468                    "activity query refused",
5469                )?]),
5470            };
5471        }
5472        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5473            Ok(request) => request,
5474            Err(_) => {
5475                return Ok(vec![control_error_frame(
5476                    &frame,
5477                    ACTIVITY_MALFORMED,
5478                    "malformed activity subscription",
5479                )?])
5480            }
5481        };
5482        let mut subscription = match ledger.subscribe(request.since).await {
5483            Ok(subscription) => subscription,
5484            Err(code) => {
5485                return Ok(vec![control_error_frame(
5486                    &frame,
5487                    code,
5488                    "activity subscription refused",
5489                )?])
5490            }
5491        };
5492        let key = (ctx.connection_id, frame.header.corr);
5493        let sink = ctx.egress.clone();
5494        let mut streams = self
5495            .activity_streams
5496            .lock()
5497            .unwrap_or_else(|p| p.into_inner());
5498        streams.retain(|_, task| !task.is_finished());
5499        if self.activity_reservations.cancelled(key) {
5500            return Ok(Vec::new()); // Its CANCEL already sent STREAM_END.
5501        }
5502        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5503            return Ok(vec![control_error_frame(
5504                &frame,
5505                "duplicate_subscription",
5506                "activity subscription correlation id already in use",
5507            )?]);
5508        }
5509        let stream = async move {
5510            loop {
5511                let entry = if let Some(entry) = subscription.replay.pop_front() {
5512                    Some(entry)
5513                } else {
5514                    subscription.receiver.recv().await
5515                };
5516                let Some(entry) = entry else {
5517                    break;
5518                };
5519                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5520                    return;
5521                };
5522                let Ok(next) = Frame::build_with_version(
5523                    response_version(&frame),
5524                    FrameType::StreamData,
5525                    control_flags(),
5526                    0,
5527                    0,
5528                    frame.header.corr,
5529                    body,
5530                ) else {
5531                    return;
5532                };
5533                if sink.send(next).await.is_err() {
5534                    return;
5535                }
5536            }
5537            // Dropping a full subscriber's sender drains its accepted entries
5538            // before the terminal error, preserving their order on the wire.
5539            if let Some(code) = subscription.terminal_code() {
5540                if let Ok(end) =
5541                    control_error_frame(&frame, code, "activity subscriber fell behind")
5542                {
5543                    let _ = sink.send(end).await;
5544                }
5545            }
5546        };
5547        // The spawn's retirement revokes this connection's authority. End the
5548        // subscription then, rather than when the connection's close is
5549        // eventually processed or the next entry fails to send.
5550        let task = tokio::spawn(async move {
5551            match bound_spawn {
5552                Some(spawn) => {
5553                    tokio::select! {
5554                        () = stream => {}
5555                        () = spawn.wait_closed() => {}
5556                    }
5557                }
5558                None => stream.await,
5559            }
5560        });
5561        streams.insert(key, task.abort_handle());
5562        Ok(Vec::new())
5563    }
5564
5565    async fn handle_activity_record(
5566        &self,
5567        ctx: &RouteCtx,
5568        frame: Frame,
5569    ) -> Result<Vec<Frame>, RouterError> {
5570        use subc_control::{
5571            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5572            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5573        };
5574        let result = async {
5575            let module = self
5576                .forwarding
5577                .module_id_for_connection(ctx.connection_id)
5578                .ok()
5579                .flatten()
5580                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5581            let request: ActivityRecordRequest =
5582                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5583            crate::activity::validate(&module, &request)?;
5584            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5585            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5586            let at_ms = std::time::SystemTime::now()
5587                .duration_since(std::time::UNIX_EPOCH)
5588                .unwrap_or_default()
5589                .as_millis() as u64;
5590            ledger.record(module, request, actor, at_ms).await
5591        }
5592        .await;
5593        match result {
5594            Ok(entry) => Ok(vec![control_response_body_frame(
5595                &frame,
5596                &ActivityRecordResponse { seq: entry.seq },
5597                "activity.record",
5598            )?]),
5599            Err(code) => Ok(vec![control_error_frame(
5600                &frame,
5601                code,
5602                "activity recording refused",
5603            )?]),
5604        }
5605    }
5606
5607    fn activity_actor(
5608        &self,
5609        connection: ConnectionId,
5610        module: &str,
5611        on: Option<&subc_control::ActivityOn>,
5612    ) -> Result<subc_control::ActivityActor, &'static str> {
5613        use crate::forwarding::{DataRoute, DataRouteState};
5614        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5615        let principal = |id: &str| Principal::Reserved {
5616            module_id: id.to_owned(),
5617        };
5618        let mut actor = ActivityActor {
5619            principal: principal(module),
5620            scope_owner: None,
5621            agent_id: None,
5622            run_id: None,
5623            flow_id: None,
5624            project_root: None,
5625            workdir: None,
5626            project_id: None,
5627        };
5628        let scope = match on {
5629            None => return Ok(actor),
5630            Some(ActivityOn::Scope(scope)) => {
5631                let selector = subc_protocol::scope::ScopeSelector::new(
5632                    principal(module),
5633                    scope.scope_ref.clone(),
5634                    Some(scope.epoch),
5635                );
5636                self.scopes
5637                    .read()
5638                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5639                    .attribute(&principal(module), module, &selector, true)
5640                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5641            }
5642            Some(ActivityOn::Route(route)) => {
5643                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5644                    .forwarding
5645                    .lookup_data_route(connection, route.channel, route.epoch)
5646                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5647                else {
5648                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5649                };
5650                if binding.module_id != module {
5651                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5652                }
5653                actor.principal = binding.principal.clone();
5654                actor.project_root = binding
5655                    .project_root
5656                    .as_ref()
5657                    .map(|root| root.as_path().to_path_buf());
5658                let Some(bound) = &binding.scope else {
5659                    return Ok(actor);
5660                };
5661                let owner = principal(&bound.owner);
5662                let selector = subc_protocol::scope::ScopeSelector::new(
5663                    owner.clone(),
5664                    bound.scope_ref.clone(),
5665                    Some(bound.tag.scope_epoch),
5666                );
5667                let admitted = self
5668                    .scopes
5669                    .read()
5670                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5671                    .attribute(&owner, module, &selector, true)
5672                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5673                if admitted.tag != bound.tag {
5674                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5675                }
5676                admitted
5677            }
5678        };
5679        actor.scope_owner = Some(scope.stamp.owner);
5680        actor.agent_id = scope.stamp.attributes.agent_id;
5681        actor.run_id = scope.stamp.attributes.run_id;
5682        actor.flow_id = scope.stamp.attributes.flow_id;
5683        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5684        actor.project_id = scope.stamp.project_id;
5685        Ok(actor)
5686    }
5687
5688    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5689        let module_id = self
5690            .claims
5691            .binding(connection)
5692            .filter(|binding| {
5693                binding.consumer_live(connection) && binding.registration.authority.alive()
5694            })
5695            .map(|binding| binding.registration.module_id.clone())
5696            .or_else(|| {
5697                self.registry
5698                    .module_id_for_connection(connection)
5699                    .ok()
5700                    .flatten()
5701            });
5702        let principal = module_id
5703            .map(|module_id| format!("reserved:{module_id}"))
5704            .unwrap_or_else(|| "direct".to_owned());
5705        self.control_usage
5706            .lock()
5707            .unwrap_or_else(|poisoned| poisoned.into_inner())
5708            .record(op, &principal);
5709    }
5710
5711    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5712        self.refresh_capability_requirements();
5713        // A bare connection count is ambiguous between many clients holding a
5714        // route each and one client accumulating hundreds, so publish the
5715        // concentration alongside it. Route state is best-effort here: a
5716        // diagnostic endpoint must still answer if the forwarding lock is
5717        // contended.
5718        let mut counters = self.counters.snapshot();
5719        if let Some(obj) = counters.as_object_mut() {
5720            obj.insert(
5721                "control_usage".into(),
5722                self.control_usage
5723                    .lock()
5724                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5725                    .snapshot(),
5726            );
5727        }
5728        let losses = self.resource_tracker.loss_diagnostics();
5729        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5730            if let Some(obj) = counters.as_object_mut() {
5731                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5732            }
5733        }
5734        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5735            obj.insert(
5736                "activity_unparseable_lines".into(),
5737                ledger.read_errors().into(),
5738            );
5739            obj.insert(
5740                "activity_lifecycle_append_failures".into(),
5741                ledger.lifecycle_failures().into(),
5742            );
5743            obj.insert(
5744                "activity_started_digest_skips".into(),
5745                ledger.lifecycle_digest_skips().into(),
5746            );
5747        }
5748        if let (Ok((connections_with_routes, max)), Some(obj)) = (
5749            self.forwarding.client_route_concentration(),
5750            counters.as_object_mut(),
5751        ) {
5752            obj.insert(
5753                "client_connections_with_routes".into(),
5754                connections_with_routes.into(),
5755            );
5756            obj.insert("max_routes_on_one_connection".into(), max.into());
5757        }
5758        // A module that is being fast-refused and a module that is fine look
5759        // identical from a client that retries and succeeds, so name the open
5760        // breakers here. This rides the existing free-form counters object
5761        // rather than a new wire field, so no sibling that deserializes
5762        // `ServerDescribe` has to be rebuilt to keep reading it.
5763        if let (Some(open_breakers), Some(obj)) = (
5764            self.route_bind_breakers.open_snapshot(),
5765            counters.as_object_mut(),
5766        ) {
5767            obj.insert("route_bind_breakers_open".into(), open_breakers);
5768        }
5769        // A daemon whose local endpoint could not be bound keeps serving TCP,
5770        // and the connection file names no endpoint. Name the reason here, in
5771        // the free-form counters object, so an operator reading daemon facts
5772        // sees it without searching the log, and no wire field changes.
5773        if let (Some(reason), Some(obj)) = (
5774            self.local_endpoint_unavailable.clone(),
5775            counters.as_object_mut(),
5776        ) {
5777            obj.insert("local_endpoint_unavailable".into(), reason.into());
5778        }
5779        let response = ClientControlResponse::ServerDescribe {
5780            protocol_ver: PROTOCOL_VERSION,
5781            subc_ops: subc_ops(),
5782            capabilities: self.describe_capabilities(),
5783            connected_clients: self.connected_clients.count(),
5784            counters: Some(counters),
5785            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
5786            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
5787            capability_requirements: self.capability_requirement_statuses(),
5788            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
5789            config_path: self
5790                .rescan
5791                .as_ref()
5792                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
5793        };
5794        Ok(vec![control_response_body_frame(
5795            &frame,
5796            &response,
5797            "ClientControlResponse::ServerDescribe",
5798        )?])
5799    }
5800
5801    fn handle_catalog_list(
5802        &self,
5803        frame: Frame,
5804        module_id: Option<String>,
5805    ) -> Result<Vec<Frame>, RouterError> {
5806        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
5807        Ok(vec![Frame::build_with_version(
5808            response_version(&frame),
5809            FrameType::Response,
5810            control_flags(),
5811            0,
5812            0,
5813            frame.header.corr,
5814            body,
5815        )
5816        .map_err(RouterError::FrameBuild)?])
5817    }
5818
5819    #[cfg(test)]
5820    fn uncached_catalog_list(
5821        &self,
5822        corr: u64,
5823        module_id: Option<&str>,
5824    ) -> Result<ClientControlResponse, RouterError> {
5825        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
5826    }
5827
5828    fn catalog_list_snapshot(
5829        &self,
5830        corr: u64,
5831        module_id: Option<&str>,
5832        include_declarations: bool,
5833    ) -> Result<ClientControlResponse, RouterError> {
5834        let (generation, modules) = self
5835            .registry
5836            .list_modules_with_nonce_verification()
5837            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
5838        let entries = modules
5839            .into_iter()
5840            .filter(|(registration, _)| {
5841                module_id
5842                    .map(|wanted| registration.manifest.module_id == wanted)
5843                    .unwrap_or(true)
5844            })
5845            .map(|(registration, nonce_verified)| {
5846                let entry = self
5847                    .catalog_discovery_entry(&registration, include_declarations)
5848                    .map_err(|err| RouterError::backend(0, corr, err))?;
5849                let not_ready = self.not_ready_reason(&registration);
5850                let mut entry = entry;
5851                entry.roles = registration.manifest.provides;
5852                entry.control_ops = registration.control_ops;
5853                Ok(entry
5854                    .with_ready(not_ready.is_none())
5855                    .with_display_name(registration.manifest.display_name)
5856                    .with_not_ready(not_ready)
5857                    .with_module_version(Some(registration.manifest.module_version))
5858                    .with_provenance(registration.manifest.provenance)
5859                    .with_capabilities(registration.manifest.capabilities)
5860                    .with_self_signals(registration.manifest.self_signals)
5861                    .with_events(registration.manifest.events)
5862                    .with_operation_delivery(registration.manifest.operation_delivery)
5863                    .with_operation_payload(registration.manifest.operation_payload)
5864                    .with_flow_operations(registration.manifest.flow_operations)
5865                    .with_operation_deferral(registration.manifest.operation_deferral)
5866                    .with_confirm_operations(registration.manifest.confirm_operations)
5867                    .with_rich_ui(registration.manifest.rich_ui)
5868                    .with_role_declarations(registration.manifest.role_declarations)
5869                    .with_nonce_verified(nonce_verified))
5870            })
5871            .collect::<Result<Vec<_>, RouterError>>()?;
5872        Ok(ClientControlResponse::CatalogList {
5873            generation,
5874            modules: entries,
5875            subc_ops: subc_ops(),
5876        })
5877    }
5878
5879    /// The caller fields for a refusal that only has the raw request frame,
5880    /// such as the connection-level admission refusal sent before the request
5881    /// reaches [`Self::handle_route_open`].
5882    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
5883        let Ok(ClientControlRequest::RouteOpen {
5884            identity,
5885            consumer_identity,
5886            scope,
5887            ..
5888        }) = parse_client_control_request(&frame.body)
5889        else {
5890            return RouteOpenCaller::unknown();
5891        };
5892        let principal = self
5893            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
5894            .map(|attested| attested.principal);
5895        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
5896    }
5897
5898    fn route_open_principal(
5899        &self,
5900        connection_id: ConnectionId,
5901        frame: &Frame,
5902        consumer_identity: Option<ConsumerIdentity>,
5903    ) -> Result<Result<Principal, Frame>, RouterError> {
5904        let attested = self
5905            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
5906            .map(|attested| attested.principal);
5907        self.route_open_principal_attested(frame, consumer_identity, attested)
5908    }
5909
5910    /// [`Self::route_open_principal`] with `attested` already taken by
5911    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
5912    /// claim or launch nonce once.
5913    fn route_open_principal_attested(
5914        &self,
5915        frame: &Frame,
5916        consumer_identity: Option<ConsumerIdentity>,
5917        attested: Option<Principal>,
5918    ) -> Result<Result<Principal, Frame>, RouterError> {
5919        if let Some(principal) = attested {
5920            return Ok(Ok(principal));
5921        }
5922        Ok(Err(control_error_frame(
5923            frame,
5924            "bad_consumer_identity",
5925            consumer_identity.map_or_else(
5926                || "connection claim is no longer authorized for routes".to_string(),
5927                |identity| format!(
5928                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
5929                    identity.module_id
5930                ),
5931            ),
5932        )?))
5933    }
5934
5935    /// Ordinary `route.open` refusals go through here; admission and breaker
5936    /// refusals log separately with their capacity or breaker state. The daemon can
5937    /// attest which code it sent: without the event, a client's "the daemon
5938    /// refused me" and the daemon's own view could only be reconciled by
5939    /// argument. Malformed input (`invalid_project_root`) does not come here;
5940    /// rejecting a request that was never a valid open is not a refusal of one.
5941    #[allow(clippy::too_many_arguments)]
5942    fn route_open_refusal_frame(
5943        &self,
5944        ctx: &RouteCtx,
5945        caller: &RouteOpenCaller,
5946        frame: &Frame,
5947        module_id: &str,
5948        reason: &'static str,
5949        code: &'static str,
5950        message: impl Into<String>,
5951    ) -> Result<Frame, RouterError> {
5952        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
5953        let detail = if matches!(
5954            reason,
5955            "registration_not_active"
5956                | "supervisor_not_live"
5957                | "no_forwarding_connection"
5958                | "reloading"
5959        ) {
5960            // A planned restart, reload or swap is already replacing the
5961            // process; it does not need a slot in the crash-restart budget.
5962            let expected_back = (reason == "reloading").then_some(true);
5963            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
5964        } else {
5965            None
5966        };
5967        control_error_body_frame(
5968            frame,
5969            ErrorBody {
5970                code: code.to_string(),
5971                message: message.into(),
5972                detail,
5973            },
5974        )
5975    }
5976
5977    fn route_open_recovery_detail(
5978        &self,
5979        module_id: &str,
5980        corr: u64,
5981        detail: Option<serde_json::Value>,
5982        expected_back: Option<bool>,
5983    ) -> Result<Option<serde_json::Value>, RouterError> {
5984        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
5985            return Ok(detail);
5986        };
5987        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
5988        detail["state"] = serde_json::json!(status.state.to_string());
5989        if let Some(expected_back) = expected_back {
5990            detail["expected_back"] = serde_json::json!(expected_back);
5991        } else if let Some(module) = self.supervisor.get(module_id) {
5992            match module.will_recover_after_connection_loss() {
5993                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
5994                Err(err) => warn!(
5995                    %module_id,
5996                    error = %err,
5997                    "failed to read route.open recovery verdict; omitting expected_back"
5998                ),
5999            }
6000        }
6001        Ok(Some(detail))
6002    }
6003
6004    /// Answer a waiting `route.open` whose relayed bind was refused.
6005    ///
6006    /// `daemon_authored` is provenance, not a code match: the daemon
6007    /// synthesized the refusal itself (a drain, a late reply, a scope that
6008    /// ended mid-bind) or the module refused the bind with its own body. A
6009    /// daemon refusal carries the daemon-origin bit; a module's own
6010    /// rejection is relayed with the bit clear, so a module that refuses
6011    /// with `module_reloading` still cannot mint a daemon refusal.
6012    #[allow(clippy::too_many_arguments)]
6013    fn route_bind_rejection(
6014        &self,
6015        ctx: &RouteCtx,
6016        caller: &RouteOpenCaller,
6017        frame: &Frame,
6018        target_module_id: &str,
6019        body: ErrorBody,
6020        daemon_authored: bool,
6021    ) -> Result<Vec<Frame>, RouterError> {
6022        // The daemon's own commit re-check refused the bind because the
6023        // scope ended or changed after admission. The module accepted;
6024        // counting it as a module rejection would blame the module. This
6025        // branch only runs for daemon-synthesized bodies: a module that
6026        // refuses with a scope code is answered as a module rejection below.
6027        if daemon_authored {
6028            let scope_code = match body.code.as_str() {
6029                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
6030                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
6031                _ => None,
6032            };
6033            if let Some(code) = scope_code {
6034                self.observe_route_open_refusal(
6035                    ctx,
6036                    caller,
6037                    target_module_id,
6038                    "scope_changed_before_commit",
6039                    code,
6040                );
6041                return Ok(vec![control_error_body_frame(frame, body)?]);
6042            }
6043        }
6044        self.counters
6045            .increment_route_open_refused("module_rejected");
6046        info!(
6047            target: "control",
6048            code = "module_rejected",
6049            module_code = ?body.code,
6050            module_id = ?target_module_id,
6051            connection_id = ctx.connection_id.get(),
6052            principal = %caller.principal,
6053            scope = %caller.scope,
6054            harness = %caller.harness,
6055            "route.open refused"
6056        );
6057        let refusal = if daemon_authored {
6058            control_error_body_frame(frame, body)?
6059        } else {
6060            control_relayed_error_body_frame(frame, body)?
6061        };
6062        Ok(vec![refusal])
6063    }
6064
6065    /// Refuse a `route.open` because the target module's bind-relay breaker is
6066    /// open, without attempting the relay.
6067    ///
6068    /// The wire code is `module_timeout`, which is the truth (the module has
6069    /// not been answering binds) and which both SDKs already classify as
6070    /// retryable with capped backoff. Reusing it is what keeps this change out
6071    /// of both SDKs; the daemon-side distinction lives in the counter key
6072    /// instead.
6073    ///
6074    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6075    /// While a breaker is open this fires on every open to that module, and the
6076    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6077    /// produced 261 lines about a single module inside 3000 lines of daemon
6078    /// log. The rare transitions are logged at warn/info instead and the volume
6079    /// is carried by the counter, so the evidence survives without the flood.
6080    /// The debug line keeps a per-refusal record reachable for whoever turns
6081    /// the level up.
6082    #[allow(clippy::too_many_arguments)]
6083    fn route_open_breaker_refusal_frame(
6084        &self,
6085        ctx: &RouteCtx,
6086        caller: &RouteOpenCaller,
6087        frame: &Frame,
6088        module_id: &str,
6089        consecutive_timeouts: u32,
6090        retry_in: Duration,
6091        probe_in_flight: bool,
6092    ) -> Result<Frame, RouterError> {
6093        self.counters
6094            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6095        debug!(
6096            target: "control",
6097            code = "module_timeout",
6098            module_id = ?module_id,
6099            connection_id = ctx.connection_id.get(),
6100            principal = %caller.principal,
6101            scope = %caller.scope,
6102            harness = %caller.harness,
6103            consecutive_timeouts,
6104            retry_in_ms = retry_in.as_millis() as u64,
6105            probe_in_flight,
6106            "route.open refused by open bind-relay breaker"
6107        );
6108        // Say what a caller can act on. An open bind-relay breaker means the
6109        // module timed out accepting several new routes in a row. The module
6110        // is still running and its established routes keep working; only new
6111        // route.open requests are refused until the cooldown ends and one
6112        // test route (the probe) gets through. A message that only counts
6113        // failed relays reads as "the module is down" to a worker that sees it.
6114        let detail = if probe_in_flight {
6115            "one test route is already being tried; retry once it settles".to_string()
6116        } else {
6117            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6118        };
6119        control_error_frame(
6120            frame,
6121            "module_timeout",
6122            format!(
6123                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6124                 timed out in a row); {detail}; its established routes are unaffected"
6125            ),
6126        )
6127    }
6128
6129    /// `reason` names the check that refused, because one wire code has
6130    /// several senders: after a module registers, `target_unavailable` can
6131    /// come from a missing role, an inactive registration, a supervisor that
6132    /// has not marked the process live, a missing forwarding connection, or a
6133    /// failed relay, and a log that records only the code cannot say which of
6134    /// them fired. It is a static, daemon-chosen label per branch, so it is
6135    /// safe to print plainly and stays a closed set.
6136    fn observe_route_open_refusal(
6137        &self,
6138        ctx: &RouteCtx,
6139        caller: &RouteOpenCaller,
6140        module_id: &str,
6141        reason: &'static str,
6142        code: &'static str,
6143    ) {
6144        self.counters.increment_route_open_refused(code);
6145        self.route_refusal_log
6146            .record(module_id, code, reason, caller, ctx.connection_id.get());
6147        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6148            self.route_outages.record_not_serving(module_id, reason);
6149        }
6150    }
6151
6152    /// Record an ACCEPTED route.open.
6153    ///
6154    /// Refusals have been logged and counted since the attestation work; accepts
6155    /// were invisible, so the daemon knew every principal it stamped and wrote
6156    /// none of them down. The party that attests the identity was the only party
6157    /// not recording it, which left a credential vault unable to name the sender
6158    /// of a call that reached it (claustrum #43) and left the launch-nonce
6159    /// concurrency question unanswerable from the outside.
6160    ///
6161    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6162    /// `code`/`module_id`/`connection_id` returns both directions of the same
6163    /// decision rather than two shapes a reader has to join by hand.
6164    ///
6165    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6166    /// and the difference carries information rather than being an
6167    /// inconsistency. This line is only reachable after a successful bind to a
6168    /// REGISTERED module, so the value has already passed HELLO validation
6169    /// including the path-hazard refusal and cannot contain control bytes. A
6170    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6171    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6172    ///
6173    /// Bare is also what every other daemon line already emits (`module
6174    /// registered`, `configured module supervised`). Shipping `?module_id` here
6175    /// made this instrument the only one in the file whose ids did not answer
6176    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6177    /// line whose whole purpose is being grepped beside its sibling.
6178    ///
6179    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6180    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6181    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6182    /// one are recorded identically. A test written against that harness passes
6183    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6184    /// green assertion that cannot fail. The same limit applies to the escaping
6185    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6186    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6187    /// Fencing either needs the real formatter, not the capture layer.
6188    ///
6189    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6190    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6191    /// to record. The ephemeral port would decay within minutes and answer only a
6192    /// live question. The identity question is instead answered by counting
6193    /// distinct live connections presenting one module's `consumer_identity` --
6194    /// "is anyone else holding this secret" rather than "is this the right
6195    /// process".
6196    fn observe_route_open_accept(
6197        &self,
6198        ctx: &RouteCtx,
6199        module_id: &str,
6200        principal: &str,
6201        scope: &str,
6202    ) {
6203        self.route_outages.record_accepted(module_id);
6204        self.counters.increment_route_open_accepted(principal);
6205        debug!(
6206            target: "control",
6207            principal,
6208            module_id,
6209            connection_id = ctx.connection_id.get(),
6210            scope = %scope,
6211            "route.open accepted"
6212        );
6213    }
6214
6215    fn supervised_absent_route_open_refusal_frame(
6216        &self,
6217        ctx: &RouteCtx,
6218        caller: &RouteOpenCaller,
6219        frame: &Frame,
6220        module_id: &str,
6221        code: &'static str,
6222        status: &crate::supervise::ModuleStatus,
6223    ) -> Result<Frame, RouterError> {
6224        self.counters.increment_route_open_refused(code);
6225        info!(
6226            target: "control",
6227            code,
6228            reason = "supervised_not_registered",
6229            module_id = ?module_id,
6230            connection_id = ctx.connection_id.get(),
6231            principal = %caller.principal,
6232            scope = %caller.scope,
6233            harness = %caller.harness,
6234            state = %status.state,
6235            enabled = status.enabled,
6236            live = status.live,
6237            "route.open refused"
6238        );
6239        // A supervised module whose process has not registered is not
6240        // serving, whatever the reason; the supervisor knows this id, so it is
6241        // safe to track.
6242        self.route_outages
6243            .record_not_serving(module_id, "supervised_not_registered");
6244        let message = if let Some(pid) = status.waiting_for_previous_pid {
6245            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6246                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6247            })
6248        } else {
6249            format!(
6250                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6251                status.state, status.enabled, status.live
6252            )
6253        };
6254        // `module_warming` here means the process is starting, running or
6255        // being restarted and has not registered yet. Nothing has to be
6256        // restarted for it to serve, so the crash budget does not decide it.
6257        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6258        control_error_body_frame(
6259            frame,
6260            ErrorBody {
6261                code: code.to_string(),
6262                message,
6263                detail: self.route_open_recovery_detail(
6264                    module_id,
6265                    frame.header.corr,
6266                    None,
6267                    expected_back,
6268                )?,
6269            },
6270        )
6271    }
6272
6273    async fn handle_route_open(
6274        &self,
6275        ctx: &RouteCtx,
6276        frame: Frame,
6277        request: RouteOpenRequest,
6278        timings: &mut RouteOpenTimings,
6279    ) -> Result<Vec<Frame>, RouterError> {
6280        let RouteOpenRequest {
6281            target,
6282            mut identity,
6283            consumer_identity,
6284            consumer_capabilities,
6285            role_versions,
6286            busy_refusals,
6287            admission_facts,
6288            scope,
6289            accepts_close_reasons,
6290        } = request;
6291        let target_module_id = target_module_id(&target).to_string();
6292        timings.module_id.clone_from(&target_module_id);
6293        if self
6294            .registry
6295            .get_module_by_connection(ctx.connection_id)
6296            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6297            .is_some()
6298        {
6299            return Ok(vec![control_error_frame(
6300                &frame,
6301                "invalid_request",
6302                "module connections cannot open client routes",
6303            )?]);
6304        }
6305        debug!(
6306            connection_id = ctx.connection_id.get(),
6307            corr = frame.header.corr,
6308            module_id = %target_module_id,
6309            "handling route.open"
6310        );
6311
6312        // The caller's attested principal, requested scope and harness, for
6313        // every `route.open refused` line below. The connection's claim
6314        // binding or launch nonce is checked here, once, and the answer is
6315        // reused where the principal is enforced further down, so the order
6316        // of refusals is unchanged.
6317        let attested =
6318            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6319        let mut caller = RouteOpenCaller::new(
6320            attested.as_ref().map(|attested| &attested.principal),
6321            scope.as_ref(),
6322            &identity,
6323        );
6324
6325        // A malformed declaration is refused first, before anything about the
6326        // target is looked up: the same body would be refused against any
6327        // module, so the caller learns nothing by retrying or waiting. An empty
6328        // map declares nothing and travels as no field at all, so a provider
6329        // only ever sees a missing field or a non-empty one.
6330        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6331        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6332            self.observe_route_open_refusal(
6333                ctx,
6334                &caller,
6335                &target_module_id,
6336                "invalid_role_versions",
6337                error_codes::INVALID_REQUEST,
6338            );
6339            return Ok(vec![control_error_body_frame(
6340                &frame,
6341                ErrorBody {
6342                    code: error_codes::INVALID_REQUEST.to_string(),
6343                    message: error.to_string(),
6344                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6345                },
6346            )?]);
6347        }
6348
6349        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6350            if status.waiting_for_previous_pid.is_some() {
6351                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6352                    ctx,
6353                    &caller,
6354                    &frame,
6355                    &target_module_id,
6356                    "module_warming",
6357                    &status,
6358                )?]);
6359            }
6360        }
6361
6362        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6363        // opposite. Below, a caller learns whether a module is unregistered,
6364        // supervised-but-down (with state/enabled/live), or registered without the
6365        // requested role. Elsewhere that is an enumeration leak: a probe learning
6366        // the shape of a fleet it cannot otherwise see.
6367        //
6368        // It is not one here, and the reason is the ACCESS MODEL rather than
6369        // anything about these errors. Reaching route.open requires the
6370        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6371        // connection file, so any caller who completes it already runs as this
6372        // user -- and can read subc.jsonc for the module list and `ck module
6373        // status` for live state. The reply discloses nothing the caller cannot
6374        // read more easily from disk, while the precision is load-bearing:
6375        // `unknown_module` is retryable and a missing role is not.
6376        //
6377        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6378        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6379        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6380        let admission_registry = self
6381            .registry
6382            .route_admission_snapshot()
6383            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6384        let Some(registration) =
6385            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6386        else {
6387            if let Some((status, warming)) =
6388                self.supervisor_status(&target_module_id, frame.header.corr)?
6389            {
6390                // BEFORE the two availability codes below, because for a module
6391                // that speaks no subc wire both of them are false comfort: they
6392                // say "not right now" and are retried, and this module will
6393                // never register no matter how long the caller waits. The
6394                // absence here is the declaration being honoured, not a module
6395                // that is late.
6396                if status.protocol == ModuleProtocol::None {
6397                    return Ok(vec![self.route_open_refusal_frame(
6398                        ctx,
6399                        &caller,
6400                        &frame,
6401                        &target_module_id,
6402                        "protocol_none",
6403                        error_codes::MODULE_NO_PROTOCOL,
6404                        format!(
6405                            "module_id '{target_module_id}' is declared protocol: none; \
6406                             it speaks no subc wire and serves no routes"
6407                        ),
6408                    )?]);
6409                }
6410                let code = if warming {
6411                    "module_warming"
6412                } else {
6413                    "target_unavailable"
6414                };
6415                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6416                    ctx,
6417                    &caller,
6418                    &frame,
6419                    &target_module_id,
6420                    code,
6421                    &status,
6422                )?]);
6423            }
6424            if let Some(removed_ago_ms) =
6425                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6426            {
6427                return Ok(vec![self.route_open_refusal_frame(
6428                    ctx,
6429                    &caller,
6430                    &frame,
6431                    &target_module_id,
6432                    "removed",
6433                    error_codes::MODULE_REMOVED,
6434                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6435                )?]);
6436            }
6437            return Ok(vec![self.route_open_refusal_frame(
6438                ctx,
6439                &caller,
6440                &frame,
6441                &target_module_id,
6442                "not_registered",
6443                error_codes::UNKNOWN_MODULE,
6444                format!("module_id '{target_module_id}' is not registered"),
6445            )?]);
6446        };
6447
6448        // Best-effort only: registry readiness and forwarding reservation use
6449        // different locks, so a module can flip readiness between this read and
6450        // the relay. Modules must still tolerate an `on_bind` while not ready.
6451        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6452            .is_err()
6453        {
6454            self.counters
6455                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6456            info!(
6457                target: "control",
6458                code = error_codes::MODULE_WARMING,
6459                module_id = ?target_module_id,
6460                connection_id = ctx.connection_id.get(),
6461                principal = %caller.principal,
6462                scope = %caller.scope,
6463                harness = %caller.harness,
6464                reason = "declared_not_ready",
6465                "route.open refused"
6466            );
6467            // The module is registered but says it cannot take work, which is
6468            // an outage from the caller's side even though its process is up.
6469            self.route_outages
6470                .record_not_serving(&target_module_id, "declared_not_ready");
6471            // The registered process can declare itself ready without a
6472            // restart, so an exhausted crash budget does not prevent serving.
6473            return Ok(vec![control_error_body_frame(
6474                &frame,
6475                ErrorBody {
6476                    code: error_codes::MODULE_WARMING.to_string(),
6477                    message: format!(
6478                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6479                    ),
6480                    detail: self.route_open_recovery_detail(
6481                        &target_module_id,
6482                        frame.header.corr,
6483                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6484                        Some(true),
6485                    )?,
6486                },
6487            )?]);
6488        }
6489
6490        // Effective readiness, second half: a module that declares a capability
6491        // `need: required` is not routable while that capability has no
6492        // registered provider. It is enforced HERE, as a retryable routing
6493        // refusal, and deliberately not as spawn ordering or a boot block. The
6494        // module is still started and registered and can make its own calls;
6495        // spawn ordering is a promise that cannot be kept once a provider
6496        // crashes at runtime, and refusing to boot would stop the whole
6497        // machine, including the tools needed to fix its configuration.
6498        //
6499        // "Provided" is the evaluator's verdict, which counts a provider as
6500        // soon as it has REGISTERED, not once it is ready. Two modules that
6501        // require each other's capabilities are therefore both routable once
6502        // both register; counting readiness instead would deadlock them.
6503        //
6504        // Only new opens are refused. Routes already bound when a provider
6505        // goes away stay bound: nothing here tears them down, and the module
6506        // answers them as it can. Like the readiness read above this is
6507        // best-effort against a provider registering or leaving concurrently.
6508        if let Some(capability) = self.first_unprovided_required_capability_for(
6509            &registration.module_id,
6510            registration.capabilities.as_ref(),
6511        ) {
6512            self.counters
6513                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6514            info!(
6515                target: "control",
6516                code = error_codes::MODULE_WARMING,
6517                module_id = ?target_module_id,
6518                connection_id = ctx.connection_id.get(),
6519                principal = %caller.principal,
6520                scope = %caller.scope,
6521                harness = %caller.harness,
6522                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6523                capability = %capability,
6524                "route.open refused"
6525            );
6526            return Ok(vec![control_error_body_frame(
6527                &frame,
6528                ErrorBody {
6529                    code: error_codes::MODULE_WARMING.to_string(),
6530                    message: format!(
6531                        "module_id '{target_module_id}' requires capability '{capability}', \
6532                         which no registered module provides; retry"
6533                    ),
6534                    detail: Some(serde_json::json!({
6535                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6536                        "capability": capability,
6537                    })),
6538                },
6539            )?]);
6540        }
6541
6542        if !target_has_required_role(&target, &registration.roles) {
6543            return Ok(vec![self.route_open_refusal_frame(
6544                ctx,
6545                &caller,
6546                &frame,
6547                &target_module_id,
6548                "role_not_provided",
6549                "target_unavailable",
6550                format!("module_id '{target_module_id}' does not provide the requested target"),
6551            )?]);
6552        }
6553
6554        if registration.state != ChannelState::Active {
6555            return Ok(vec![self.route_open_refusal_frame(
6556                ctx,
6557                &caller,
6558                &frame,
6559                &target_module_id,
6560                "registration_not_active",
6561                "target_unavailable",
6562                format!("module_id '{target_module_id}' is not active"),
6563            )?]);
6564        }
6565
6566        if self
6567            .forwarding
6568            .module_is_draining(&target_module_id)
6569            .map_err(RouterError::Forwarding)?
6570        {
6571            return Ok(vec![self.route_open_refusal_frame(
6572                ctx,
6573                &caller,
6574                &frame,
6575                &target_module_id,
6576                "reloading",
6577                "module_reloading",
6578                format!("module_id '{target_module_id}' is reloading"),
6579            )?]);
6580        }
6581
6582        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6583            process_liveness.process_live(&target_module_id) == Some(false)
6584        }) {
6585            // A module the supervisor is restarting or reloading can still hold
6586            // a registration: the old process before its connection closes, or
6587            // a new one that registered while the supervisor was draining. The
6588            // forwarding table does not see that as draining, but the consumer
6589            // should still be told to retry soon, exactly as for the drain
6590            // above, rather than that the target is unavailable.
6591            if process_liveness.process_replacing(&target_module_id) {
6592                return Ok(vec![self.route_open_refusal_frame(
6593                    ctx,
6594                    &caller,
6595                    &frame,
6596                    &target_module_id,
6597                    "reloading",
6598                    "module_reloading",
6599                    format!("module_id '{target_module_id}' is reloading"),
6600                )?]);
6601            }
6602            return Ok(vec![self.route_open_refusal_frame(
6603                ctx,
6604                &caller,
6605                &frame,
6606                &target_module_id,
6607                "supervisor_not_live",
6608                "target_unavailable",
6609                format!("module_id '{target_module_id}' is not live"),
6610            )?]);
6611        }
6612
6613        if !self
6614            .forwarding
6615            .has_live_module_connection(&target_module_id)
6616            .map_err(RouterError::Forwarding)?
6617        {
6618            return Ok(vec![self.route_open_refusal_frame(
6619                ctx,
6620                &caller,
6621                &frame,
6622                &target_module_id,
6623                "no_forwarding_connection",
6624                "target_unavailable",
6625                format!("module_id '{target_module_id}' has no live forwarding connection"),
6626            )?]);
6627        }
6628
6629        if let Some(error) =
6630            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6631        {
6632            self.observe_route_open_refusal(
6633                ctx,
6634                &caller,
6635                &target_module_id,
6636                "op_not_allowed",
6637                "op_not_allowed",
6638            );
6639            return Ok(vec![error]);
6640        }
6641
6642        let principal = match (&attested, consumer_identity.is_some()) {
6643            // A claim-bound connection whose launch ended attests nothing,
6644            // and it must never fall back to opening as `direct`.
6645            (None, false) => {
6646                self.observe_route_open_refusal(
6647                    ctx,
6648                    &caller,
6649                    &target_module_id,
6650                    "registration_channel_closed",
6651                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6652                );
6653                return Ok(vec![control_error_frame(
6654                    &frame,
6655                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6656                    "the claim binding's launch has ended",
6657                )?]);
6658            }
6659            _ => match self.route_open_principal_attested(
6660                &frame,
6661                consumer_identity,
6662                attested.as_ref().map(|attested| attested.principal.clone()),
6663            )? {
6664                Ok(principal) => principal,
6665                Err(error) => {
6666                    self.observe_route_open_refusal(
6667                        ctx,
6668                        &caller,
6669                        &target_module_id,
6670                        "bad_consumer_identity",
6671                        "bad_consumer_identity",
6672                    );
6673                    return Ok(vec![error]);
6674                }
6675            },
6676        };
6677        let attested = attested.expect("an attested principal was resolved above");
6678        timings.principal = principal_label(&principal);
6679
6680        // The opener's spawn authority, read once here and carried with the
6681        // relay; nothing below reads its record again.
6682        let Ok(mut caller_capture) = attested.capture() else {
6683            self.observe_route_open_refusal(
6684                ctx,
6685                &caller,
6686                &target_module_id,
6687                "registration_channel_closed",
6688                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6689            );
6690            return Ok(vec![control_error_frame(
6691                &frame,
6692                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6693                "the opener's launch has ended",
6694            )?]);
6695        };
6696        // The caller-side checks below read the opener's own spawn: its
6697        // module from its record and its manifest from its own registration,
6698        // never another launch's active registration under the same id.
6699        let caller_module_id = match &attested.spawn {
6700            Some((record, _)) => Some(record.module_id().to_owned()),
6701            None => match &principal {
6702                Principal::Reserved { module_id } => Some(module_id.clone()),
6703                _ => None,
6704            },
6705        };
6706
6707        // Only Callosum can attest a production phone build. Consume the raw
6708        // claim here; opted-in targets receive only the honoured peer fact.
6709        let build_class = identity.build_class.take().filter(|build_class| {
6710            if caller_module_id.as_deref() == Some("callosum") {
6711                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6712            } else {
6713                if self
6714                    .build_class_warned
6715                    .lock()
6716                    .unwrap_or_else(|p| p.into_inner())
6717                    .insert(ctx.connection_id)
6718                {
6719                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6720                        "ignoring build_class from a non-Callosum opener");
6721                }
6722                false
6723            }
6724        });
6725
6726        // This is attested, control-plane policy for supervised module origins.
6727        // Keep it before route reservation and out of the opaque forwarding hot
6728        // path: data frames must never acquire a per-frame capability check.
6729        let opening_registration = self.caller_registration(&attested, &admission_registry);
6730        if let Some(opening_registration) = &opening_registration {
6731            let opening_module_id = opening_registration.module_id.as_str();
6732            if let Some(capability) = denied_capability(
6733                opening_registration.capabilities.as_ref(),
6734                registration.capabilities.as_ref(),
6735            ) {
6736                warn!(
6737                    opening_module_id,
6738                    target_module_id,
6739                    capability,
6740                    "refusing route.open because an attested capability deny edge matches"
6741                );
6742                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6743                    &frame,
6744                    &target_module_id,
6745                    "capability_deny_edge",
6746                    "capability_forbidden",
6747                    format!(
6748                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
6749                    ),
6750                )?]);
6751            }
6752        }
6753
6754        if admission_facts.is_some() {
6755            let carrier_matches = caller_module_id.is_some()
6756                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
6757            if !carrier_matches {
6758                return Ok(vec![self.route_open_refusal_frame(
6759                    ctx,
6760                    &caller,
6761                    &frame,
6762                    &target_module_id,
6763                    "admission_facts_carrier_not_permitted",
6764                    "admission_facts_not_permitted",
6765                    "admission facts may only be carried by the configured reserved module",
6766                )?]);
6767            }
6768
6769            let target_allowed = self
6770                .admission_facts_targets
6771                .as_ref()
6772                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
6773            if !target_allowed {
6774                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6775                    &frame,
6776                    &target_module_id,
6777                    "admission_facts_target_not_listed",
6778                    "admission_facts_target_not_allowed",
6779                    format!(
6780                        "admission facts are not permitted for target module_id '{target_module_id}'"
6781                    ),
6782                )?]);
6783            }
6784
6785            // Keep the value opaque to subc. The downstream admission validator owns
6786            // schema and semantic checks; this daemon only enforces carrier authority
6787            // and the configured destination allowlist.
6788        }
6789
6790        // Scope admission, on the attested principal above and never on the
6791        // request body. The tag read here travels with the pending bind and is
6792        // compared with the published one at commit, so a sync between here
6793        // and the module's ack refuses the open instead of binding a stamp
6794        // that is no longer true.
6795        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
6796            None => (None, None, false),
6797            Some(selector) => {
6798                let owner_configured = match &selector.owner {
6799                    // A reserved owner counts as configured from before its
6800                    // process is spawned (see `SupervisorHandle::is_configured`).
6801                    // So an owner that has not synced its scopes yet is refused
6802                    // as retryable (`scope_not_synced`), not as one that will
6803                    // never sync.
6804                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
6805                    _ => false,
6806                };
6807                let mut scopes = self
6808                    .scopes
6809                    .write()
6810                    .unwrap_or_else(|poisoned| poisoned.into_inner());
6811                let admitted = crate::scopes::admission::admit_route(
6812                    &scopes,
6813                    &admission_registry,
6814                    &principal,
6815                    &target_module_id,
6816                    Some(selector),
6817                    owner_configured,
6818                    crate::scopes::admission::AdmissionMode::Open,
6819                )
6820                .map(|route| {
6821                    let admission = route.scope.expect("scoped admission");
6822                    let bound = scopes.reserve_bind(
6823                        &admission,
6824                        &principal,
6825                        ctx.connection_id,
6826                        selector.hold_presence,
6827                    );
6828                    (admission, bound)
6829                });
6830                match admitted {
6831                    Ok((admission, bound)) => {
6832                        (Some(bound), Some(admission.stamp), admission.stamp_required)
6833                    }
6834                    Err(refusal) => {
6835                        return Ok(vec![self.route_open_refusal_frame(
6836                            ctx,
6837                            &caller,
6838                            &frame,
6839                            &target_module_id,
6840                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6841                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6842                            refusal.message,
6843                        )?]);
6844                    }
6845                }
6846            }
6847        };
6848        // From here on a refusal names the scope by the stamp admission
6849        // issued, exactly as the `route.open accepted` line does.
6850        if let Some(stamp) = &scope_stamp {
6851            caller.scope = route_open_scope_label(stamp);
6852        }
6853        // Decided from the admitted stamp, before any field of it is stripped
6854        // for a target that lacks the capability to read it.
6855        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
6856            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
6857        }
6858
6859        // Allow resolvable missing-tail paths so a vanished directory does not
6860        // prevent reopening an existing session for cleanup. Binding does not
6861        // authorize creation of durable provider state.
6862        //
6863        // Resolve real paths rather than lexical cleanup: canonicalize the
6864        // longest existing ancestor and append the missing tail, retaining the
6865        // path's real existing ancestry even when a leaf is missing.
6866        timings.enter(RouteOpenPhase::ProjectRoot);
6867        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
6868            Ok(project) => project,
6869            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
6870        };
6871        timings.enter(RouteOpenPhase::Admission);
6872        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
6873            Ok(root) => root,
6874            Err(err) => {
6875                return Ok(vec![control_error_frame(
6876                    &frame,
6877                    "invalid_project_root",
6878                    err.to_string(),
6879                )?])
6880            }
6881        };
6882        // Compute compatibility project fields before stripping optional stamp
6883        // members. Preserve the canonical opener root and its project ID,
6884        // including absence. For rootless openers, use stamp workdir or `/`, and
6885        // opener ID, else stamp ID, else no ID. Emit these identity fields only
6886        // to targets without bind-no-project/v1.
6887        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
6888
6889        // Last gate before any relay work, and deliberately after the cheap
6890        // registry and availability checks above: those name a more precise
6891        // condition (unknown, removed, reloading) and a caller is better served
6892        // by the precise code than by this one.
6893        //
6894        // Everything below this point costs an egress permit, a reserved handle
6895        // pair and, if the module does not answer, the whole relay budget. The
6896        // reader no longer waits for that budget, so cap each target explicitly;
6897        // serial dispatch used to provide the accidental cap of one relay per
6898        // connection. Admission is a mutex-protected count and never waits.
6899        let _concurrency_guard = match self
6900            .route_bind_concurrency
6901            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
6902        {
6903            Ok(guard) => guard,
6904            Err(in_flight) => {
6905                return Ok(vec![self.route_open_target_capacity_refusal(
6906                    ctx,
6907                    &caller,
6908                    &frame,
6909                    &target_module_id,
6910                    in_flight,
6911                )?]);
6912            }
6913        };
6914
6915        // A module that has already burned the whole budget `threshold` times
6916        // in a row does not get to charge it again until a probe says it recovered.
6917        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
6918            RouteBindAdmission::Admitted { guard, probe } => {
6919                if probe {
6920                    info!(
6921                        module_id = %target_module_id,
6922                        connection_id = ctx.connection_id.get(),
6923                        "route.bind breaker half-open: admitting one probe"
6924                    );
6925                }
6926                guard
6927            }
6928            RouteBindAdmission::Refused {
6929                consecutive_timeouts,
6930                retry_in,
6931                probe_in_flight,
6932            } => {
6933                return Ok(vec![self.route_open_breaker_refusal_frame(
6934                    ctx,
6935                    &caller,
6936                    &frame,
6937                    &target_module_id,
6938                    consecutive_timeouts,
6939                    retry_in,
6940                    probe_in_flight,
6941                )?]);
6942            }
6943        };
6944
6945        let operator_app = self
6946            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
6947            .await;
6948        // Resolve the per-module budget here so the wait matches the operator's
6949        // intent for this specific target. A per-module override in
6950        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
6951        // daemons) wins over the daemon-wide default.
6952        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
6953        let relay_deadline = Instant::now() + route_bind_relay_timeout;
6954        let production_peer_build =
6955            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
6956        timings.enter(RouteOpenPhase::EgressReservation);
6957        let pending = match self
6958            .forwarding
6959            .begin_route_bind_relay_for(
6960                ctx.connection_id,
6961                ctx.egress.clone(),
6962                response_version(&frame),
6963                frame.header.corr,
6964                &target_module_id,
6965                principal.clone(),
6966                bound_scope,
6967                project_root,
6968                identity.harness.clone(),
6969                build_class,
6970                operator_app.clone(),
6971                crate::forwarding::RouteAuthority {
6972                    incarnation: self.supervisor.daemon_incarnation(),
6973                    caller: caller_capture
6974                        .as_ref()
6975                        .map(|caller| caller.authority.pair()),
6976                    capability_fence: route_bind_settlement::fence(
6977                        &opening_registration,
6978                        registration,
6979                    ),
6980                },
6981                relay_deadline,
6982                busy_refusals == Some(true),
6983                accepts_close_reasons,
6984            )
6985            .await
6986        {
6987            Ok(pending) => pending,
6988            Err(err) => {
6989                return Ok(vec![self.route_open_refusal_frame(
6990                    ctx,
6991                    &caller,
6992                    &frame,
6993                    &target_module_id,
6994                    "relay_reservation_failed",
6995                    forwarding_error_code(&err),
6996                    err.to_string(),
6997                )?])
6998            }
6999        };
7000        timings.enter(RouteOpenPhase::Admission);
7001        let crate::forwarding::PendingRouteBindRelay {
7002            endpoint,
7003            module_sink,
7004            negotiated_ver,
7005            client_channel,
7006            client_epoch,
7007            module_channel,
7008            module_epoch,
7009            corr: relay_corr,
7010            receiver,
7011        } = pending;
7012        let mut reservation =
7013            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
7014
7015        // Reserving egress can wait while a module reconnects or a swap cuts
7016        // over. Check the relay's captured connection, not the earlier by-id
7017        // lookup: the original module's flow/run capabilities cannot authorize
7018        // its replacement. The captured sink stays bound to that connection.
7019        let relay_registration = self
7020            .registry
7021            .route_registration_by_connection(endpoint.connection_id)
7022            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7023        let relay_capabilities = relay_registration
7024            .as_ref()
7025            .and_then(|registration| registration.capabilities.as_ref());
7026        if let Some(selector) = &scope {
7027            // Egress reservation may wait across a scope update. Recheck the
7028            // proof against the current record before sending the captured bind.
7029            if let Err(refusal) = self
7030                .scopes
7031                .read()
7032                .unwrap_or_else(|poisoned| poisoned.into_inner())
7033                .check_bind_proof(&principal, selector)
7034            {
7035                reservation.release_and_disarm();
7036                return Ok(vec![self.route_open_refusal_frame(
7037                    ctx,
7038                    &caller,
7039                    &frame,
7040                    &target_module_id,
7041                    refusal.code,
7042                    refusal.code,
7043                    refusal.message,
7044                )?]);
7045            }
7046        }
7047        if let Some(stamp) = scope_stamp.as_ref() {
7048            if let Err(refusal) = crate::scopes::check_target_required_stamp(
7049                stamp_required,
7050                &target_module_id,
7051                relay_capabilities,
7052            )
7053            .and_then(|()| {
7054                crate::scopes::check_target_flow_support(
7055                    stamp,
7056                    &target_module_id,
7057                    relay_capabilities,
7058                )
7059            })
7060            .and_then(|()| {
7061                crate::scopes::check_target_agent_run_support(
7062                    stamp,
7063                    &target_module_id,
7064                    relay_capabilities,
7065                )
7066            }) {
7067                reservation.release_and_disarm();
7068                return Ok(vec![self.route_open_refusal_frame(
7069                    ctx,
7070                    &caller,
7071                    &frame,
7072                    &target_module_id,
7073                    refusal.code,
7074                    refusal.code,
7075                    refusal.message,
7076                )?]);
7077            }
7078        }
7079
7080        // Older readers may reject unknown fields. Select optional fields from
7081        // the captured endpoint's declaration, including on unscoped binds.
7082        if scope_stamp
7083            .as_ref()
7084            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7085            && !crate::scopes::target_supports_federated(relay_capabilities)
7086        {
7087            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7088            scope_stamp = None;
7089        }
7090        if !relay_capabilities.is_some_and(|caps| {
7091            caps.provides
7092                .iter()
7093                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7094        }) {
7095            if let Some(stamp) = scope_stamp.as_mut() {
7096                stamp.workdir = None;
7097                stamp.project_id = None;
7098            }
7099        }
7100        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7101        // attribution. The run gate above has already required the target to
7102        // declare `worker-runs/v1`, which promises to read both
7103        // `on_behalf_of_agent` and `call_mode`.
7104        let worker_run = scope_stamp
7105            .as_ref()
7106            .is_some_and(crate::scopes::is_worker_run)
7107            && relay_capabilities.is_some_and(|caps| {
7108                caps.provides
7109                    .iter()
7110                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7111            });
7112        if !worker_run
7113            && !relay_capabilities.is_some_and(|caps| {
7114                caps.provides
7115                    .iter()
7116                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7117            })
7118        {
7119            if let Some(stamp) = scope_stamp.as_mut() {
7120                stamp.attributes.on_behalf_of_agent = None;
7121            }
7122        }
7123        if !relay_capabilities.is_some_and(|caps| {
7124            caps.provides
7125                .iter()
7126                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7127        }) {
7128            if let Some(stamp) = scope_stamp.as_mut() {
7129                stamp.attributes.flow_version = None;
7130                stamp.attributes.flow_code_hash = None;
7131                stamp.attributes.flow_install_id = None;
7132            }
7133        }
7134        let call_mode = if worker_run
7135            || relay_capabilities
7136                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7137        {
7138            Some(derive_call_mode(scope_stamp.as_ref()))
7139        } else {
7140            if let Some(stamp) = scope_stamp.as_mut() {
7141                stamp.expires_at_ms = None;
7142            }
7143            None
7144        };
7145
7146        debug!(
7147            connection_id = ctx.connection_id.get(),
7148            client_channel,
7149            client_epoch,
7150            module_channel,
7151            module_epoch,
7152            "reserved route handle pair"
7153        );
7154        // Rendered BEFORE the move into the relay, because the accept arm below
7155        // is where it is logged and the principal is gone by then.
7156        let route_principal_label = principal_label(&principal);
7157        let relay = ModuleControlRequest::RouteBind {
7158            route_channel: module_channel,
7159            epoch: module_epoch,
7160            target,
7161            identity,
7162            principal: Some(principal),
7163            consumer_capabilities,
7164            role_versions,
7165            admission_facts,
7166            scope: scope_stamp,
7167            call_mode,
7168        };
7169        let peer = RouteBindPeer::new()
7170            .with_observed_peer(
7171                relay_capabilities
7172                    .is_some_and(|caps| {
7173                        caps.provides
7174                            .iter()
7175                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7176                    })
7177                    .then(|| {
7178                        self.observed_peers
7179                            .lock()
7180                            .unwrap_or_else(|p| p.into_inner())
7181                            .get(&ctx.connection_id)
7182                            .cloned()
7183                            .unwrap_or_else(ObservedPeer::unobserved)
7184                    }),
7185            )
7186            .with_operator_app(
7187                self.connection_operator_app(operator_app.as_ref())
7188                    .filter(|_| {
7189                        relay_capabilities.is_some_and(|caps| {
7190                            caps.provides
7191                                .iter()
7192                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7193                        })
7194                    }),
7195            )
7196            .with_caller(caller_for_target(
7197                caller_capture.as_ref(),
7198                relay_capabilities,
7199                &target_module_id,
7200            ))
7201            .with_peer_build(
7202                (production_peer_build
7203                    && relay_capabilities.is_some_and(|caps| {
7204                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7205                    }))
7206                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7207            );
7208        let relay_body = crate::bind_compat::encode_bind(
7209            &relay,
7210            &peer,
7211            &legacy_bind_project,
7212            relay_capabilities,
7213        )
7214        .map_err(|err| {
7215            RouterError::backend(
7216                0,
7217                frame.header.corr,
7218                format!("failed to encode route.bind request: {err}"),
7219            )
7220        })?;
7221        let relay_frame = Frame::build_with_version(
7222            negotiated_ver,
7223            FrameType::Request,
7224            control_flags(),
7225            0,
7226            0,
7227            relay_corr,
7228            relay_body,
7229        )
7230        .map_err(RouterError::FrameBuild)?;
7231
7232        timings.enter(RouteOpenPhase::BindSend);
7233        // Enqueueing the bind spends the same absolute budget as its ack.
7234        let sent = timeout_at(relay_deadline, module_sink.send(relay_frame)).await;
7235        timings.enter(RouteOpenPhase::Admission);
7236        let Ok(sent) = sent else {
7237            // Never enqueued: the module's queue, not its bind handler, was
7238            // slow, so the ack-timeout breaker is not charged.
7239            reservation.release_and_disarm();
7240            breaker.record_inconclusive();
7241            return Ok(vec![self.unsent_bind_timeout_refusal(
7242                ctx,
7243                &caller,
7244                &frame,
7245                &target_module_id,
7246            )?]);
7247        };
7248        if let Err(err) = sent {
7249            reservation.release_and_disarm();
7250            return Ok(vec![self.route_open_refusal_frame(
7251                ctx,
7252                &caller,
7253                &frame,
7254                &target_module_id,
7255                "relay_send_failed",
7256                "target_unavailable",
7257                err.to_string(),
7258            )?]);
7259        }
7260
7261        #[cfg(test)]
7262        if let Some(hold) = &self.route_bind_relay_sent_hold {
7263            // First wait: tell the test the bind is queued. Second wait: stay
7264            // here until the test has driven whatever it wants to happen
7265            // between queueing the bind and marking it enqueued.
7266            hold.wait().await;
7267            hold.wait().await;
7268        }
7269
7270        // A missing relay is not by itself an abandoned bind: the module may
7271        // already have acked it and the route may be committed. Only a relay
7272        // dropped without any module reply needs this GOODBYE; one a reply
7273        // settled has already had its GOODBYE decided by the reply path.
7274        if self
7275            .forwarding
7276            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7277            .map_err(RouterError::Forwarding)?
7278            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7279        {
7280            self.send_abandoned_route_bind_goodbye(
7281                &module_sink,
7282                negotiated_ver,
7283                module_channel,
7284                module_epoch,
7285            );
7286        }
7287
7288        timings.enter(RouteOpenPhase::BindAckWait);
7289        let outcome = timeout_at(relay_deadline, receiver).await;
7290        timings.enter(RouteOpenPhase::Admission);
7291        match outcome {
7292            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7293                reservation.disarm();
7294                if breaker.record_accepted() {
7295                    info!(
7296                        module_id = %target_module_id,
7297                        "route.bind breaker closed: the probe was accepted"
7298                    );
7299                }
7300                self.observe_route_open_accept(
7301                    ctx,
7302                    &target_module_id,
7303                    &route_principal_label,
7304                    &caller.scope,
7305                );
7306                Ok(Vec::new())
7307            }
7308            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7309                reservation.release_and_disarm();
7310                // A module that says no in microseconds is healthy. Rejection
7311                // is a different condition with its own refusal and must not
7312                // move the breaker.
7313                breaker.record_inconclusive();
7314                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7315            }
7316            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7317                reservation.release_and_disarm();
7318                breaker.record_inconclusive();
7319                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7320            }
7321            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7322                reservation.release_and_disarm();
7323                breaker.record_inconclusive();
7324                // Fires when the module's connection closes while a relayed
7325                // bind is pending -- typically a caller racing a module restart
7326                // whose bind was relayed BEFORE the drain mark went up. Logged
7327                // because the caller sees only its own error and the fleet has
7328                // already spent one diagnosis round unable to tell this arm
7329                // from a relay timeout without daemon-side evidence.
7330                tracing::warn!(
7331                    module_id = %target_module_id,
7332                    "route.bind relay abandoned: {message}"
7333                );
7334                Ok(vec![self.route_open_refusal_frame(
7335                    ctx,
7336                    &caller,
7337                    &frame,
7338                    &target_module_id,
7339                    "relay_abandoned",
7340                    "target_unavailable",
7341                    message,
7342                )?])
7343            }
7344            Ok(Err(_)) => {
7345                reservation.release_and_disarm();
7346                breaker.record_inconclusive();
7347                Ok(vec![self.route_open_refusal_frame(
7348                    ctx,
7349                    &caller,
7350                    &frame,
7351                    &target_module_id,
7352                    "relay_waiter_canceled",
7353                    "target_unavailable",
7354                    "route.bind relay waiter was canceled before the module responded",
7355                )?])
7356            }
7357            Err(_) => {
7358                reservation.release_and_disarm();
7359                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7360                // answer at all is the one condition a fast refusal can
7361                // usefully stand in for; every other arm already answered.
7362                if let Some(opened) = breaker.record_timeout(
7363                    self.route_bind_breaker_threshold,
7364                    self.route_bind_breaker_cooldown,
7365                ) {
7366                    warn!(
7367                        module_id = %target_module_id,
7368                        consecutive_timeouts = opened.consecutive_timeouts,
7369                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7370                        reopened_after_probe = opened.reopened_after_probe,
7371                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7372                    );
7373                }
7374                // The generous budget just burned to no answer: the module is
7375                // registered and its connection is up, but its bind handler sat
7376                // on the ack for the full budget (warm-on-bind, cold configure,
7377                // or a wedged handler). Every earlier unavailability shape
7378                // fast-refuses BEFORE the relay, so this arm firing means the
7379                // slowness is module-side -- log it so the per-module timeline
7380                // is reconstructable without client audit rows.
7381                tracing::warn!(
7382                    module_id = %target_module_id,
7383                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7384                    "route.bind relay timed out: module did not ack within budget"
7385                );
7386                Ok(vec![self.route_open_refusal_frame(
7387                    ctx,
7388                    &caller,
7389                    &frame,
7390                    &target_module_id,
7391                    "relay_timed_out",
7392                    "module_timeout",
7393                    format!(
7394                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7395                        route_bind_relay_timeout
7396                    ),
7397                )?])
7398            }
7399        }
7400    }
7401
7402    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7403        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7404            snapshot: self.supervisor.spawn_snapshot(),
7405        };
7406        Ok(vec![control_response_body_frame(
7407            &frame,
7408            &response,
7409            "ClientControlResponse::SupervisorSpawnSnapshot",
7410        )?])
7411    }
7412
7413    fn handle_supervisor_spawn_subscribe(
7414        &self,
7415        ctx: &RouteCtx,
7416        frame: Frame,
7417        since: Option<SpawnCursor>,
7418    ) -> Result<Vec<Frame>, RouterError> {
7419        match self.supervisor.subscribe_spawns(
7420            ctx.connection_id,
7421            frame.header.corr,
7422            response_version(&frame),
7423            since,
7424            ctx.egress.clone(),
7425        ) {
7426            Ok(()) => Ok(Vec::new()),
7427            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7428                Ok(vec![control_error_body_frame(
7429                    &frame,
7430                    ErrorBody {
7431                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7432                        message: "spawn cursor belongs to a different daemon incarnation"
7433                            .to_string(),
7434                        detail: Some(serde_json::json!({
7435                            "current_daemon_incarnation": current
7436                        })),
7437                    },
7438                )?])
7439            }
7440            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7441                &frame,
7442                ErrorBody {
7443                    code: "spawn_cursor_too_old".to_string(),
7444                    message: "spawn cursor predates the retained event ring".to_string(),
7445                    detail: Some(serde_json::json!({
7446                        "oldest_retained_cursor": oldest
7447                    })),
7448                },
7449            )?]),
7450            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7451                0,
7452                frame.header.corr,
7453                format!("failed to open supervisor spawn subscription: {error}"),
7454            )),
7455        }
7456    }
7457
7458    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7459        // Status/configuration snapshots may wait on synchronous supervisor
7460        // locks. Keep that work off the connection's async runtime thread.
7461        let handler = self.clone();
7462        let runtime = tokio::runtime::Handle::current();
7463        // The blocking pool does not inherit the control request's tracing
7464        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7465        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7466        let corr = frame.header.corr;
7467        tokio::task::spawn_blocking(move || {
7468            runtime.block_on(
7469                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7470                    .with_subscriber(subscriber),
7471            )
7472        })
7473        .await
7474        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7475    }
7476
7477    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7478        use crate::config_gate::runtime::ApprovedDaemonView;
7479        let publication = self
7480            .config_runtime
7481            .as_ref()
7482            .and_then(|owner| owner.polled_snapshot().ok());
7483        let approved = publication
7484            .as_ref()
7485            .map(|view| view.approved_daemon.clone())
7486            .unwrap_or_else(|| {
7487                if self.config_runtime.is_some() {
7488                    ApprovedDaemonView::Unavailable
7489                } else {
7490                    ApprovedDaemonView::NotStamped
7491                }
7492            });
7493        let generation = self
7494            .registry
7495            .generation()
7496            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7497        let supervised = self.supervisor.list();
7498        let mut statuses = BTreeMap::new();
7499        let mut not_running = BTreeSet::new();
7500        for module in &supervised {
7501            let status = module.status_for_control("list").map_err(|err| {
7502                RouterError::backend(
7503                    0,
7504                    frame.header.corr,
7505                    format!("failed to read supervisor status: {err}"),
7506                )
7507            })?;
7508            if !status.enabled || !status.process_alive {
7509                not_running.insert(module.module_id().to_owned());
7510            }
7511            statuses.insert(module.module_id().to_owned(), status);
7512        }
7513        // Legacy per-process diagnostics keep their shared optional budget.
7514        // The cached tree and accounting export below does not spend it.
7515        let mut process_resources = BTreeMap::new();
7516        for module in &supervised {
7517            process_resources.insert(
7518                module.module_id().to_owned(),
7519                crate::subtree_resources::read_process(module.clone()).await,
7520            );
7521        }
7522        // Image evidence uses the same optional deadline, but an exhausted
7523        // budget must not suppress the committed resource view.
7524        let mut image_readings = BTreeMap::new();
7525        for module in &supervised {
7526            image_readings.insert(
7527                module.module_id().to_owned(),
7528                module.running_image_agreement().await,
7529            );
7530        }
7531        let readings = self.resource_tracker.list(supervised.clone());
7532        let mut modules = Vec::new();
7533        for module in supervised {
7534            let status = statuses
7535                .remove(module.module_id())
7536                .expect("each supervised module has a status snapshot");
7537            let (configured, _) = module.configuration().map_err(|err| {
7538                RouterError::backend(
7539                    0,
7540                    frame.header.corr,
7541                    format!("failed to read module configuration: {err}"),
7542                )
7543            })?;
7544            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7545                RouterError::backend(
7546                    0,
7547                    frame.header.corr,
7548                    format!("failed to read retry time: {err}"),
7549                )
7550            })?;
7551            let image = image_readings
7552                .remove(module.module_id())
7553                .expect("each supervised module has an image snapshot");
7554            let resources = process_resources.remove(module.module_id());
7555            let mut verdict =
7556                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7557            verdict.spec = Some(launch_spec_agreement(
7558                &configured,
7559                status.process_alive,
7560                status.launch_spec_digest.as_ref(),
7561            ));
7562            let pending_reload = Some(verdict);
7563            let pending_entry = match &approved {
7564                ApprovedDaemonView::Approved { config, .. } => config
7565                    .modules
7566                    .iter()
7567                    .find(|m| m.module_id == module.module_id()),
7568                _ => None,
7569            };
7570            let pending = self
7571                .pending_module_fields(
7572                    &module,
7573                    pending_entry,
7574                    false,
7575                    Self::registration_channel_in_force(
7576                        publication
7577                            .as_ref()
7578                            .and_then(|view| view.registration_declaration(module.module_id()))
7579                            .as_deref(),
7580                        pending_entry.map(|entry| entry.registration_channel),
7581                    ),
7582                    publication.as_deref(),
7583                )
7584                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7585            let script = configured.script.as_ref().map(|entry| {
7586                let approved = self
7587                    .config_runtime
7588                    .as_ref()
7589                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7590                crate::supervise::script::status(entry, approved.as_ref())
7591            });
7592            let configured_enabled = match &approved {
7593                ApprovedDaemonView::Approved {
7594                    config: approved, ..
7595                } => approved
7596                    .modules
7597                    .iter()
7598                    .find(|module| module.module_id == status.module_id)
7599                    .map(|module| module.enabled),
7600                ApprovedDaemonView::NotStamped => self
7601                    .capability_evaluator
7602                    .configured_enabled(&status.module_id),
7603                ApprovedDaemonView::Unavailable => None,
7604            };
7605            let admission_refused = status
7606                .admission_refused
7607                .clone()
7608                .filter(|_| status.enabled && !status.process_alive)
7609                .filter(|_| {
7610                    publication
7611                        .as_ref()
7612                        .and_then(|view| view.registration_declaration(&status.module_id))
7613                        .as_deref()
7614                        == Some("undeclared")
7615                });
7616            // Keep the retired policy field on the wire for one release so
7617            // existing status consumers still receive the platform policy.
7618            let mut entry = SupervisorEntry::new(
7619                status.module_id,
7620                status.state.to_string(),
7621                status.enabled,
7622                status.live,
7623                status.health.status,
7624            )
7625            .with_configured_enabled(configured_enabled)
7626            .with_script(script)
7627            .with_admission_refused(admission_refused)
7628            .with_next_retry_at_ms(next_retry_at_ms)
7629            .with_launch_nonce_env(Some(!cfg!(unix)))
7630            .with_launch_nonce_source(status.launch_nonce_source)
7631            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7632            .with_protocol(status.protocol)
7633            .with_pending_reload(pending_reload)
7634            .with_last_probe_ms(status.health.last_probe_ms)
7635            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7636            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7637            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7638            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7639            .with_restart_count(Some(status.restart_count))
7640            .with_max_restarts(Some(status.max_restarts))
7641            .with_lifetime_restarts(Some(status.lifetime_restarts))
7642            .with_spawn_generation(Some(status.spawn_generation))
7643            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7644            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7645            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7646            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7647            .with_resources(resources);
7648            entry.pending = pending;
7649            modules.push(entry);
7650        }
7651        for module in &mut modules {
7652            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7653                module.tree = tree.clone();
7654                module.cpu_last_hour = hour.clone();
7655            }
7656            module.tree_unavailable = readings
7657                .reasons
7658                .get(&module.module_id)
7659                .map(|reason| (*reason).to_owned());
7660            if module.tree.is_none() {
7661                module.tree_unavailable = Some(
7662                    if not_running.contains(&module.module_id) {
7663                        "not_running"
7664                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7665                        reason
7666                    } else {
7667                        "not_yet_measured"
7668                    }
7669                    .to_owned(),
7670                );
7671            }
7672        }
7673        let response = ClientControlResponse::SupervisorList {
7674            generation,
7675            modules,
7676            daemon: readings.daemon,
7677            agent_commands: readings.agent_commands,
7678        };
7679        Ok(vec![control_response_body_frame(
7680            &frame,
7681            &response,
7682            "ClientControlResponse::SupervisorList",
7683        )?])
7684    }
7685
7686    fn handle_supervisor_stderr_tail(
7687        &self,
7688        frame: Frame,
7689        module_id: String,
7690        max_lines: Option<u32>,
7691        max_bytes: Option<u32>,
7692    ) -> Result<Vec<Frame>, RouterError> {
7693        let Some(module) = self.supervisor.get(&module_id) else {
7694            return Ok(vec![control_error_frame(
7695                &frame,
7696                "unknown_module",
7697                format!("module_id '{module_id}' is not supervised"),
7698            )?]);
7699        };
7700
7701        let snapshot = module.stderr_tail(
7702            max_lines.map(|value| value as usize),
7703            max_bytes.map(|value| value as usize),
7704        );
7705
7706        let response = ClientControlResponse::SupervisorStderrTail {
7707            module_id,
7708            tail: StderrTail {
7709                capture: match snapshot.capture {
7710                    CaptureState::Captured => StderrCaptureState::Captured,
7711                    CaptureState::Incomplete { reason } => {
7712                        StderrCaptureState::Incomplete { reason }
7713                    }
7714                    CaptureState::NotCaptured { reason } => {
7715                        StderrCaptureState::NotCaptured { reason }
7716                    }
7717                },
7718                entries: snapshot
7719                    .entries
7720                    .into_iter()
7721                    .map(|entry| match entry {
7722                        TailEntry::Line {
7723                            text,
7724                            truncated,
7725                            at_ms,
7726                        } => StderrTailEntry::Line {
7727                            text,
7728                            truncated,
7729                            at_ms,
7730                        },
7731                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7732                    })
7733                    .collect(),
7734                dropped_lines: snapshot.dropped_lines,
7735            },
7736        };
7737        Ok(vec![control_response_body_frame(
7738            &frame,
7739            &response,
7740            "ClientControlResponse::SupervisorStderrTail",
7741        )?])
7742    }
7743
7744    async fn observe_control_wait<F: std::future::Future>(
7745        &self,
7746        ctx: &RouteCtx,
7747        target: Option<&str>,
7748        kind: &'static str,
7749        future: F,
7750    ) -> F::Output {
7751        self.counters
7752            .observe_reader_wait(
7753                || {
7754                    let module = self
7755                        .forwarding
7756                        .module_id_for_connection(ctx.connection_id)
7757                        .ok()
7758                        .flatten();
7759                    let principal = if module.is_some() { "module" } else { "direct" };
7760                    (
7761                        self.resolve_reader_wait_target(kind, target)
7762                            .or(module)
7763                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7764                        principal.into(),
7765                    )
7766                },
7767                kind,
7768                future,
7769            )
7770            .await
7771    }
7772
7773    /// Resolve the reader-wait module ID only from supervisor or registry
7774    /// records; never attribute a wait from the request selector alone.
7775    pub(crate) fn resolve_reader_wait_target(
7776        &self,
7777        op: &str,
7778        selector: Option<&str>,
7779    ) -> Option<String> {
7780        let selector = selector?;
7781        match op {
7782            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7783                .supervisor
7784                .get(selector)
7785                .map(|module| module.module_id().to_owned()),
7786            ops::SUPERVISOR_HEALTH_PROBE => self
7787                .registry
7788                .get_module(selector)
7789                .ok()
7790                .flatten()
7791                .map(|registration| registration.manifest.module_id),
7792            _ => None,
7793        }
7794    }
7795
7796    async fn handle_supervisor_terminals(
7797        &self,
7798        ctx: &RouteCtx,
7799        frame: Frame,
7800        module_id: String,
7801    ) -> Result<Vec<Frame>, RouterError> {
7802        let Some(module) = self.supervisor.get(&module_id) else {
7803            return Ok(vec![control_error_frame(
7804                &frame,
7805                "unknown_module",
7806                format!("module_id '{module_id}' is not supervised"),
7807            )?]);
7808        };
7809
7810        // The journal read runs on a blocking thread: it can be megabytes of
7811        // file I/O and must not occupy a runtime worker.
7812        let terminals = self
7813            .observe_control_wait(
7814                ctx,
7815                Some(module.module_id()),
7816                ops::SUPERVISOR_TERMINALS,
7817                module.read_durable_terminal_history(),
7818            )
7819            .await
7820            .map_err(|error| {
7821                RouterError::backend(
7822                    0,
7823                    frame.header.corr,
7824                    format!("failed to read terminal history: {error}"),
7825                )
7826            })?;
7827        let response = ClientControlResponse::SupervisorTerminals {
7828            module_id,
7829            terminals,
7830        };
7831        Ok(vec![control_response_body_frame(
7832            &frame,
7833            &response,
7834            "ClientControlResponse::SupervisorTerminals",
7835        )?])
7836    }
7837
7838    fn handle_supervisor_routes(
7839        &self,
7840        frame: Frame,
7841        module_id: Option<String>,
7842    ) -> Result<Vec<Frame>, RouterError> {
7843        let modules = self
7844            .forwarding
7845            .route_census(module_id.as_deref())
7846            .map_err(RouterError::Forwarding)?
7847            .into_iter()
7848            .map(|(module_id, routes)| SupervisorRouteModule {
7849                module_id,
7850                routes: routes
7851                    .into_iter()
7852                    .map(|route| SupervisorRoute {
7853                        consumer: match route.principal {
7854                            Principal::Reserved { module_id } => {
7855                                SupervisorRouteConsumer::Reserved { module_id }
7856                            }
7857                            Principal::Direct | Principal::Unverified => {
7858                                SupervisorRouteConsumer::Direct {
7859                                    connection_id: route.goodbye_target.connection_id.get(),
7860                                }
7861                            }
7862                        },
7863                        age_ms: Instant::now()
7864                            .saturating_duration_since(route.bound_at)
7865                            .as_millis()
7866                            .try_into()
7867                            .unwrap_or(u64::MAX),
7868                        draining: route.draining,
7869                        drain_reason: route.drain_reason,
7870                    })
7871                    .collect(),
7872            })
7873            .collect();
7874        let response = ClientControlResponse::SupervisorRoutes { modules };
7875        Ok(vec![control_response_body_frame(
7876            &frame,
7877            &response,
7878            "ClientControlResponse::SupervisorRoutes",
7879        )?])
7880    }
7881
7882    fn running_registration_method(
7883        &self,
7884        module: &str,
7885    ) -> Option<subc_control::RegistrationMethod> {
7886        let registration = self.registry.get_module(module).ok()??;
7887        let connection = registration.connection_id;
7888        let channel = self.supervisor.registration_spawn(connection).is_some();
7889        let nonce = if channel {
7890            None
7891        } else {
7892            self.hello_launch_nonces
7893                .lock()
7894                .ok()?
7895                .nonce(connection)
7896                .map(str::to_owned)
7897        };
7898        if !channel && nonce.is_none() {
7899            return None;
7900        }
7901        self.supervisor
7902            .registration_snapshot_is_current_live(
7903                &self.registry,
7904                module,
7905                connection,
7906                nonce.as_deref(),
7907            )
7908            .then_some(if channel {
7909                subc_control::RegistrationMethod::Channel
7910            } else {
7911                subc_control::RegistrationMethod::Nonce
7912            })
7913    }
7914
7915    async fn handle_supervisor_provenance(
7916        &self,
7917        ctx: &RouteCtx,
7918        frame: Frame,
7919        module_id: Option<String>,
7920    ) -> Result<Vec<Frame>, RouterError> {
7921        let targeted = module_id.is_some();
7922        let selected = if let Some(module_id) = module_id {
7923            let Some(module) = self.supervisor.get(&module_id) else {
7924                return Ok(vec![control_error_frame(
7925                    &frame,
7926                    "unknown_module",
7927                    format!("module_id '{module_id}' is not supervised"),
7928                )?]);
7929            };
7930            vec![module]
7931        } else {
7932            self.supervisor.list()
7933        };
7934
7935        let target = targeted.then(|| selected[0].module_id());
7936        let declarations = if let Some(owner) = &self.config_runtime {
7937            owner
7938                .on_blocking(|owner| owner.registration_declarations())
7939                .await
7940                .ok()
7941        } else {
7942            None
7943        };
7944        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
7945            let mut modules = Vec::with_capacity(selected.len());
7946            let mut extensions = Vec::with_capacity(selected.len());
7947            for module in &selected {
7948                let (status, observed_image) = module
7949                    .status_and_running_image_agreement()
7950                    .await
7951                    .map_err(|err| {
7952                        RouterError::backend(
7953                            0,
7954                            frame.header.corr,
7955                            format!("failed to read supervisor status: {err}"),
7956                        )
7957                    })?;
7958                let module_declared = self
7959                    .registry
7960                    .get_module(&status.module_id)
7961                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
7962                    .and_then(|registration| registration.manifest.provenance)
7963                    .map(|build| ModuleDeclaredProvenance::Reported { build })
7964                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
7965                #[cfg(test)]
7966                let running_image = match &self.provenance_probe_override {
7967                    Some(result) => result.clone(),
7968                    None => observed_image,
7969                };
7970                #[cfg(not(test))]
7971                let running_image = observed_image;
7972                let registration = self.running_registration_method(&status.module_id);
7973                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
7974                    .with_registration(registration);
7975                extension.registration_declaration = declarations
7976                    .as_ref()
7977                    .and_then(|entries| entries.get(&status.module_id))
7978                    .cloned();
7979                if status.process_alive && status.registration_declaration.is_some() {
7980                    extension.registration_declaration = status.registration_declaration.clone();
7981                }
7982                extensions.push(extension);
7983                modules.push(SupervisorModuleProvenance {
7984                    module_id: status.module_id,
7985                    module_declared,
7986                    daemon_observed: SupervisorObservedProcess {
7987                        launch_nonce_source: status.launch_nonce_source,
7988                        pid: status.pid,
7989                        spawned_at_ms: status.spawned_at_ms,
7990                        spawned_from: status.spawned_from,
7991                        running_image,
7992                    },
7993                });
7994            }
7995            let daemon = SupervisorDaemonProvenance {
7996                daemon_build: self.daemon_provenance.build.clone(),
7997                daemon_observed: DaemonObservedProcess {
7998                    pid: self.daemon_provenance.pid,
7999                    started_at_ms: self
8000                        .daemon_provenance
8001                        .start_clock
8002                        .map(|clock| clock.started_at_ms())
8003                        .or(self.daemon_provenance.started_at_ms),
8004                    running_image: self
8005                        .daemon_provenance
8006                        .probe
8007                        .observe(
8008                            self.daemon_provenance.pid,
8009                            self.daemon_provenance.executable_path.as_deref(),
8010                            self.daemon_provenance.executable_identity.clone(),
8011                            self.daemon_provenance.process_start_time,
8012                        )
8013                        .await,
8014                },
8015            };
8016            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8017            let mut response = serde_json::to_value(response)
8018                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8019            for (entry, extension) in response["modules"]
8020                .as_array_mut()
8021                .expect("provenance modules are an array")
8022                .iter_mut()
8023                .zip(extensions)
8024            {
8025                extension.write_to(entry).map_err(|error| {
8026                    RouterError::backend(0, frame.header.corr, error.to_string())
8027                })?;
8028            }
8029            Ok(vec![control_response_body_frame(
8030                &frame,
8031                &response,
8032                "ClientControlResponse::SupervisorProvenance",
8033            )?])
8034        })
8035        .await
8036    }
8037
8038    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8039        self.refresh_capability_requirements();
8040        let publication = self
8041            .config_runtime
8042            .as_ref()
8043            .and_then(|owner| owner.polled_snapshot().ok());
8044        let generation = self
8045            .registry
8046            .generation()
8047            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8048        let modules = self
8049            .supervisor
8050            .list()
8051            .into_iter()
8052            .map(|module| {
8053                let status = module.status_for_control("health").map_err(|err| {
8054                    RouterError::backend(
8055                        0,
8056                        frame.header.corr,
8057                        format!("failed to read supervisor health: {err}"),
8058                    )
8059                })?;
8060                let module_id = status.module_id;
8061                let capability_detail = self
8062                    .capability_evaluator
8063                    .required_problem_detail(&module_id);
8064                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8065                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8066                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8067                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8068                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8069                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8070                Ok(SupervisorHealthEntry {
8071                    module_id,
8072                    status: status.health.status,
8073                    detail: append_capability_problem_detail(
8074                        status.health.detail,
8075                        capability_detail,
8076                    ),
8077                    metrics: status.health.metrics,
8078                    consecutive_failures: status.health.consecutive_failures,
8079                    late_answer_count: status.health.late_answer_count,
8080                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8081                    last_action: status.health.last_action,
8082                    last_action_ms: status.health.last_action_ms,
8083                    last_probe_ms: status.health.last_probe_ms,
8084                })
8085            })
8086            .collect::<Result<Vec<_>, RouterError>>()?;
8087        let response = ClientControlResponse::SupervisorHealth {
8088            generation,
8089            modules,
8090        };
8091        Ok(vec![control_response_body_frame(
8092            &frame,
8093            &response,
8094            "ClientControlResponse::SupervisorHealth",
8095        )?])
8096    }
8097
8098    async fn handle_supervisor_restart(
8099        &self,
8100        frame: Frame,
8101        module_id: String,
8102        drain_timeout_ms: Option<u64>,
8103        requester: Principal,
8104    ) -> Result<Vec<Frame>, RouterError> {
8105        let operation_lock = self.supervisor.operation_lock();
8106        let _operation_guard = operation_lock.lock().await;
8107        let Some(module) = self.supervisor.get(&module_id) else {
8108            return Ok(vec![control_error_frame(
8109                &frame,
8110                "unknown_module",
8111                format!("module_id '{module_id}' is not supervised"),
8112            )?]);
8113        };
8114
8115        self.route_outages.mark_operator_action(&module_id);
8116        if let Err(err) = module
8117            .restart_requested(drain_timeout_ms, Some(requester))
8118            .await
8119        {
8120            self.route_outages
8121                .operator_action_ended_unrefused(&module_id);
8122            let (code, message) = match err {
8123                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8124                crate::supervise::SuperviseError::Disabled { .. } => {
8125                    ("module_disabled", err.to_string())
8126                }
8127                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8128                    ("swap_in_progress", err.to_string())
8129                }
8130                _ => (
8131                    "target_unavailable",
8132                    format!("failed to restart module_id '{module_id}': {err}"),
8133                ),
8134            };
8135            return Ok(vec![control_error_frame(&frame, code, message)?]);
8136        }
8137
8138        let response = ClientControlResponse::SupervisorAck {
8139            module_id,
8140            applied: true,
8141        };
8142        Ok(vec![control_response_body_frame(
8143            &frame,
8144            &response,
8145            "ClientControlResponse::SupervisorAck",
8146        )?])
8147    }
8148
8149    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8150    /// when the old process has finished draining: a caller whose own lane
8151    /// rides the old process must get its reply before that drain waits on it.
8152    async fn handle_supervisor_swap(
8153        &self,
8154        frame: Frame,
8155        module_id: String,
8156        ready_timeout_ms: Option<u64>,
8157        requester: Principal,
8158    ) -> Result<Vec<Frame>, RouterError> {
8159        // The daemon-wide operation lock is held only to resolve the handle,
8160        // not across the swap. The swap can take its whole readiness budget,
8161        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8162        // holding it here would park an operator's stop behind the swap it is
8163        // meant to abort. A rescan or stop that reaches the module during the
8164        // swap is served by the swap itself (see `supervise_swap`).
8165        let module = {
8166            let operation_lock = self.supervisor.operation_lock();
8167            let _operation_guard = operation_lock.lock().await;
8168            self.supervisor.get(&module_id)
8169        };
8170        let Some(module) = module else {
8171            return Ok(vec![control_error_frame(
8172                &frame,
8173                "unknown_module",
8174                format!("module_id '{module_id}' is not supervised"),
8175            )?]);
8176        };
8177
8178        self.route_outages.mark_operator_action(&module_id);
8179        if let Err(err) = module
8180            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8181            .await
8182        {
8183            self.route_outages
8184                .operator_action_ended_unrefused(&module_id);
8185            use crate::supervise::SuperviseError;
8186            let message = err.to_string();
8187            let error = match err {
8188                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8189                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8190                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8191                    code: "swap_refused".to_string(),
8192                    message,
8193                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8194                },
8195                SuperviseError::SwapFailed {
8196                    arm,
8197                    candidate_exit,
8198                    ..
8199                } => ErrorBody {
8200                    code: "swap_failed".to_string(),
8201                    message,
8202                    detail: Some(serde_json::json!({
8203                        "arm": arm.as_str(),
8204                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8205                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8206                    })),
8207                },
8208                _ => ErrorBody::new(
8209                    "target_unavailable",
8210                    format!("failed to swap module_id '{module_id}': {message}"),
8211                ),
8212            };
8213            return Ok(vec![control_error_body_frame(&frame, error)?]);
8214        }
8215        // A completed swap kept the incumbent serving until cutover, so it
8216        // usually opened no outage; a mark left behind would make the next,
8217        // unrelated outage read as requested.
8218        self.route_outages
8219            .operator_action_ended_unrefused(&module_id);
8220
8221        let response = ClientControlResponse::SupervisorAck {
8222            module_id,
8223            applied: true,
8224        };
8225        Ok(vec![control_response_body_frame(
8226            &frame,
8227            &response,
8228            "ClientControlResponse::SupervisorAck",
8229        )?])
8230    }
8231
8232    async fn handle_supervisor_reload(
8233        &self,
8234        frame: Frame,
8235        module_id: String,
8236        requester: Principal,
8237    ) -> Result<Vec<Frame>, RouterError> {
8238        let operation_lock = self.supervisor.operation_lock();
8239        let _operation_guard = operation_lock.lock().await;
8240        let Some(module) = self.supervisor.get(&module_id) else {
8241            return Ok(vec![control_error_frame(
8242                &frame,
8243                "unknown_module",
8244                format!("module_id '{module_id}' is not supervised"),
8245            )?]);
8246        };
8247
8248        self.route_outages.mark_operator_action(&module_id);
8249        if let Err(err) = module.reload_requested(Some(requester)).await {
8250            self.route_outages
8251                .operator_action_ended_unrefused(&module_id);
8252            let (code, message) = match err {
8253                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8254                crate::supervise::SuperviseError::Disabled { .. } => {
8255                    ("module_disabled", err.to_string())
8256                }
8257                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8258                    ("swap_in_progress", err.to_string())
8259                }
8260                _ => (
8261                    "reload_failed",
8262                    format!("failed to reload module_id '{module_id}': {err}"),
8263                ),
8264            };
8265            return Ok(vec![control_error_frame(&frame, code, message)?]);
8266        }
8267
8268        let response = ClientControlResponse::SupervisorAck {
8269            module_id,
8270            applied: true,
8271        };
8272        Ok(vec![control_response_body_frame(
8273            &frame,
8274            &response,
8275            "ClientControlResponse::SupervisorAck",
8276        )?])
8277    }
8278
8279    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8280    /// the configuration comes from and whether to apply it; every mode then
8281    /// runs the same comparison, so a preview describes the apply it previews.
8282    async fn handle_supervisor_rescan(
8283        &self,
8284        frame: Frame,
8285        mode: RescanMode,
8286        requester: Principal,
8287    ) -> Result<Vec<Frame>, RouterError> {
8288        let preview = mode.previews();
8289        let Some(context) = self.rescan.clone() else {
8290            return Ok(vec![control_error_frame(
8291                &frame,
8292                "rescan_unavailable",
8293                "the daemon was not started with a reloadable config path".to_string(),
8294            )?]);
8295        };
8296
8297        let _rescan_guard = context.rescan_lock.lock().await;
8298        let rescan_checked::RescanInput {
8299            config: loaded,
8300            approved_preview,
8301            guard: _operation_guard,
8302        } = match self.rescan_input(&mode, &context).await {
8303            Ok(input) => input,
8304            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
8305        };
8306        // `load` reports a missing file as Ok(None), which is correct at boot
8307        // (no config, nothing to supervise) and catastrophic here: rescan treats
8308        // "not in the config" as "remove it", so an absent file would read as an
8309        // empty module list and retire the entire running fleet. An editor
8310        // writing via write-new-then-rename, or a half-finished edit, is enough
8311        // to open that window. Refuse instead: a config that cannot be read
8312        // carries no instruction to remove anything.
8313        let Some((config, activity_config)) = loaded else {
8314            return Ok(vec![control_error_frame(
8315                &frame,
8316                "invalid_daemon_config",
8317                format!(
8318                    "daemon config not found at {}; refusing to rescan (an absent config would \
8319                     retire every supervised module)",
8320                    context.config_path.display()
8321                ),
8322            )?]);
8323        };
8324        let (
8325            configured_port,
8326            storage_config,
8327            admission_facts_carrier_module_id,
8328            admission_facts_targets,
8329            scope_authority_owners,
8330            federated_scope_owner,
8331            privileged_operator_prompt,
8332            modules,
8333            reserved_capabilities,
8334        ) = (
8335            config.port,
8336            config.storage,
8337            config.admission_facts_carrier_module_id,
8338            config.admission_facts_targets,
8339            config.scope_authority_owners,
8340            config.federated_scope_owner,
8341            config.privileged_operator_prompt,
8342            config.modules,
8343            config.reserved_capabilities,
8344        );
8345
8346        // Collect the sections rescan cannot apply, so the REPLY carries them.
8347        //
8348        // The warning below has always been correct and has always gone only to
8349        // the journal -- addressed to whoever reads logs, while the person who
8350        // just edited the config is looking at the CLI. Naming each section
8351        // individually rather than setting a flag: "something outside modules
8352        // changed" sends the operator back to diffing their own file, which is
8353        // the work this is meant to save.
8354        let mut restart_required = Vec::new();
8355        for section in RestartRequiredSection::ALL {
8356            let changed = match section {
8357                RestartRequiredSection::Port => configured_port != context.configured_port,
8358                RestartRequiredSection::Storage => storage_config != context.storage_config,
8359                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8360                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8361                }
8362                RestartRequiredSection::AdmissionFactsTargets => {
8363                    admission_facts_targets != context.admission_facts_targets
8364                }
8365                RestartRequiredSection::ScopeAuthorityOwners => {
8366                    scope_authority_owners != context.scope_authority_owners
8367                }
8368                RestartRequiredSection::FederatedScopeOwner => {
8369                    federated_scope_owner != context.federated_scope_owner
8370                }
8371                RestartRequiredSection::PrivilegedOperatorPrompt => {
8372                    privileged_operator_prompt != context.privileged_operator_prompt
8373                }
8374            };
8375            if changed {
8376                restart_required.push(section.label().to_string());
8377            }
8378        }
8379        if !restart_required.is_empty() {
8380            warn!(
8381                config_path = %context.config_path.display(),
8382                sections = %restart_required.join(", "),
8383                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8384            );
8385        }
8386
8387        for configured in &modules {
8388            if let Err(err) = validate_spec(&configured.module_spec()) {
8389                return Ok(vec![control_error_frame(
8390                    &frame,
8391                    "invalid_daemon_config",
8392                    format!("supervisor rescan rejected daemon config: {err}"),
8393                )?]);
8394            }
8395        }
8396
8397        let configured_capabilities = modules
8398            .iter()
8399            .map(|module| (module.module_id.clone(), module.enabled))
8400            .collect::<Vec<_>>();
8401        let preview_capability_warnings = if preview {
8402            let (_, registrations) = self.runtime_capability_snapshot()?;
8403            let current_modules = self
8404                .supervisor
8405                .list()
8406                .into_iter()
8407                .map(|module| module.module_id().to_string())
8408                .collect::<BTreeSet<_>>();
8409            let resulting_modules = configured_capabilities.clone();
8410            let removed = current_modules
8411                .into_iter()
8412                .filter(|module_id| {
8413                    !resulting_modules
8414                        .iter()
8415                        .any(|(configured_id, _)| configured_id == module_id)
8416                })
8417                .collect::<Vec<_>>();
8418            // A candidate preview also names providers the candidate disables.
8419            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8420            let disabled = match &mode {
8421                RescanMode::Candidate(_) => resulting_modules
8422                    .iter()
8423                    .filter(|(_, enabled)| !enabled)
8424                    .map(|(module_id, _)| module_id.clone())
8425                    .collect::<Vec<_>>(),
8426                _ => Vec::new(),
8427            };
8428            self.capability_evaluator.preview_warnings(
8429                resulting_modules,
8430                &removed,
8431                &disabled,
8432                &registrations,
8433            )
8434        } else {
8435            Vec::new()
8436        };
8437        let reconciled = match (&mode, approved_preview.as_ref()) {
8438            (RescanMode::Preview, Some(approved)) => Ok((
8439                config_gate::preview_approved_daemon(approved, &modules),
8440                Vec::new(),
8441            )),
8442            (RescanMode::Candidate(candidate), _) => self
8443                .preview_candidate(&context, modules, candidate)
8444                .map(|result| (result, Vec::new())),
8445            _ => {
8446                self.reconcile_supervised_modules(
8447                    &context.supervisor,
8448                    modules,
8449                    preview,
8450                    requester.clone(),
8451                )
8452                .await
8453            }
8454        };
8455        let (result, changed) = match reconciled {
8456            Ok(result) => result,
8457            Err(message) => {
8458                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8459            }
8460        };
8461        if !preview {
8462            if let Some(ledger) = &self.activity {
8463                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8464                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8465            }
8466            if let Err(code) = self.configure_activity(activity_config).await {
8467                warn!(
8468                    code,
8469                    "activity retention could not be applied during rescan"
8470                );
8471            }
8472            self.capability_evaluator
8473                .configure(configured_capabilities, reserved_capabilities);
8474            self.capability_evaluator.wake_deadline_loop();
8475            self.refresh_capability_requirements();
8476        }
8477        let mut result = result;
8478        result.restart_required = restart_required;
8479        result.capability_warnings = preview_capability_warnings;
8480        let response = ClientControlResponse::SupervisorRescan { result };
8481        Ok(vec![control_response_body_frame(
8482            &frame,
8483            &response,
8484            "ClientControlResponse::SupervisorRescan",
8485        )?])
8486    }
8487
8488    async fn handle_supervisor_release_reserved(
8489        &self,
8490        frame: Frame,
8491        module_id: String,
8492    ) -> Result<Vec<Frame>, RouterError> {
8493        let Some(context) = self.rescan.clone() else {
8494            return Ok(vec![control_error_frame(
8495                &frame,
8496                "release_unavailable",
8497                "reserved-id release requires a daemon started with a reloadable config path",
8498            )?]);
8499        };
8500        let operation_lock = self.supervisor.operation_lock();
8501        let _operation_guard = operation_lock.lock().await;
8502        let approved = if let Some(owner) = &self.config_runtime {
8503            // Observe the file as a proposal, but decide membership solely from
8504            // approved bytes. A proposed re-add must not retain a removed id.
8505            match owner
8506                .on_blocking(|owner| {
8507                    owner.observe_file_proposal()?;
8508                    owner.approved_daemon_configuration()
8509                })
8510                .await
8511            {
8512                Ok(config) => config,
8513                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8514            }
8515        } else {
8516            None
8517        };
8518        let loaded = if let Some(approved) = approved {
8519            Ok(Some(approved))
8520        } else {
8521            crate::daemon_config::load(&context.config_path)
8522        };
8523        let loaded = match loaded {
8524            Ok(Some(config)) => config,
8525            Ok(None) => {
8526                return Ok(vec![control_error_frame(
8527                    &frame,
8528                    "invalid_daemon_config",
8529                    format!(
8530                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8531                        context.config_path.display()
8532                    ),
8533                )?])
8534            }
8535            Err(err) => {
8536                return Ok(vec![control_error_frame(
8537                    &frame,
8538                    "invalid_daemon_config",
8539                    format!("unable to verify reserved-id release against daemon config: {err}"),
8540                )?])
8541            }
8542        };
8543        if loaded
8544            .modules
8545            .iter()
8546            .any(|configured| configured.module_id == module_id)
8547        {
8548            return Ok(vec![control_error_frame(
8549                &frame,
8550                "reserved_module_configured",
8551                format!(
8552                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8553                ),
8554            )?]);
8555        }
8556        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8557            return Ok(vec![control_error_frame(
8558                &frame,
8559                "reserved_gate_not_retained",
8560                format!(
8561                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8562                ),
8563            )?]);
8564        }
8565
8566        let response = ClientControlResponse::SupervisorAck {
8567            module_id,
8568            applied: true,
8569        };
8570        Ok(vec![control_response_body_frame(
8571            &frame,
8572            &response,
8573            "ClientControlResponse::SupervisorAck",
8574        )?])
8575    }
8576
8577    /// Compare the configured module set with the supervised one, changing
8578    /// nothing. The staged spec each supervised module holds is what the
8579    /// configured entry is compared with.
8580    fn plan_rescan(
8581        &self,
8582        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8583    ) -> Result<RescanPlan, String> {
8584        let mut current = BTreeMap::new();
8585        for module in self.supervisor.list() {
8586            let (spec, health) = module.configuration().map_err(|err| {
8587                format!(
8588                    "failed to read configuration for module_id '{}': {err}",
8589                    module.module_id()
8590                )
8591            })?;
8592            let enabled = module
8593                .status()
8594                .map_err(|err| {
8595                    format!(
8596                        "failed to read status for module_id '{}': {err}",
8597                        module.module_id()
8598                    )
8599                })?
8600                .enabled;
8601            current.insert(
8602                module.module_id().to_string(),
8603                (module, spec, health, enabled),
8604            );
8605        }
8606        let configured = configured_modules
8607            .into_iter()
8608            .map(|module| (module.module_id.clone(), module))
8609            .collect::<BTreeMap<_, _>>();
8610
8611        let added = configured
8612            .keys()
8613            .filter(|module_id| !current.contains_key(*module_id))
8614            .cloned()
8615            .collect::<Vec<_>>();
8616        let removed = current
8617            .keys()
8618            .filter(|module_id| !configured.contains_key(*module_id))
8619            .cloned()
8620            .collect::<Vec<_>>();
8621        let mut changed_pending_reload = Vec::new();
8622        let mut changed_pending = Vec::new();
8623        let mut configuration_changes = BTreeSet::new();
8624        let mut enabled_changes = BTreeSet::new();
8625        let mut unchanged = 0_u32;
8626        let publication = self
8627            .config_runtime
8628            .as_ref()
8629            .and_then(|owner| owner.polled_snapshot().ok());
8630
8631        for (module_id, configured_module) in &configured {
8632            let Some((module, current_spec, current_health, current_enabled)) =
8633                current.get(module_id)
8634            else {
8635                continue;
8636            };
8637            // Compare the whole launch spec so a future launch field cannot
8638            // accidentally become a live-only policy change. Health is stored
8639            // separately and applies live without replacing the process.
8640            let launch_changed = *current_spec != configured_module.module_spec();
8641            let configuration_changed =
8642                launch_changed || *current_health != configured_module.health;
8643            let pending = self.pending_module_fields(
8644                module,
8645                Some(configured_module),
8646                configuration_changed,
8647                Self::registration_channel_in_force(
8648                    publication
8649                        .as_ref()
8650                        .and_then(|view| view.registration_declaration(module_id))
8651                        .as_deref(),
8652                    publication
8653                        .as_ref()
8654                        .and_then(|view| match &view.approved_daemon {
8655                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8656                                config,
8657                                ..
8658                            } => config
8659                                .modules
8660                                .iter()
8661                                .find(|entry| entry.module_id == *module_id)
8662                                .map(|entry| entry.registration_channel),
8663                            _ => None,
8664                        }),
8665                ),
8666                publication.as_deref(),
8667            )?;
8668            let has_pending = !pending.is_empty();
8669            if has_pending {
8670                changed_pending.push(subc_control::SupervisorPendingModule {
8671                    module_id: module_id.clone(),
8672                    fields: pending
8673                        .into_iter()
8674                        .map(|mut field| {
8675                            field.value = None;
8676                            field
8677                        })
8678                        .collect(),
8679                });
8680            }
8681            // Applying a rescan also replaces the recorded config value, even
8682            // when an operator already put the runtime in the requested state.
8683            let enabled_changed = *current_enabled != configured_module.enabled
8684                || self
8685                    .capability_evaluator
8686                    .configured_enabled(module_id)
8687                    .is_some_and(|enabled| enabled != configured_module.enabled);
8688            if configuration_changed {
8689                configuration_changes.insert(module_id.clone());
8690            }
8691            if launch_changed {
8692                changed_pending_reload.push(module_id.clone());
8693            }
8694            if enabled_changed {
8695                enabled_changes.insert(module_id.clone());
8696            }
8697            if !configuration_changed && !enabled_changed && !has_pending {
8698                unchanged = unchanged.saturating_add(1);
8699            }
8700        }
8701        Ok(RescanPlan {
8702            current,
8703            configured,
8704            added,
8705            removed,
8706            changed_pending_reload,
8707            changed_pending,
8708            configuration_changes,
8709            enabled_changes,
8710            unchanged,
8711        })
8712    }
8713
8714    /// Reconcile the running module set against the configured one.
8715    ///
8716    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8717    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8718    /// deliberately shares this function with the executing path rather than
8719    /// computing the same diff somewhere else -- two implementations of one
8720    /// decision agree until they do not, and the whole value of a preview is that
8721    /// it describes the operation that will actually run.
8722    async fn reconcile_supervised_modules(
8723        &self,
8724        supervisor: &Supervisor,
8725        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8726        preview: bool,
8727        requester: Principal,
8728    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8729        let plan = self.plan_rescan(configured_modules)?;
8730
8731        // Everything above this point is pure computation over two snapshots.
8732        // Everything below MUTATES. The preview returns here so the boundary is a
8733        // single early return rather than a condition repeated at each mutation
8734        // site, where one missed guard would apply part of a change the caller was
8735        // told would not happen.
8736        if preview {
8737            return Ok((plan.preview_result(), Vec::new()));
8738        }
8739        let changed = plan
8740            .configuration_changes
8741            .union(&plan.enabled_changes)
8742            .cloned()
8743            .collect::<Vec<_>>();
8744        let RescanPlan {
8745            current,
8746            configured,
8747            added,
8748            removed,
8749            changed_pending_reload,
8750            changed_pending,
8751            configuration_changes,
8752            enabled_changes,
8753            unchanged,
8754        } = plan;
8755        // The staged generation moves before the first change rather than
8756        // after the last, so a rescan that fails partway still invalidates
8757        // every earlier `supervisor.rescan_checked` preview: part of its diff
8758        // may have run.
8759        if !(added.is_empty()
8760            && removed.is_empty()
8761            && configuration_changes.is_empty()
8762            && changed_pending.is_empty()
8763            && enabled_changes.is_empty())
8764        {
8765            if let Some(context) = &self.rescan {
8766                context
8767                    .generation
8768                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8769            }
8770        }
8771
8772        for module_id in &removed {
8773            let module = &current
8774                .get(module_id)
8775                .expect("removed module came from current supervisor state")
8776                .0;
8777            module
8778                .retire_requested(Some(requester.clone()))
8779                .await
8780                .map_err(|err| {
8781                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8782                })?;
8783            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8784            //
8785            // `handle_route_open` resolves an absent module in three steps:
8786            // registry, then supervisor status, then tombstone. Retiring first
8787            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8788            // went with the teardown above, the supervisor entry went with
8789            // `retire`, and the tombstone does not exist yet -- so a route.open
8790            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8791            // it") for a module that was deliberately removed and whose caller
8792            // should get `module_removed` (TERMINAL, carrying a removal age).
8793            //
8794            // Writing the tombstone first closes it: during the window the
8795            // supervisor entry still answers, so the caller gets
8796            // `target_unavailable` -- retryable, and TRUE, because the module
8797            // is mid-teardown. After both statements it is `module_removed`.
8798            // No instant remains where a removed module reads as one that
8799            // never existed.
8800            //
8801            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8802            // the absence of a test beside a fix invites deletion: these are
8803            // two sync statements with no await between them, so reaching the
8804            // window needs a second worker thread to land exactly between them
8805            // and there is no hook to force it. MEASURED: the 25 daemon_config
8806            // tests pass identically with the old order and the new one, so
8807            // the existing suite cannot see this and a green run is not
8808            // evidence either way. What the suite does hold is the
8809            // post-condition -- a removed module answers `module_removed` --
8810            // which this preserves.
8811            //
8812            // Found by an Athena panel reading the shipped tree against a
8813            // design note (2026-09-19), as the one concrete instance of that
8814            // note's class that survived contact with source. Direction is
8815            // benign: retryable where terminal was intended, never the reverse.
8816            self.supervisor.record_rescan_removal(module_id);
8817            self.supervisor.retire(module_id);
8818            self.route_outages.forget(module_id);
8819        }
8820
8821        for module_id in configured.keys() {
8822            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8823                continue;
8824            };
8825            let configured_module = configured
8826                .get(module_id)
8827                .expect("configured module id came from configured map");
8828            if configuration_changes.contains(module_id) {
8829                module
8830                    .update_configuration(
8831                        configured_module.module_spec(),
8832                        configured_module.health.clone(),
8833                        configured_module.drain_timeout_ms,
8834                    )
8835                    .await
8836                    .map_err(|err| {
8837                        format!(
8838                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8839                        )
8840                    })?;
8841            }
8842            // Config-only drift is applied by the evaluator's config update;
8843            // do not turn it into a runtime start or stop.
8844            if *current_enabled != configured_module.enabled {
8845                // A rescan that starts or stops a module applies an operator's
8846                // edit to the config, so the resulting outage was asked for.
8847                self.route_outages.mark_operator_action(module_id);
8848                module
8849                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8850                    .await
8851                    .map_err(|err| {
8852                        self.route_outages.operator_action_ended_unrefused(module_id);
8853                        format!(
8854                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8855                            configured_module.enabled
8856                        )
8857                    })?;
8858            }
8859        }
8860
8861        for module_id in &added {
8862            let configured_module = configured
8863                .get(module_id)
8864                .expect("added module id came from configured map");
8865            supervisor
8866                .supervise_configured_requested_async(
8867                    configured_module.module_spec(),
8868                    configured_module.enabled,
8869                    configured_module.health.clone(),
8870                    configured_module.drain_timeout_ms,
8871                    configured_module.restart,
8872                    configured_module.register_timeout,
8873                    Some(requester.clone()),
8874                )
8875                .await
8876                .map_err(|err| {
8877                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8878                })?;
8879        }
8880
8881        if let Some(context) = &self.rescan {
8882            let mut entries = context
8883                .module_entries
8884                .lock()
8885                .unwrap_or_else(|e| e.into_inner());
8886            entries.record(&configured, &added, &removed);
8887        }
8888
8889        Ok((
8890            SupervisorRescanResult {
8891                added,
8892                removed,
8893                changed_pending_reload,
8894                changed_pending,
8895                enabled_changes: enabled_changes.iter().cloned().collect(),
8896                unchanged,
8897                preview: false,
8898                // Filled by the caller, which is the only layer that can see the
8899                // previous config to diff against.
8900                restart_required: Vec::new(),
8901                capability_warnings: Vec::new(),
8902                module_actions: Vec::new(),
8903                earlier_pending: Vec::new(),
8904                expect: None,
8905            },
8906            changed,
8907        ))
8908    }
8909
8910    async fn handle_supervisor_set_enabled(
8911        &self,
8912        frame: Frame,
8913        module_id: String,
8914        enabled: bool,
8915        requester: Principal,
8916    ) -> Result<Vec<Frame>, RouterError> {
8917        let operation_lock = self.supervisor.operation_lock();
8918        let _operation_guard = operation_lock.lock().await;
8919        let Some(module) = self.supervisor.get(&module_id) else {
8920            return Ok(vec![control_error_frame(
8921                &frame,
8922                "unknown_module",
8923                format!("module_id '{module_id}' is not supervised"),
8924            )?]);
8925        };
8926
8927        // Enabling counts as well as disabling: a module an operator starts
8928        // is refused until it registers, and that wait was asked for.
8929        self.route_outages.mark_operator_action(&module_id);
8930        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
8931            Ok(applied) => applied,
8932            Err(err) => {
8933                self.route_outages
8934                    .operator_action_ended_unrefused(&module_id);
8935                return Ok(vec![control_error_frame(
8936                    &frame,
8937                    if err.is_config_gate_error() {
8938                        "config_gated"
8939                    } else {
8940                        "target_unavailable"
8941                    },
8942                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
8943                )?]);
8944            }
8945        };
8946        if !applied {
8947            // Already in the requested state: nothing was made unavailable,
8948            // so the mark must not outlive this request.
8949            self.route_outages
8950                .operator_action_ended_unrefused(&module_id);
8951        }
8952
8953        self.capability_evaluator.wake_deadline_loop();
8954        self.refresh_capability_requirements();
8955        let response = ClientControlResponse::SupervisorAck { module_id, applied };
8956        Ok(vec![control_response_body_frame(
8957            &frame,
8958            &response,
8959            "ClientControlResponse::SupervisorAck",
8960        )?])
8961    }
8962
8963    async fn handle_supervisor_health_probe(
8964        &self,
8965        ctx: &RouteCtx,
8966        frame: Frame,
8967        module_id: String,
8968    ) -> Result<Vec<Frame>, RouterError> {
8969        self.refresh_capability_requirements();
8970        let Some(registration) = self
8971            .registry
8972            .get_module(&module_id)
8973            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8974        else {
8975            return Ok(vec![control_error_frame(
8976                &frame,
8977                "unknown_module",
8978                format!("module_id '{module_id}' is not registered"),
8979            )?]);
8980        };
8981
8982        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
8983        // named for it. Making `module_registration_grants_op` return false
8984        // unconditionally reddens five tests, and every one is named for something
8985        // else -- capability relay, probe/bind demultiplexing, supervision-only
8986        // probing. They exercise a successful advertisement check on the way to their
8987        // own subject.
8988        //
8989        // Real protection, fragile in a specific way: narrowing any of those tests to
8990        // focus on its stated subject would silently remove coverage nobody knows
8991        // they are carrying. Recorded here rather than as a sixth test, because the
8992        // useful fact is WHICH tests hold the guard up -- a new test would add
8993        // coverage without telling the next person what the existing ones quietly do.
8994        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
8995        {
8996            return Ok(vec![control_error_frame(
8997                &frame,
8998                "health_not_advertised",
8999                format!("module_id '{module_id}' did not advertise health.check"),
9000            )?]);
9001        }
9002
9003        self.observe_control_wait(
9004            ctx,
9005            Some(&registration.manifest.module_id),
9006            ops::SUPERVISOR_HEALTH_PROBE,
9007            async {
9008                let deadline = Instant::now() + self.health_probe_timeout;
9009                let pending = match self.forwarding.begin_module_control_rpc_for(
9010                    &module_id,
9011                    MODULE_CONTROL_OP_HEALTH_CHECK,
9012                    deadline,
9013                ) {
9014                    Ok(pending) => pending,
9015                    Err(err) => {
9016                        return Ok(vec![control_error_frame(
9017                            &frame,
9018                            forwarding_error_code(&err),
9019                            err.to_string(),
9020                        )?])
9021                    }
9022                };
9023
9024                let PendingModuleControlRpc {
9025                    endpoint,
9026                    module_sink,
9027                    negotiated_ver,
9028                    corr: probe_corr,
9029                    receiver,
9030                } = pending;
9031                let mut guard =
9032                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9033                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9034                    .map_err(|err| {
9035                        RouterError::backend(
9036                            0,
9037                            frame.header.corr,
9038                            format!("failed to encode health.check request: {err}"),
9039                        )
9040                    })?;
9041                let probe_frame = Frame::build_with_version(
9042                    negotiated_ver,
9043                    FrameType::Request,
9044                    control_flags(),
9045                    0,
9046                    0,
9047                    probe_corr,
9048                    probe_body,
9049                )
9050                .map_err(RouterError::FrameBuild)?;
9051
9052                // Queue admission and the reply share one deadline, so a module that
9053                // stops reading cannot park the requesting connection's reader forever.
9054                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9055                    Ok(Ok(())) => {}
9056                    Ok(Err(err)) => {
9057                        return Ok(vec![control_error_frame(
9058                            &frame,
9059                            "target_unavailable",
9060                            err.to_string(),
9061                        )?]);
9062                    }
9063                    Err(_) => {
9064                        return Ok(vec![control_error_frame(
9065                            &frame,
9066                            "module_timeout",
9067                            format!(
9068                                "module_id '{module_id}' did not answer health.check within {:?}",
9069                                self.health_probe_timeout
9070                            ),
9071                        )?]);
9072                    }
9073                }
9074
9075                match timeout_at(deadline, receiver).await {
9076                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9077                        Ok(vec![control_error_frame(
9078                            &frame,
9079                            "invalid_control_body",
9080                            "health.check returned an unexpected config response",
9081                        )?])
9082                    }
9083                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9084                        guard.disarm();
9085                        let Some(report) = response.health_report() else {
9086                            return Ok(vec![control_error_frame(
9087                                &frame,
9088                                "invalid_control_body",
9089                                "health.check RPC returned a non-health response",
9090                            )?]);
9091                        };
9092                        // Metrics go out whole here. The supervisor's cached snapshot
9093                        // caps this blob (see truncate_health_metrics), and this path
9094                        // exists precisely to answer without that cap -- so applying it
9095                        // here would leave no way to see what the cached view drops.
9096                        let HealthReport {
9097                            status,
9098                            detail,
9099                            metrics,
9100                        } = report;
9101                        let capability_detail = self
9102                            .capability_evaluator
9103                            .required_problem_detail(&module_id);
9104                        let response = ClientControlResponse::SupervisorHealthProbe {
9105                            module_id,
9106                            status,
9107                            detail: append_capability_problem_detail(detail, capability_detail),
9108                            metrics,
9109                        };
9110                        Ok(vec![control_response_body_frame(
9111                            &frame,
9112                            &response,
9113                            "ClientControlResponse::SupervisorHealthProbe",
9114                        )?])
9115                    }
9116                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9117                        guard.disarm();
9118                        // The module refused the health probe with its own body, so
9119                        // the refusal is relayed without the daemon-origin flag
9120                        // (bit 6): a client must not read it as the daemon's own
9121                        // refusal, which it may treat as never forwarded.
9122                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9123                    }
9124                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9125                        guard.disarm();
9126                        Ok(vec![control_error_frame(
9127                            &frame,
9128                            "target_unavailable",
9129                            message,
9130                        )?])
9131                    }
9132                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9133                        guard.disarm();
9134                        Ok(vec![control_error_frame(
9135                            &frame,
9136                            "invalid_control_body",
9137                            message,
9138                        )?])
9139                    }
9140                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9141                        guard.disarm();
9142                        Ok(vec![control_error_frame(
9143                            &frame,
9144                            "invalid_control_body",
9145                            format!("expected module-control op '{expected}', got '{actual}'"),
9146                        )?])
9147                    }
9148                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9149                        guard.disarm();
9150                        Ok(vec![control_error_frame(
9151                            &frame,
9152                            "module_timeout",
9153                            format!(
9154                                "module_id '{module_id}' answered health.check after {:?}",
9155                                self.health_probe_timeout
9156                            ),
9157                        )?])
9158                    }
9159                    Ok(Err(_)) => Ok(vec![control_error_frame(
9160                        &frame,
9161                        "target_unavailable",
9162                        "health.check waiter was canceled before the module responded",
9163                    )?]),
9164                    Err(_) => Ok(vec![control_error_frame(
9165                        &frame,
9166                        "module_timeout",
9167                        format!(
9168                            "module_id '{module_id}' did not answer health.check within {:?}",
9169                            self.health_probe_timeout
9170                        ),
9171                    )?]),
9172                }
9173            },
9174        )
9175        .await
9176    }
9177
9178    fn supervisor_status(
9179        &self,
9180        module_id: &str,
9181        corr: u64,
9182    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9183        self.supervisor
9184            .get(module_id)
9185            .map(|module| {
9186                let warming = module.is_warming_for_control("status").map_err(|err| {
9187                    RouterError::backend(
9188                        0,
9189                        corr,
9190                        format!(
9191                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9192                        ),
9193                    )
9194                })?;
9195                module.status_for_control("status").map_err(|err| {
9196                    RouterError::backend(
9197                        0,
9198                        corr,
9199                        format!(
9200                            "failed to read supervisor status for module_id '{module_id}': {err}"
9201                        ),
9202                    )
9203                }).map(|status| (status, warming))
9204            })
9205            .transpose()
9206    }
9207
9208    fn guard_module_control_op(
9209        &self,
9210        frame: &Frame,
9211        module_id: &str,
9212        op: &str,
9213    ) -> Result<Option<Frame>, RouterError> {
9214        if self.module_grants_op(module_id, op, frame.header.corr)? {
9215            return Ok(None);
9216        }
9217
9218        Ok(Some(control_error_frame(
9219            frame,
9220            "op_not_allowed",
9221            format!("module_id '{module_id}' did not grant control op '{op}'"),
9222        )?))
9223    }
9224
9225    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9226        self.registry
9227            .grants_control_op(module_id, op)
9228            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9229    }
9230
9231    fn handle_status_update(
9232        &self,
9233        endpoint: ModuleEndpointId,
9234        frame: Frame,
9235    ) -> Result<Vec<Frame>, RouterError> {
9236        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9237            Ok(update) => update,
9238            Err(err) => {
9239                // Forward-compat: a newer module may push a channel-0 op this subc
9240                // version doesn't know. The control contract says unknown push ops
9241                // are IGNORED, never answered with an error. Only a malformed body
9242                // for an op we DO know is a real error worth surfacing.
9243                if is_known_module_push_op(&frame.body) {
9244                    return Ok(vec![control_error_frame(
9245                        &frame,
9246                        "invalid_control_body",
9247                        format!("malformed module control push body: {err}"),
9248                    )?]);
9249                }
9250                return Ok(Vec::new());
9251            }
9252        };
9253
9254        match update {
9255            ModuleControlPush::RouteStatus {
9256                route_channel,
9257                route_epoch,
9258                status,
9259            } => {
9260                self.forwarding
9261                    .cache_status(endpoint, route_channel, route_epoch, status)
9262                    .map_err(RouterError::Forwarding)?;
9263            }
9264        }
9265        Ok(Vec::new())
9266    }
9267
9268    fn handle_route_poll(
9269        &self,
9270        ctx: &RouteCtx,
9271        frame: Frame,
9272        route_channel: u16,
9273        route_epoch: u32,
9274        kind: PollKind,
9275    ) -> Result<Vec<Frame>, RouterError> {
9276        let snapshot = self
9277            .forwarding
9278            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9279            .map_err(RouterError::Forwarding)?;
9280        let response = match (kind, snapshot) {
9281            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9282                ClientControlResponse::RoutePoll {
9283                    route_channel,
9284                    route_epoch,
9285                    status,
9286                    live: None,
9287                }
9288            }
9289            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9290                route_channel,
9291                route_epoch,
9292                status: None,
9293                live: None,
9294            },
9295            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9296                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9297                // is what makes reporting `true` correct rather than a
9298                // confident guess. `process_live` returns None only when the
9299                // module id has no supervisor snapshot at all -- an
9300                // externally-started module the daemon did not spawn -- and
9301                // for those the supervisor has no opinion to offer, ever. It
9302                // is never None for a supervised module in an unknown state:
9303                // a supervised module always has a snapshot, and the answer
9304                // comes from `state == Running && process_alive`.
9305                //
9306                // The route is Bound, so the module completed a HELLO on a
9307                // live connection; "the process this route points at is
9308                // running" is therefore attested by the binding rather than
9309                // assumed. Reporting `false` for an unsupervised module would
9310                // be the actual lie -- it would tell a client its healthy
9311                // route is dead because the daemon does not manage the
9312                // process.
9313                //
9314                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9315                // module whose liveness is genuinely unknown, e.g. a snapshot
9316                // that has not been populated yet -- THIS DEFAULT BECOMES
9317                // WRONG and must split: unsupervised stays true, unknown
9318                // becomes null so the client can tell the two apart. The
9319                // response field is already `Option<bool>`, so the wire can
9320                // carry that distinction today.
9321                let live = self
9322                    .process_liveness
9323                    .as_ref()
9324                    .and_then(|source| source.process_live(&module_id))
9325                    .unwrap_or(true);
9326                ClientControlResponse::RoutePoll {
9327                    route_channel,
9328                    route_epoch,
9329                    status: None,
9330                    live: Some(live),
9331                }
9332            }
9333            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9334                route_channel,
9335                route_epoch,
9336                status: None,
9337                live: Some(false),
9338            },
9339        };
9340
9341        Ok(vec![control_response_body_frame(
9342            &frame,
9343            &response,
9344            "ClientControlResponse::RoutePoll",
9345        )?])
9346    }
9347
9348    pub(crate) fn observe_module_control_completion(
9349        &self,
9350        completion: ModuleControlRpcCompletion,
9351    ) -> bool {
9352        match completion {
9353            ModuleControlRpcCompletion::Unknown => false,
9354            ModuleControlRpcCompletion::Settled => true,
9355            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9356                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9357                info!(
9358                    module_id = %module_id,
9359                    latency_ms,
9360                    "late health.check answer proves the module is alive"
9361                );
9362                match self
9363                    .supervisor
9364                    .record_late_health_answer(&module_id, latency_ms)
9365                {
9366                    Ok(true) => {}
9367                    Ok(false) => debug!(
9368                        module_id = %module_id,
9369                        latency_ms,
9370                        "late health.check answer has no active supervisor snapshot"
9371                    ),
9372                    Err(err) => warn!(
9373                        module_id = %module_id,
9374                        latency_ms,
9375                        error = %err,
9376                        "failed to record late health.check answer"
9377                    ),
9378                }
9379                true
9380            }
9381        }
9382    }
9383
9384    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9385    /// the module connection whose frame is being handled, or to the client that
9386    /// relay was opened for.
9387    ///
9388    /// This runs on the MODULE connection's frame handler, where returning `Err`
9389    /// ends that connection -- and a module connection carries every client's
9390    /// routes to that module, so ending it costs the whole fleet its tools.
9391    /// `ConnectionClosing` carries the id of the connection that is closing, and
9392    /// when that id is a CLIENT's, the condition is entirely about that one
9393    /// client's route.open. A client-scoped condition has no authority over a
9394    /// shared module connection, so it is logged and the single relay is dropped:
9395    /// the client is going away, and `complete_pending_relay` already removed the
9396    /// relay before failing, so there is nothing left to settle. Anything that
9397    /// relay still reserved is released by that client's own connection teardown,
9398    /// which is already under way -- that is what "closing" means.
9399    ///
9400    /// Every other failure is a statement about THIS connection and stays fatal:
9401    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9402    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9403    /// frames correctly.
9404    fn refuse_to_end_module_connection_for_a_client(
9405        &self,
9406        module_connection_id: ConnectionId,
9407        corr: u64,
9408        err: ForwardingError,
9409    ) -> Result<(), RouterError> {
9410        if let ForwardingError::ConnectionClosing { connection_id } = err {
9411            if connection_id != module_connection_id {
9412                warn!(
9413                    module_connection_id = module_connection_id.get(),
9414                    client_connection_id = connection_id.get(),
9415                    corr,
9416                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9417                );
9418                return Ok(());
9419            }
9420        }
9421        Err(RouterError::Forwarding(err))
9422    }
9423
9424    fn handle_module_relay_response(
9425        &self,
9426        connection_id: ConnectionId,
9427        frame: Frame,
9428    ) -> Result<Vec<Frame>, RouterError> {
9429        let mut secondary_error = None;
9430        let outcome = match frame.header.ty {
9431            FrameType::Response => match module_control_response_probe(&frame.body) {
9432                Ok(probe) if probe.op == "route.bind" => {
9433                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9434                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9435                            RouteBindRelayOutcome::Accepted
9436                        }
9437                        Ok(other) => {
9438                            let message =
9439                                format!("route.bind response carried unexpected body: {other:?}");
9440                            secondary_error = Some(control_error_frame(
9441                                &frame,
9442                                "invalid_control_body",
9443                                message.clone(),
9444                            )?);
9445                            RouteBindRelayOutcome::ModuleGone(message)
9446                        }
9447                        Err(err) => {
9448                            let message = format!("malformed route.bind response body: {err}");
9449                            secondary_error = Some(control_error_frame(
9450                                &frame,
9451                                "invalid_control_body",
9452                                message.clone(),
9453                            )?);
9454                            RouteBindRelayOutcome::ModuleGone(message)
9455                        }
9456                    }
9457                }
9458                Ok(probe) => {
9459                    let outcome = if matches!(
9460                        probe.op.as_str(),
9461                        "config.review" | "consent/v1" | "projects.enumerate"
9462                    ) {
9463                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9464                    } else {
9465                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9466                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9467                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9468                                "malformed {} response body: {err}",
9469                                probe.op
9470                            )),
9471                        }
9472                    };
9473                    let completion = self
9474                        .forwarding
9475                        .complete_module_control_rpc(
9476                            connection_id,
9477                            frame.header.corr,
9478                            Some(&probe.op),
9479                            outcome,
9480                        )
9481                        .map_err(RouterError::Forwarding)?;
9482                    if !self.observe_module_control_completion(completion) {
9483                        debug!(
9484                            connection_id = connection_id.get(),
9485                            corr = frame.header.corr,
9486                            op = %probe.op,
9487                            "dropping late or unknown module-control RPC response"
9488                        );
9489                    }
9490                    return Ok(Vec::new());
9491                }
9492                Err(err) => {
9493                    if let Some(expected_op) = self
9494                        .forwarding
9495                        .pending_module_control_op(connection_id, frame.header.corr)
9496                        .map_err(RouterError::Forwarding)?
9497                    {
9498                        let completion = self
9499                            .forwarding
9500                            .complete_module_control_rpc(
9501                                connection_id,
9502                                frame.header.corr,
9503                                None,
9504                                ModuleControlRpcOutcome::MalformedResponse(format!(
9505                                    "malformed {expected_op} response body: {err}"
9506                                )),
9507                            )
9508                            .map_err(RouterError::Forwarding)?;
9509                        if !self.observe_module_control_completion(completion) {
9510                            debug!(
9511                                connection_id = connection_id.get(),
9512                                corr = frame.header.corr,
9513                                "dropping late malformed module-control RPC response"
9514                            );
9515                        }
9516                        return Ok(Vec::new());
9517                    }
9518                    let message = format!("malformed route.bind response body: {err}");
9519                    secondary_error = Some(control_error_frame(
9520                        &frame,
9521                        "invalid_control_body",
9522                        message.clone(),
9523                    )?);
9524                    RouteBindRelayOutcome::ModuleGone(message)
9525                }
9526            },
9527            FrameType::Error => {
9528                if self
9529                    .forwarding
9530                    .pending_module_control_op(connection_id, frame.header.corr)
9531                    .map_err(RouterError::Forwarding)?
9532                    .is_some()
9533                {
9534                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9535                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9536                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9537                            "malformed module-control ERROR body: {err}"
9538                        )),
9539                    };
9540                    let completion = self
9541                        .forwarding
9542                        .complete_module_control_rpc(
9543                            connection_id,
9544                            frame.header.corr,
9545                            None,
9546                            outcome,
9547                        )
9548                        .map_err(RouterError::Forwarding)?;
9549                    if !self.observe_module_control_completion(completion) {
9550                        debug!(
9551                            connection_id = connection_id.get(),
9552                            corr = frame.header.corr,
9553                            "dropping late or unknown module-control RPC error"
9554                        );
9555                    }
9556                    return Ok(Vec::new());
9557                }
9558                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9559                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9560                    Err(err) => {
9561                        let message = format!("malformed route.bind ERROR body: {err}");
9562                        secondary_error = Some(control_error_frame(
9563                            &frame,
9564                            "invalid_control_body",
9565                            message.clone(),
9566                        )?);
9567                        RouteBindRelayOutcome::ModuleGone(message)
9568                    }
9569                }
9570            }
9571            ty => {
9572                return Ok(vec![control_error_frame(
9573                    &frame,
9574                    "unsupported_control_frame",
9575                    format!("unsupported module channel-0 frame {ty:?}"),
9576                )?])
9577            }
9578        };
9579
9580        let settled = self.settle_route_bind_relay(connection_id, frame.header.corr, outcome);
9581        let completion = match settled {
9582            Ok(completion) => completion,
9583            Err(err) => {
9584                self.refuse_to_end_module_connection_for_a_client(
9585                    connection_id,
9586                    frame.header.corr,
9587                    err,
9588                )?;
9589                return Ok(secondary_error.into_iter().collect());
9590            }
9591        };
9592        if let Some(target) = completion.abandoned.as_ref() {
9593            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9594        }
9595        if !completion.settled {
9596            debug!(
9597                connection_id = connection_id.get(),
9598                corr = frame.header.corr,
9599                frame_type = ?frame.header.ty,
9600                "dropping late or unknown route.bind relay response"
9601            );
9602        }
9603        Ok(secondary_error.into_iter().collect())
9604    }
9605
9606    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9607        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9608        // GOODBYE ends the connection's logical session even when its socket
9609        // stays open. Use disconnect teardown so verdicts, client notices and
9610        // scope authority are released at the same lifecycle boundary.
9611        self.cleanup_connection_with_end_reason(
9612            connection_id,
9613            RegistrationEndReason::ExplicitGoodbye,
9614        )
9615        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9616        Ok(Vec::new())
9617    }
9618}
9619
9620impl Default for ControlHandler {
9621    fn default() -> Self {
9622        Self::new(Arc::new(Registry::default()))
9623    }
9624}
9625
9626impl crate::supervise::SwapPromotionObserver for ControlHandler {
9627    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9628        self.apply_registration_capabilities(registration);
9629    }
9630}
9631
9632fn append_capability_problem_detail(
9633    detail: Option<String>,
9634    capability_detail: Option<String>,
9635) -> Option<String> {
9636    match (detail, capability_detail) {
9637        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9638        (Some(detail), None) => Some(detail),
9639        (None, Some(capability_detail)) => Some(capability_detail),
9640        (None, None) => None,
9641    }
9642}
9643
9644fn subc_ops() -> Vec<String> {
9645    SUBC_CONTROL_OPS
9646        .iter()
9647        .map(|op| (*op).to_string())
9648        .collect()
9649}
9650
9651fn module_subc_ops() -> Vec<String> {
9652    SUBC_CONTROL_OPS
9653        .iter()
9654        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9655        .map(|op| (*op).to_string())
9656        .collect()
9657}
9658
9659#[cfg(test)]
9660fn module_baseline_control_ops() -> Vec<String> {
9661    MODULE_BASELINE_CONTROL_OPS
9662        .iter()
9663        .map(|op| (*op).to_string())
9664        .collect()
9665}
9666
9667fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9668    let mut seen = HashSet::new();
9669    let mut effective = Vec::new();
9670    for op in MODULE_BASELINE_CONTROL_OPS {
9671        if seen.insert((*op).to_string()) {
9672            effective.push((*op).to_string());
9673        }
9674    }
9675    for op in declared.unwrap_or_default() {
9676        if seen.insert(op.clone()) {
9677            effective.push(op);
9678        }
9679    }
9680    effective
9681}
9682
9683fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9684    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9685}
9686
9687fn target_module_id(target: &RouteTarget) -> &str {
9688    match target {
9689        RouteTarget::ToolProvider { module_id }
9690        | RouteTarget::ManagementSurface { module_id }
9691        | RouteTarget::InternalService { module_id, .. } => module_id,
9692    }
9693}
9694
9695fn target_has_required_role(
9696    target: &RouteTarget,
9697    roles: &[crate::registry::AdmissionRole],
9698) -> bool {
9699    use crate::registry::AdmissionRole;
9700    roles.iter().any(|role| match (target, role) {
9701        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9702        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9703        (
9704            RouteTarget::InternalService { service_id, .. },
9705            AdmissionRole::InternalService(provided),
9706        ) => service_id == provided,
9707        _ => false,
9708    })
9709}
9710
9711fn is_routable_role(role: &ProviderRole) -> bool {
9712    matches!(
9713        role,
9714        ProviderRole::ToolProvider { .. }
9715            | ProviderRole::ManagementSurface { .. }
9716            | ProviderRole::InternalService { .. }
9717    )
9718}
9719
9720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9721enum ControlRequestBodyError {
9722    UnknownOp,
9723    InvalidBody,
9724}
9725
9726#[derive(Debug, Deserialize)]
9727struct ControlOpProbe {
9728    op: String,
9729}
9730
9731fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9732    serde_json::from_slice(body).or_else(|original| {
9733        #[derive(Deserialize)]
9734        struct ConsentProbe {
9735            protocol: String,
9736        }
9737        match serde_json::from_slice::<ConsentProbe>(body) {
9738            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9739                Ok(ControlOpProbe { op: probe.protocol })
9740            }
9741            _ => Err(original),
9742        }
9743    })
9744}
9745
9746/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9747/// this set is treated as a forward-compat unknown and ignored rather than errored.
9748const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9749
9750fn is_known_module_push_op(body: &[u8]) -> bool {
9751    serde_json::from_slice::<ControlOpProbe>(body)
9752        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9753        .unwrap_or(false)
9754}
9755
9756fn is_known_module_request_op(body: &[u8]) -> bool {
9757    serde_json::from_slice::<ControlOpProbe>(body)
9758        .map(|probe| is_module_to_subc_op(&probe.op))
9759        .unwrap_or(false)
9760}
9761
9762fn is_module_to_subc_op(op: &str) -> bool {
9763    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9764}
9765
9766fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9767    debug!(
9768        op = %op,
9769        connection_id = connection_id.get(),
9770        corr,
9771        "control dispatch"
9772    );
9773}
9774
9775fn log_slow_control_dispatch(
9776    dispatch_started_at: Option<StdInstant>,
9777    op: &'static str,
9778    connection_id: ConnectionId,
9779    corr: u64,
9780    route_open_timings: Option<&RouteOpenTimings>,
9781) {
9782    let Some(dispatch_started_at) = dispatch_started_at else {
9783        return;
9784    };
9785    // Use the same monotonic clock as the phase timers and relay deadline.
9786    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9787    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9788        if let Some(timings) = route_open_timings {
9789            warn!(
9790                op = %op,
9791                connection_id = connection_id.get(),
9792                corr,
9793                elapsed_ms = elapsed.as_millis() as u64,
9794                module_id = ?timings.module_id,
9795                principal = %timings.principal,
9796                admission_ms = timings.admission.as_millis() as u64,
9797                project_root_ms = timings.project_root.as_millis() as u64,
9798                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9799                bind_send_ms = timings.bind_send.as_millis() as u64,
9800                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9801                "slow control dispatch"
9802            );
9803            return;
9804        }
9805        warn!(
9806            op = %op,
9807            connection_id = connection_id.get(),
9808            corr,
9809            elapsed_ms = elapsed.as_millis() as u64,
9810            "slow control dispatch"
9811        );
9812    }
9813}
9814
9815/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9816#[cfg(test)]
9817type TestCallerLookup =
9818    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9819
9820/// Every new client operation needs an explicit privilege decision here.
9821fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9822    request.privileged_operation()
9823}
9824
9825trait PrivilegedRequest {
9826    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9827}
9828
9829impl PrivilegedRequest for ClientControlRequest {
9830    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9831        let request = self;
9832        match request {
9833        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9834            Some(PrivilegedOperation::Restart { module_id })
9835        }
9836        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9837            Some(PrivilegedOperation::Swap { module_id })
9838        }
9839        ClientControlRequest::SupervisorReload { module_id } => {
9840            Some(PrivilegedOperation::Reload { module_id })
9841        }
9842        ClientControlRequest::SupervisorRescan { preview } => {
9843            if *preview {
9844                None
9845            } else {
9846                Some(PrivilegedOperation::Rescan)
9847            }
9848        }
9849        // Only the well-formed apply asks for approval. A preview changes
9850        // nothing, and any other combination is refused before it touches
9851        // anything, so prompting the operator for it would ask about a request
9852        // that cannot run.
9853        ClientControlRequest::SupervisorRescanChecked {
9854            preview,
9855            candidate,
9856            expect,
9857        } => (!*preview && candidate.is_none() && expect.is_some())
9858            .then_some(PrivilegedOperation::Rescan),
9859        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9860            Some(PrivilegedOperation::SetEnabled {
9861                module_id,
9862                enabled: *enabled,
9863            })
9864        }
9865        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9866            Some(PrivilegedOperation::ReleaseReserved { module_id })
9867        }
9868        ClientControlRequest::ServerDescribe {}
9869        // The announcement uses the same client admission as supervisor.restart,
9870        // but cannot stop anything itself and needs no operator confirmation.
9871        | ClientControlRequest::DaemonShutdownIntent { .. }
9872        | ClientControlRequest::CatalogList { .. }
9873        | ClientControlRequest::RouteOpen { .. }
9874        | ClientControlRequest::RoutePoll { .. }
9875        | ClientControlRequest::SupervisorList {}
9876        | ClientControlRequest::SupervisorHealth {}
9877        | ClientControlRequest::SupervisorHealthProbe { .. }
9878        | ClientControlRequest::SupervisorRoutes { .. }
9879        | ClientControlRequest::SupervisorProvenance { .. }
9880        | ClientControlRequest::SupervisorStderrTail { .. }
9881        | ClientControlRequest::SupervisorTerminals { .. }
9882        | ClientControlRequest::SupervisorSpawnSnapshot {}
9883        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9884    }
9885    }
9886}
9887
9888fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9889    match request {
9890        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9891        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9892        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
9893        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
9894        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
9895        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
9896        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
9897        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
9898        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
9899        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
9900        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
9901        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
9902        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
9903        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
9904        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
9905        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
9906        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
9907        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
9908        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
9909        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
9910        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
9911    }
9912}
9913
9914/// The caller of one `route.open`, as its `route.open refused` line names it.
9915///
9916/// A connection id alone cannot name a caller after the fact: ids restart at
9917/// every daemon restart, so the same number belongs to different modules
9918/// before and after one. These three fields are what the refused line needs
9919/// to be attributable on its own, and they are rendered with the same helpers
9920/// as the `route.open accepted` line so both directions grep alike.
9921struct RouteOpenCaller {
9922    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
9923    /// when the request presented a consumer identity whose launch nonce did
9924    /// not verify. The claimed module id is never printed as a principal.
9925    principal: String,
9926    /// `none` for an unscoped open; the admitted stamp's label once scope
9927    /// admission issued one; before that, the requested selector's label.
9928    scope: String,
9929    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
9930    /// because it is a string the caller chose.
9931    harness: String,
9932}
9933
9934impl RouteOpenCaller {
9935    fn new(
9936        principal: Option<&Principal>,
9937        scope: Option<&ScopeSelector>,
9938        identity: &BindIdentity,
9939    ) -> Self {
9940        Self {
9941            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
9942            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
9943            harness: bounded_log_text(&identity.harness),
9944        }
9945    }
9946
9947    /// For a refusal that has no parsed request at hand: names whatever the
9948    /// frame still says, and `unknown` where it says nothing parseable.
9949    fn unknown() -> Self {
9950        Self {
9951            principal: "unknown".to_string(),
9952            scope: "unknown".to_string(),
9953            harness: "unknown".to_string(),
9954        }
9955    }
9956}
9957
9958/// Longest client-chosen text (a scope ref, a harness) a route.open log line
9959/// prints before cutting it.
9960const MAX_LOGGED_TEXT_CHARS: usize = 64;
9961
9962/// `value` Debug-quoted, so control characters land escaped and cannot forge
9963/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
9964/// `…` inside the quotes so one request cannot flood the line.
9965fn bounded_log_text(value: &str) -> String {
9966    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
9967    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
9968        bounded.push('…');
9969    }
9970    format!("{bounded:?}")
9971}
9972
9973/// The `scope=` field of the `route.open accepted` line, from the stamp that
9974/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
9975/// so a ref holding control characters cannot forge a log line, and cut to 64
9976/// characters with a trailing `…` to bound the line. The bind proof and the
9977/// scope's attributes never appear.
9978fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
9979    use subc_protocol::scope::ScopeKind;
9980    let kind = match stamp.kind {
9981        ScopeKind::Head => "head",
9982        ScopeKind::Worker => "worker",
9983        ScopeKind::Ephemeral => "ephemeral",
9984        ScopeKind::Federated => "federated",
9985        _ => "unknown",
9986    };
9987    format!(
9988        "{kind}/{}/{}@{}",
9989        principal_label(&stamp.owner),
9990        bounded_log_text(&stamp.scope_ref),
9991        stamp.scope_epoch
9992    )
9993}
9994
9995/// The `scope=` field of a `route.open refused` line for an open refused
9996/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
9997/// The kind is not known yet, so the literal `requested` stands in its place.
9998/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
9999/// owner it has not been checked against the configured modules: a quoted
10000/// owner means the value was never validated. The bind proof never appears.
10001fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10002    let epoch = selector
10003        .scope_epoch
10004        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10005    format!(
10006        "requested/{}/{}@{epoch}",
10007        bounded_log_text(&principal_label(&selector.owner)),
10008        bounded_log_text(&selector.scope_ref),
10009    )
10010}
10011
10012fn principal_label(principal: &Principal) -> String {
10013    match principal {
10014        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10015        Principal::Direct => "direct".to_string(),
10016        other => format!("{other:?}"),
10017    }
10018}
10019
10020fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10021    match request {
10022        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10023        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10024            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10025        }
10026        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10027        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10028        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10029        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10030        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10031            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10032        }
10033        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10034        _ => "unsupported",
10035    }
10036}
10037
10038fn parse_client_control_request(
10039    body: &[u8],
10040) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10041    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10042        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10043            Ok(probe)
10044                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10045                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10046            {
10047                ControlRequestBodyError::InvalidBody
10048            }
10049            Ok(_) => ControlRequestBodyError::UnknownOp,
10050            Err(_) => ControlRequestBodyError::InvalidBody,
10051        };
10052        (err, classification)
10053    })
10054}
10055
10056fn parse_module_control_request_from_module(
10057    body: &[u8],
10058) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10059    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10060        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10061            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10062            Ok(_) => ControlRequestBodyError::UnknownOp,
10063            Err(_) => ControlRequestBodyError::InvalidBody,
10064        };
10065        (err, classification)
10066    })
10067}
10068
10069#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10070enum ProviderRoleKind {
10071    ToolProvider,
10072    PipelineStage,
10073    ManagementSurface,
10074    InternalService,
10075}
10076
10077fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10078    match role {
10079        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10080        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10081        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10082        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10083    }
10084}
10085
10086fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10087    roles.iter().map(provider_role_kind).collect()
10088}
10089
10090/// Most refused scope records named individually in the log per sync; the
10091/// `refused` count on the accepted line is always complete.
10092const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10093
10094/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10095#[derive(Debug, Default, PartialEq, Eq)]
10096struct ScopeOutcomeCounts {
10097    created: usize,
10098    replaced: usize,
10099    updated: usize,
10100    unchanged: usize,
10101    refused: usize,
10102}
10103
10104impl ScopeOutcomeCounts {
10105    fn of(results: &[ScopeRecordResult]) -> Self {
10106        let mut counts = Self::default();
10107        for result in results {
10108            let slot = match result.outcome {
10109                ScopeRecordOutcome::Created => &mut counts.created,
10110                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10111                ScopeRecordOutcome::Updated => &mut counts.updated,
10112                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10113                ScopeRecordOutcome::Refused => &mut counts.refused,
10114            };
10115            *slot += 1;
10116        }
10117        counts
10118    }
10119}
10120
10121#[cfg(test)]
10122mod scope_outcome_count_tests {
10123    use super::*;
10124
10125    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10126        ScopeRecordResult {
10127            scope_ref: "r".to_string(),
10128            scope_epoch: 1,
10129            outcome,
10130            code: None,
10131            message: None,
10132            version: None,
10133            parent_state: None,
10134        }
10135    }
10136
10137    /// Each outcome lands in its own count, so a refused record can never be
10138    /// hidden inside the total the log already printed.
10139    #[test]
10140    fn every_outcome_is_counted_in_its_own_field() {
10141        let results = [
10142            result(ScopeRecordOutcome::Created),
10143            result(ScopeRecordOutcome::Created),
10144            result(ScopeRecordOutcome::Replaced),
10145            result(ScopeRecordOutcome::Updated),
10146            result(ScopeRecordOutcome::Unchanged),
10147            result(ScopeRecordOutcome::Refused),
10148            result(ScopeRecordOutcome::Refused),
10149            result(ScopeRecordOutcome::Refused),
10150        ];
10151        assert_eq!(
10152            ScopeOutcomeCounts::of(&results),
10153            ScopeOutcomeCounts {
10154                created: 2,
10155                replaced: 1,
10156                updated: 1,
10157                unchanged: 1,
10158                refused: 3,
10159            }
10160        );
10161    }
10162}
10163
10164/// Return whether a catalog change can create a newly violating live route.
10165/// Removing an attested claim is intentionally excluded: it makes fewer routes
10166/// forbidden and therefore must leave the existing route census untouched.
10167fn capability_census_trigger(
10168    old: Option<&CapabilityDeclarations>,
10169    new: Option<&CapabilityDeclarations>,
10170) -> bool {
10171    let old_provides = old
10172        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10173        .unwrap_or_default();
10174    let old_denies = old
10175        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10176        .unwrap_or_default();
10177    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10178        provides: Vec::new(),
10179        requires: Vec::new(),
10180        must_never_reach: Vec::new(),
10181    });
10182
10183    new.provides
10184        .iter()
10185        .any(|capability| !old_provides.contains(capability))
10186        || new
10187            .must_never_reach
10188            .iter()
10189            .any(|capability| !old_denies.contains(capability))
10190}
10191
10192fn catalog_update_frozen_field_message(
10193    registered: &ModuleManifest,
10194    provides: &[ProviderRole],
10195) -> Option<String> {
10196    let old_has_provides = !registered.provides.is_empty();
10197    let new_has_provides = !provides.is_empty();
10198    if old_has_provides != new_has_provides {
10199        return Some(format!(
10200            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10201            registered.module_id
10202        ));
10203    }
10204
10205    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10206        return Some(format!(
10207            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10208            registered.module_id
10209        ));
10210    }
10211
10212    let registered_concurrency = manifest_concurrency(registered);
10213    let mut candidate = registered.clone();
10214    candidate.provides = provides.to_vec();
10215    let candidate_concurrency = manifest_concurrency(&candidate);
10216    if candidate_concurrency != registered_concurrency {
10217        return Some(format!(
10218            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10219            registered.module_id, registered_concurrency, candidate_concurrency
10220        ));
10221    }
10222
10223    // control_ops live beside the manifest in the HELLO body, not inside
10224    // ModuleManifest, so a provides-only catalog.update cannot change them.
10225    None
10226}
10227
10228fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10229    manifest.provides.iter().any(is_routable_role)
10230}
10231
10232/// Returns the routable-provider concurrency subc should enforce for this manifest.
10233///
10234/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10235/// InternalService has no role-specific concurrency field, so it retains the
10236/// existing ModuleManaged default for backward compatibility.
10237fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10238    manifest
10239        .provides
10240        .iter()
10241        .find_map(|provider| match provider {
10242            ProviderRole::ToolProvider { concurrency, .. }
10243            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10244            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10245        })
10246        .unwrap_or(Concurrency::ModuleManaged)
10247}
10248
10249/// True when the manifest carries a ManagementSurface role whose concurrency
10250/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10251/// bytes because the typed manifest deliberately erases that distinction: the
10252/// default exists for wire compatibility, and this probe exists so the default
10253/// stays observable. Any parse irregularity returns false -- the caller only
10254/// logs, and a malformed body already failed registration upstream.
10255fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10256    let has_management_surface = manifest
10257        .provides
10258        .iter()
10259        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10260    if !has_management_surface {
10261        return false;
10262    }
10263    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10264        return false;
10265    };
10266    let Some(provides) = raw
10267        .get("manifest")
10268        .and_then(|manifest| manifest.get("provides"))
10269        .and_then(serde_json::Value::as_array)
10270    else {
10271        return false;
10272    };
10273    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10274    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10275    // against the management_surface_manifest_without_concurrency golden, not
10276    // recalled (the externally-tagged guess was this function's first bug).
10277    provides.iter().any(|role| {
10278        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10279            && role.get("concurrency").is_none()
10280    })
10281}
10282
10283fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10284    if peer_version != PROTOCOL_VERSION {
10285        return Err(format!(
10286            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10287        ));
10288    }
10289    Ok(PROTOCOL_VERSION)
10290}
10291
10292fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10293    Frame::build_with_version(
10294        response_version(frame),
10295        FrameType::Pong,
10296        frame.header.flags,
10297        0,
10298        0,
10299        frame.header.corr,
10300        Vec::new(),
10301    )
10302    .map_err(RouterError::FrameBuild)
10303}
10304
10305pub(crate) fn control_error_frame(
10306    frame: &Frame,
10307    code: &'static str,
10308    message: impl Into<String>,
10309) -> Result<Frame, RouterError> {
10310    control_error_body_frame(
10311        frame,
10312        ErrorBody {
10313            code: code.to_string(),
10314            message: message.into(),
10315            detail: None,
10316        },
10317    )
10318}
10319
10320/// A channel-0 ERROR for a refusal the daemon decided itself: every
10321/// route.open refusal, the drain `module_reloading` and scope-change/end
10322/// bodies, spawn-subscription and supervisor refusals. Carries the
10323/// daemon-origin bit, which is what lets a client treat `module_reloading`
10324/// as proof that its request never reached a module. Response, push,
10325/// goodbye and relay-request frames keep the plain control flags in their
10326/// own builders.
10327pub(crate) fn control_error_body_frame(
10328    frame: &Frame,
10329    error: ErrorBody,
10330) -> Result<Frame, RouterError> {
10331    control_error_frame_with_flags(frame, error, daemon_error_flags())
10332}
10333
10334/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10335/// refused route.bind answered as a route.open refusal, or a refused
10336/// module-control RPC. Plain control flags — the code and message are
10337/// module-chosen, so the frame must not claim daemon authorship, even when
10338/// the module picks a daemon code like `module_reloading`.
10339fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10340    control_error_frame_with_flags(frame, error, control_flags())
10341}
10342
10343fn control_error_frame_with_flags(
10344    frame: &Frame,
10345    error: ErrorBody,
10346    flags: Flags,
10347) -> Result<Frame, RouterError> {
10348    let body = serde_json::to_vec(&error).map_err(|err| {
10349        RouterError::backend(
10350            0,
10351            frame.header.corr,
10352            format!("failed to encode control ERROR: {err}"),
10353        )
10354    })?;
10355
10356    Frame::build_with_version(
10357        response_version(frame),
10358        FrameType::Error,
10359        flags,
10360        0,
10361        0,
10362        frame.header.corr,
10363        body,
10364    )
10365    .map_err(RouterError::FrameBuild)
10366}
10367
10368pub(crate) fn control_response_body_frame<T: Serialize>(
10369    frame: &Frame,
10370    reply: &T,
10371    label: &'static str,
10372) -> Result<Frame, RouterError> {
10373    let body = serde_json::to_vec(reply).map_err(|err| {
10374        RouterError::backend(
10375            0,
10376            frame.header.corr,
10377            format!("failed to encode {label}: {err}"),
10378        )
10379    })?;
10380
10381    Frame::build_with_version(
10382        response_version(frame),
10383        FrameType::Response,
10384        control_flags(),
10385        0,
10386        0,
10387        frame.header.corr,
10388        body,
10389    )
10390    .map_err(RouterError::FrameBuild)
10391}
10392
10393/// Map a forwarding failure to the wire code a client sees.
10394///
10395/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10396/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10397/// chosen here decides whether a caller retries or gives up.
10398///
10399/// That makes attribution the load-bearing property, not merely having a code. A
10400/// permanent fault published as a retryable one produces a fleet-wide retry storm
10401/// against something that can never recover; a transient fault published as
10402/// permanent gives up on work that would have succeeded. Both look correct in a
10403/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10404/// the mapping per variant rather than merely asserting that some code exists.
10405///
10406/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10407/// two codes on the same side of the boundary passes it. Measured rather than
10408/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10409/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10410/// a test named for something else that happens to assert the string.
10411///
10412/// That accidental coverage is deliberately left alone rather than promoted to a
10413/// named test, because it guards a property this function does not promise.
10414/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10415/// specific code within a class, so identity is free to change and only the
10416/// partition is a contract. Splitting it out would assert a guarantee nothing
10417/// depends on — and a suite that promises more than the code does is the harder
10418/// thing to correct later, because the next reader cannot tell which assertions
10419/// are load-bearing.
10420///
10421/// Pin identity here the moment a consumer branches on a specific code.
10422/// The spawn a HELLO would register as and the provider declarations it
10423/// requests, carried from the HELLO's checks to the point the registry
10424/// accepts it.
10425struct HelloAuthority {
10426    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10427    requested: ProviderDeclarations,
10428    /// Whether admitting this HELLO froze the spawn's requested declarations,
10429    /// so a refusal after admission undoes that freeze and no other.
10430    froze: std::sync::atomic::AtomicBool,
10431}
10432
10433fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10434    match err {
10435        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10436        ForwardingError::NoModuleConnection => "target_unavailable",
10437        ForwardingError::ModuleReloading { .. } => "module_reloading",
10438        ForwardingError::ClientRouteChannelExhausted { .. }
10439        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10440        ForwardingError::StaleModuleEndpoint
10441        | ForwardingError::UnknownReservation { .. }
10442        | ForwardingError::ConnectionClosing { .. }
10443        | ForwardingError::ClientEgressClosed { .. }
10444        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10445        // Only a swap candidate's registration can produce this, and it means
10446        // exactly what a second active HELLO for a live id means.
10447        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10448        ForwardingError::TargetRegistrationChanged(_) => "capability_forbidden",
10449        ForwardingError::RelayDeadlineElapsed => "module_timeout",
10450        ForwardingError::RelayCorrelationExhausted
10451        | ForwardingError::RouteOpenBuild(_)
10452        | ForwardingError::Poisoned => "forwarding_error",
10453    }
10454}
10455
10456fn response_version(frame: &Frame) -> u8 {
10457    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10458        frame.header.ver
10459    } else {
10460        PROTOCOL_VERSION
10461    }
10462}
10463
10464pub(crate) fn control_flags() -> Flags {
10465    Flags::new(false, Priority::Passive, false)
10466}
10467
10468/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10469/// channel. The target is the module (a client never saw the route), so this
10470/// takes the module path: delivered late rather than dropped when the module's
10471/// queue is momentarily full, and never closing its connection.
10472fn send_goodbye_target_best_effort(
10473    counters: &DaemonCounters,
10474    target: &GoodbyeTarget,
10475    context: &'static str,
10476) {
10477    let Ok(frame) = Frame::build_with_version(
10478        target.negotiated_ver,
10479        FrameType::Goodbye,
10480        control_flags(),
10481        target.channel,
10482        target.epoch,
10483        0,
10484        Vec::new(),
10485    ) else {
10486        return;
10487    };
10488    crate::forwarding::send_module_route_goodbye(
10489        counters,
10490        &target.sink,
10491        frame,
10492        target.module_id.as_deref(),
10493        context,
10494    );
10495}
10496
10497fn route_close_reason_for_opener(
10498    reason: RouteCloseReason,
10499    accepts_close_reasons: Option<&[String]>,
10500) -> RouteCloseReason {
10501    if reason == RouteCloseReason::AuthorityChanged
10502        && !accepts_close_reasons
10503            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10504    {
10505        // Older readers forbid reopening for unknown reasons. Reload already
10506        // permits reopening and, like an authority change, requires a new bind.
10507        RouteCloseReason::Reload
10508    } else {
10509        reason
10510    }
10511}
10512
10513pub(crate) fn send_route_control_pushes(
10514    forwarding: &ForwardingTable,
10515    routes: Vec<EndpointRoute>,
10516    push: ClientControlPush,
10517) {
10518    let reason = match &push {
10519        ClientControlPush::RouteClosing { reason, .. }
10520        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10521    };
10522    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10523    for route in routes {
10524        let recipient_reason =
10525            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10526        let target = route.goodbye_target;
10527        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10528            existing.connection_id == target.connection_id && *reason == recipient_reason
10529        }) {
10530            debug_assert_eq!(
10531                existing.negotiated_ver, target.negotiated_ver,
10532                "one connection cannot negotiate multiple frame versions"
10533            );
10534            if !channels.contains(&target.channel) {
10535                channels.push(target.channel);
10536            }
10537            continue;
10538        }
10539        let channel = target.channel;
10540        targets.push((target, recipient_reason, vec![channel]));
10541    }
10542    for (target, recipient_reason, mut channels) in targets {
10543        channels.sort_unstable();
10544        let mut push = push.clone();
10545        match &mut push {
10546            ClientControlPush::RouteClosing {
10547                channels: covered,
10548                reason,
10549                ..
10550            }
10551            | ClientControlPush::RouteClosed {
10552                channels: covered,
10553                reason,
10554                ..
10555            } => {
10556                *covered = channels;
10557                *reason = recipient_reason;
10558            }
10559        }
10560        let body = match serde_json::to_vec(&push) {
10561            Ok(body) => body,
10562            Err(err) => {
10563                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10564                continue;
10565            }
10566        };
10567        let frame = match Frame::build_with_version(
10568            target.negotiated_ver,
10569            FrameType::Push,
10570            control_flags(),
10571            0,
10572            0,
10573            0,
10574            body.clone(),
10575        ) {
10576            Ok(frame) => frame,
10577            Err(err) => {
10578                warn!(
10579                    route_channel = target.channel,
10580                    error = %err,
10581                    "failed to build route lifecycle control PUSH frame"
10582                );
10583                continue;
10584            }
10585        };
10586        if let Err(err) = target.sink.try_send(frame) {
10587            if target.close_on_delivery_failure() {
10588                warn!(
10589                    target_connection_id = target.connection_id.get(),
10590                    route_channel = target.channel,
10591                    error = %err,
10592                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10593                );
10594                let _ = forwarding.escalate_client_delivery_failure(
10595                    target.connection_id,
10596                    target.channel,
10597                    target.epoch,
10598                    CloseReason::new(
10599                        "route_lifecycle_push_delivery_failed",
10600                        format!(
10601                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10602                            target.channel
10603                        ),
10604                    ),
10605                    crate::forwarding::UndeliveredFrame {
10606                        module_id: target.module_id.as_deref(),
10607                        sink: &target.sink,
10608                    },
10609                );
10610            }
10611        }
10612    }
10613}
10614
10615#[cfg(test)]
10616mod tests {
10617    include!("control/agent_commands_tests.rs");
10618    include!("control/supervisor_health_vectors_tests.rs");
10619    include!("control/resource_revision_tests.rs");
10620    include!("control/route_open_recovery_tests.rs");
10621    mod router_audit {
10622        use super::*;
10623        include!("control/router_audit_tests.rs");
10624    }
10625    #[tokio::test]
10626    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10627        let registry = Arc::new(Registry::default());
10628        let handler = ControlHandler::new(registry);
10629        assert_eq!(
10630            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10631            None
10632        );
10633        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10634        hello_via_sink(
10635            &handler,
10636            &ctx,
10637            &mut rx,
10638            hello_frame("daemon", PROTOCOL_VERSION, 1),
10639        )
10640        .await;
10641        assert_eq!(
10642            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10643            Some("daemon".into())
10644        );
10645        assert_eq!(
10646            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10647            None
10648        );
10649        assert_eq!(
10650            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10651            None,
10652            "a registered module is not necessarily supervised"
10653        );
10654        assert_eq!(
10655            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10656            None,
10657            "aggregate provenance has no single target"
10658        );
10659        assert_eq!(
10660            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10661            None
10662        );
10663    }
10664
10665    mod peer_manifest {
10666        include!("peer_manifest_tests.rs");
10667    }
10668    mod catalog_declarations {
10669        include!("control/catalog_tests.rs");
10670    }
10671    mod activity_read {
10672        include!("activity_read_tests.rs");
10673    }
10674
10675    mod lifecycle_activity {
10676        include!("control_lifecycle_tests.rs");
10677    }
10678    #[cfg(unix)]
10679    #[tokio::test]
10680    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10681        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10682        let path = dir.join("subc.jsonc");
10683        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10684            "program":"/bin/sleep","args":["60"],"protocol":"none",
10685            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10686        }}}).to_string()).unwrap();
10687        let mut configured = crate::daemon_config::load(&path)
10688            .unwrap()
10689            .unwrap()
10690            .modules
10691            .pop()
10692            .unwrap();
10693        let registry = std::sync::Arc::new(crate::Registry::default());
10694        let handle = crate::SupervisorHandle::new();
10695        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10696            .with_handle(handle.clone());
10697        let module = supervisor
10698            .supervise_configured_with_health(
10699                configured.module_spec(),
10700                true,
10701                configured.health.clone(),
10702                None,
10703                configured.restart,
10704            )
10705            .unwrap();
10706        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10707        let before = module.status().unwrap().pid;
10708        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10709        configured.health.cadence = std::time::Duration::from_secs(3600);
10710        let health_only = handler
10711            .reconcile_supervised_modules(
10712                &supervisor,
10713                vec![configured.clone()],
10714                false,
10715                Principal::Direct,
10716            )
10717            .await
10718            .unwrap();
10719        assert!(
10720            health_only.0.changed_pending_reload.is_empty(),
10721            "health policy is already applied live"
10722        );
10723        assert_eq!(module.status().unwrap().pid, before);
10724        assert_eq!(
10725            module.configuration().unwrap().1.http,
10726            configured.health.http
10727        );
10728        configured.args = vec!["61".into()];
10729        let launch = handler
10730            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10731            .await
10732            .unwrap();
10733        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10734        assert_eq!(
10735            module.status().unwrap().pid,
10736            before,
10737            "a launch edit is stored until reload"
10738        );
10739        module.drain().await.unwrap();
10740    }
10741    use cortexkit_test_support::ScratchDir;
10742    use std::{
10743        collections::BTreeMap,
10744        fmt,
10745        path::PathBuf,
10746        sync::{Arc, Mutex},
10747        time::Duration,
10748    };
10749
10750    use serde_json::{json, Value};
10751    use subc_protocol::{
10752        manifest::{
10753            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10754            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10755        },
10756        session::HealthStatus,
10757        FrameType,
10758    };
10759
10760    use super::*;
10761    use crate::{
10762        forwarding::{DataRoute, DataRouteState},
10763        registry::ChannelState,
10764        router::FrameSink,
10765        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10766        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10767        RouteCtx, Router,
10768    };
10769    use tokio::{
10770        sync::mpsc,
10771        time::{sleep, Instant},
10772    };
10773    use tracing::{
10774        field::{Field, Visit},
10775        Event, Subscriber,
10776    };
10777    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10778
10779    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10780    ///
10781    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10782    /// is only populated for `tests/*.rs` integration test binaries -- this file
10783    /// compiles as part of the library target, which gets neither. The binary
10784    /// lives in the profile folder this test was built into,
10785    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10786    /// from the test's own path.
10787    ///
10788    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10789    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10790    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10791    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10792    /// `NotFound`, which reads as a broken test rather than an unbuilt
10793    /// dependency -- so state the cause and the remedy instead. Deliberately a
10794    /// panic and not a silent skip: a test that quietly passes when it could not
10795    /// run is worse than one that fails, because it reports health it never
10796    /// verified.
10797    fn fake_aft_stub_path() -> PathBuf {
10798        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10799        assert!(
10800            path.exists(),
10801            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10802             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10803            path.display()
10804        );
10805        path
10806    }
10807
10808    /// Whether clients retry `code` in place: the predicate itself, never a copy
10809    /// of its set. A copied list breaks silently when a code is added to or
10810    /// removed from the real one, and a stale copy here would let exactly the
10811    /// failure this test exists to catch pass.
10812    fn client_retries(code: &str) -> bool {
10813        subc_protocol::error_codes::is_retryable_route_open(code)
10814    }
10815
10816    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10817    /// of failure is worse than publishing none. A permanent fault dressed as
10818    /// retryable makes every client in the fleet retry forever against something
10819    /// that cannot recover; a transient fault dressed as permanent abandons work
10820    /// that would have succeeded.
10821    ///
10822    /// Asserting "a code exists" cannot catch either, because the string is free
10823    /// to say anything. This enumerates every variant and pins which side of the
10824    /// retry boundary it lands on, so a new variant must be classified here
10825    /// deliberately rather than inheriting whichever arm it was appended to.
10826    #[test]
10827    fn retryability_of_forwarding_codes_matches_the_failure() {
10828        // Transient by nature: the target is booting, reloading, or its endpoint
10829        // was swapped mid-flight. Retrying is how these resolve.
10830        let transient = [
10831            ForwardingError::NoModuleConnection,
10832            ForwardingError::ModuleReloading {
10833                module_id: "m".into(),
10834            },
10835            ForwardingError::StaleModuleEndpoint,
10836            ForwardingError::UnknownReservation {
10837                client_channel: 1,
10838                module_channel: 1,
10839            },
10840            ForwardingError::ConnectionClosing {
10841                connection_id: ConnectionId::new(1),
10842            },
10843            ForwardingError::ClientEgressClosed {
10844                connection_id: ConnectionId::new(1),
10845            },
10846            ForwardingError::ModuleEgressUnavailable {
10847                connection_id: ConnectionId::new(1),
10848            },
10849        ];
10850        for err in transient {
10851            let code = forwarding_error_code(&err);
10852            assert!(
10853                client_retries(code),
10854                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10855            );
10856        }
10857
10858        // Not fixed by retrying. Channel and correlation exhaustion need the
10859        // caller to close routes, and a poisoned lock is a daemon that cannot
10860        // recover at all — the worst thing to advertise as retryable, since every
10861        // client would storm a daemon that will never answer.
10862        let permanent = [
10863            ForwardingError::ConnectionRoleConflict {
10864                connection_id: ConnectionId::new(1),
10865            },
10866            ForwardingError::ClientRouteChannelExhausted {
10867                connection_id: ConnectionId::new(1),
10868            },
10869            ForwardingError::ModuleRouteChannelExhausted {
10870                endpoint: ModuleEndpointId {
10871                    connection_id: ConnectionId::new(1),
10872                    generation: 1,
10873                },
10874            },
10875            ForwardingError::RelayCorrelationExhausted,
10876            ForwardingError::RouteOpenBuild("x".into()),
10877            ForwardingError::Poisoned,
10878        ];
10879        for err in permanent {
10880            let code = forwarding_error_code(&err);
10881            assert!(
10882                !client_retries(code),
10883                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10884            );
10885        }
10886    }
10887
10888    /// The principal is the daemon's answer to "who is calling", and modules
10889    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10890    /// plexus gates connector invocation. So a stamp is an authorization input in
10891    /// another process, not a label — and both possible answers SUCCEED, which is
10892    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10893    /// first-party capability to something that never proved it; a supervised one
10894    /// stamped `Direct` silently strips a module of capability it is entitled to.
10895    ///
10896    /// Neither shows up in a test that only checks the bind succeeded. Before this
10897    /// test the only coverage was accidental —
10898    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
10899    /// stamped principal on its way past, so narrowing that wire-shape test to its
10900    /// stated subject would have deleted the last assertion on this value. It
10901    /// still asserts the stamp, which is now redundancy rather than the only
10902    /// guard: both fail under the same mutation, and this one names the reason.
10903    /// SCOPE: this handler's supervisor has spawned nothing, so
10904    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
10905    /// is unreachable here. Both assertions below are refusals, and a mutant that
10906    /// refuses everything would satisfy them.
10907    ///
10908    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
10909    /// spawns a supervised consumer, reads its live nonce, and asserts the module
10910    /// observed `principal.kind == "reserved"` carrying that module_id — verified
10911    /// at source rather than assumed, since a citation is a claim about another
10912    /// file and ages like one. Recorded because a harness that structurally
10913    /// cannot reach an arm reports "none" for that arm identically to one that
10914    /// covers it and found nothing.
10915    #[tokio::test]
10916    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
10917        let handler = ControlHandler::default();
10918        let frame =
10919            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
10920
10921        // Absent consumer_identity is the ordinary case: a human at a terminal, or
10922        // any process holding the connection file. Nothing was proved, so nothing
10923        // may be granted beyond the unattested floor.
10924        let stamped = handler
10925            .route_open_principal(ConnectionId::new(1), &frame, None)
10926            .unwrap()
10927            .unwrap();
10928        assert_eq!(
10929            stamped,
10930            Principal::Direct,
10931            "a caller that proved nothing must not be stamped as a supervised module"
10932        );
10933
10934        // A claimed module_id with a nonce no supervised child was given is a
10935        // forgery attempt, not a weaker caller: it must be REFUSED rather than
10936        // quietly demoted to Direct, or an impersonation attempt looks identical
10937        // to an ordinary unattested connection.
10938        let forged = handler
10939            .route_open_principal(
10940                ConnectionId::new(1),
10941                &frame,
10942                Some(ConsumerIdentity {
10943                    module_id: "aft".to_string(),
10944                    launch_nonce: "not-a-real-nonce".to_string(),
10945                }),
10946            )
10947            .unwrap();
10948        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
10949        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
10950    }
10951
10952    /// The test above hands `route_open_principal` an identity it built itself,
10953    /// which proves the stamping rule and nothing about where the identity comes
10954    /// from. The real producer is a wire body, and the two are joined by a serde
10955    /// field name that nothing else asserts.
10956    ///
10957    /// That join fails quietly in one specific way: an unrecognised key is simply
10958    /// absent after parsing, so a renamed or misspelled `consumer_identity`
10959    /// yields `None` and every supervised module silently drops to `Direct`.
10960    /// Capability-wise that is the safe direction, but it surfaces far from its
10961    /// cause — as a module mysteriously refused bash — and it would pass every
10962    /// test that builds its own input.
10963    ///
10964    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
10965    /// would break every client the moment the daemon gains a field, trading a
10966    /// quiet demotion for a hard refusal on additive change. Asserting the join
10967    /// instead means a rename breaks a test here rather than the fleet.
10968    #[test]
10969    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
10970        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"}}"#;
10971        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
10972        let ClientControlRequest::RouteOpen {
10973            consumer_identity, ..
10974        } = parsed
10975        else {
10976            panic!("route.open body must parse as RouteOpen");
10977        };
10978        assert_eq!(
10979            consumer_identity,
10980            Some(ConsumerIdentity {
10981                module_id: "aft".to_string(),
10982                launch_nonce: "n".to_string(),
10983            }),
10984            "the wire field name must reach the value route_open_principal reads"
10985        );
10986    }
10987
10988    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
10989        ModuleManifest::builder(module_id, "0.1.0")
10990            .protocol_ver(protocol_ver)
10991            .provides(vec![ProviderRole::ToolProvider {
10992                tools: vec![Tool {
10993                    name: "read".to_string(),
10994                    description: None,
10995                    execution_mode: ExecutionMode::Pure,
10996                    schema: json!({"type": "object"}),
10997                }],
10998                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
10999                concurrency: Concurrency::ModuleManaged,
11000                emits_push: true,
11001                sub_supervises: true,
11002            }])
11003            .build()
11004    }
11005
11006    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11007        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11008    }
11009
11010    fn hello_frame_with_control_ops(
11011        module_id: &str,
11012        protocol_ver: u8,
11013        corr: u64,
11014        control_ops: Option<Vec<String>>,
11015    ) -> Frame {
11016        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11017    }
11018
11019    fn hello_frame_with_nonce(
11020        module_id: &str,
11021        protocol_ver: u8,
11022        corr: u64,
11023        launch_nonce: Option<&str>,
11024    ) -> Frame {
11025        hello_frame_full(
11026            module_id,
11027            protocol_ver,
11028            corr,
11029            None,
11030            launch_nonce.map(ToOwned::to_owned),
11031        )
11032    }
11033
11034    fn hello_frame_full(
11035        module_id: &str,
11036        protocol_ver: u8,
11037        corr: u64,
11038        control_ops: Option<Vec<String>>,
11039        launch_nonce: Option<String>,
11040    ) -> Frame {
11041        let body = serde_json::to_vec(&ModuleHelloBody {
11042            manifest: manifest(module_id, protocol_ver),
11043            protocol_ver,
11044            control_ops,
11045            launch_nonce,
11046        })
11047        .unwrap();
11048        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11049    }
11050
11051    fn hello_frame_with_rich_ui(
11052        module_id: &str,
11053        protocol_ver: u8,
11054        corr: u64,
11055        launch_nonce: Option<&str>,
11056        rich_ui: Value,
11057    ) -> Frame {
11058        let mut body = serde_json::to_value(ModuleHelloBody {
11059            manifest: manifest(module_id, protocol_ver),
11060            protocol_ver,
11061            control_ops: None,
11062            launch_nonce: launch_nonce.map(str::to_string),
11063        })
11064        .unwrap();
11065        body["manifest"]["rich_ui"] = rich_ui;
11066        Frame::build(
11067            FrameType::Hello,
11068            control_flags(),
11069            0,
11070            0,
11071            corr,
11072            serde_json::to_vec(&body).unwrap(),
11073        )
11074        .unwrap()
11075    }
11076
11077    fn non_routable_hello_frame_with_control_ops(
11078        module_id: &str,
11079        corr: u64,
11080        control_ops: Option<Vec<String>>,
11081    ) -> Frame {
11082        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11083        manifest.provides.clear();
11084        let body = serde_json::to_vec(&ModuleHelloBody {
11085            manifest,
11086            protocol_ver: PROTOCOL_VERSION,
11087            control_ops,
11088            launch_nonce: None,
11089        })
11090        .unwrap();
11091        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11092    }
11093
11094    fn capability_grammar_hello_frame(
11095        capabilities: Value,
11096        runtime_computed: Option<Value>,
11097        corr: u64,
11098    ) -> Frame {
11099        let mut body = serde_json::to_value(ModuleHelloBody {
11100            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11101            protocol_ver: PROTOCOL_VERSION,
11102            control_ops: None,
11103            launch_nonce: None,
11104        })
11105        .expect("HELLO body serializes");
11106        body["manifest"]["capabilities"] = capabilities;
11107        if let Some(runtime_computed) = runtime_computed {
11108            body["runtime_computed"] = runtime_computed;
11109        }
11110        Frame::build(
11111            FrameType::Hello,
11112            control_flags(),
11113            0,
11114            0,
11115            corr,
11116            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11117        )
11118        .expect("HELLO frame builds")
11119    }
11120
11121    fn channel_request(channel: u16, corr: u64) -> Frame {
11122        Frame::build(
11123            FrameType::Request,
11124            Flags::new(true, Priority::Interactive, false),
11125            channel,
11126            0,
11127            corr,
11128            b"opaque".to_vec(),
11129        )
11130        .unwrap()
11131    }
11132
11133    fn route_ctx(
11134        connection_id: ConnectionId,
11135    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11136        let (tx, rx) = mpsc::channel(8);
11137        (
11138            RouteCtx {
11139                connection_id,
11140                egress: FrameSink::new(tx),
11141            },
11142            rx,
11143        )
11144    }
11145
11146    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11147        serde_json::from_slice(&frame.body).unwrap()
11148    }
11149
11150    /// Register a module over a connection that has a sink and return the
11151    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11152    /// module's own sink rather than returning it as a reply, so the ack is
11153    /// taken off `rx` here and whatever the test reads next is what followed it.
11154    async fn hello_via_sink(
11155        handler: &ControlHandler,
11156        ctx: &RouteCtx,
11157        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11158        hello: Frame,
11159    ) -> Frame {
11160        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11161        assert!(
11162            replies.is_empty(),
11163            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11164        );
11165        let ack = rx
11166            .try_recv()
11167            .expect("HELLO_ACK is queued on the module sink")
11168            .frame;
11169        assert_eq!(ack.header.ty, FrameType::HelloAck);
11170        ack
11171    }
11172
11173    fn parse_error(frame: &Frame) -> Value {
11174        serde_json::from_slice(&frame.body).unwrap()
11175    }
11176
11177    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11178        serde_json::from_slice(&frame.body).unwrap()
11179    }
11180
11181    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11182        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11183            route_channel,
11184            route_epoch: 0,
11185            kind,
11186        })
11187        .unwrap();
11188        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11189    }
11190
11191    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11192        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11193            module_id: module_id.to_string(),
11194        })
11195        .unwrap();
11196        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11197    }
11198
11199    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11200        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11201    }
11202
11203    // Exercise retired opener fields without putting them back in BindIdentity.
11204    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11205        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11206        let mut frame = route_open_frame(corr, module_id, root);
11207        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11208        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11209        frame.body = serde_json::to_vec(&body).unwrap();
11210        frame
11211    }
11212
11213    fn route_open_frame_with_consumer_capabilities(
11214        corr: u64,
11215        module_id: &str,
11216        _project_root: ScratchDir,
11217        consumer_capabilities: Option<Vec<String>>,
11218    ) -> Frame {
11219        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11220            busy_refusals: None,
11221            target: RouteTarget::ToolProvider {
11222                module_id: module_id.to_string(),
11223            },
11224            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11225            consumer_identity: None,
11226            consumer_capabilities,
11227            role_versions: None,
11228            admission_facts: None,
11229            scope: None,
11230        })
11231        .unwrap();
11232        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11233    }
11234
11235    fn route_open_frame_with_role_versions(
11236        corr: u64,
11237        module_id: &str,
11238        _project_root: ScratchDir,
11239        role_versions: Option<BTreeMap<String, String>>,
11240    ) -> Frame {
11241        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11242            busy_refusals: None,
11243            target: RouteTarget::ToolProvider {
11244                module_id: module_id.to_string(),
11245            },
11246            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11247            consumer_identity: None,
11248            consumer_capabilities: None,
11249            role_versions,
11250            admission_facts: None,
11251            scope: None,
11252        })
11253        .unwrap();
11254        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11255    }
11256
11257    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11258        entries
11259            .iter()
11260            .map(|(role, version)| (role.to_string(), version.to_string()))
11261            .collect()
11262    }
11263
11264    fn route_open_frame_with_admission_facts(
11265        corr: u64,
11266        module_id: &str,
11267        _project_root: ScratchDir,
11268        consumer_identity: Option<subc_control::ConsumerIdentity>,
11269        facts: Option<Value>,
11270    ) -> Frame {
11271        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11272            busy_refusals: None,
11273            target: RouteTarget::ToolProvider {
11274                module_id: module_id.to_string(),
11275            },
11276            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11277            consumer_identity,
11278            consumer_capabilities: None,
11279            role_versions: None,
11280            admission_facts: facts,
11281            scope: None,
11282        })
11283        .unwrap();
11284        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11285    }
11286
11287    #[derive(Clone, Default)]
11288    struct EventCapture {
11289        events: Arc<Mutex<Vec<CapturedEvent>>>,
11290    }
11291
11292    #[derive(Clone, Debug)]
11293    struct CapturedEvent {
11294        target: String,
11295        level: tracing::Level,
11296        fields: BTreeMap<String, String>,
11297    }
11298
11299    impl EventCapture {
11300        fn events(&self) -> Vec<CapturedEvent> {
11301            self.events.lock().unwrap().clone()
11302        }
11303    }
11304
11305    impl<S> Layer<S> for EventCapture
11306    where
11307        S: Subscriber,
11308    {
11309        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11310            let mut visitor = EventFieldVisitor::default();
11311            event.record(&mut visitor);
11312            self.events.lock().unwrap().push(CapturedEvent {
11313                target: event.metadata().target().to_string(),
11314                level: *event.metadata().level(),
11315                fields: visitor.fields,
11316            });
11317        }
11318    }
11319
11320    #[derive(Default)]
11321    struct EventFieldVisitor {
11322        fields: BTreeMap<String, String>,
11323    }
11324
11325    impl Visit for EventFieldVisitor {
11326        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11327            self.fields
11328                .insert(field.name().to_string(), format!("{value:?}"));
11329        }
11330    }
11331
11332    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11333        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11334            status,
11335            detail: Some("warming".to_string()),
11336            metrics: Some(json!({"queue_depth": 3})),
11337        })
11338        .unwrap();
11339        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11340    }
11341
11342    fn route_bind_ack(corr: u64) -> Frame {
11343        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11344        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11345    }
11346
11347    fn unique_project_root(label: &str) -> ScratchDir {
11348        ScratchDir::new(label)
11349    }
11350
11351    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11352        match parse_route_poll(frame) {
11353            ClientControlResponse::RoutePoll {
11354                status: None,
11355                live: Some(live),
11356                ..
11357            } => assert_eq!(live, expected_live),
11358            other => panic!("unexpected route.poll response: {other:?}"),
11359        }
11360    }
11361
11362    fn bind_liveness_route(
11363        registry: &Registry,
11364        forwarding: &ForwardingTable,
11365        module_id: &str,
11366    ) -> (RouteCtx, u16, u32) {
11367        let module_connection = ConnectionId::new(101);
11368        let client_connection = ConnectionId::new(202);
11369        let registration = registry
11370            .register_with_control_ops(
11371                manifest(module_id, PROTOCOL_VERSION),
11372                PROTOCOL_VERSION,
11373                module_connection,
11374                module_baseline_control_ops(),
11375            )
11376            .unwrap();
11377        let (module_tx, _module_rx) = mpsc::channel(8);
11378        let endpoint = forwarding
11379            .register_module_connection(
11380                module_connection,
11381                module_id.to_string(),
11382                PROTOCOL_VERSION,
11383                manifest_concurrency(&registration.manifest),
11384                FrameSink::new(module_tx),
11385            )
11386            .unwrap();
11387        let (client_ctx, _client_rx) = route_ctx(client_connection);
11388        let pending = forwarding
11389            .begin_route_bind_relay_for_test(
11390                client_connection,
11391                client_ctx.egress.clone(),
11392                1,
11393                module_id,
11394            )
11395            .unwrap();
11396        assert_eq!(pending.endpoint, endpoint);
11397        let route_channel = pending.client_channel;
11398        let route_epoch = pending.client_epoch;
11399        forwarding
11400            .complete_pending_relay(
11401                module_connection,
11402                pending.corr,
11403                RouteBindRelayOutcome::Accepted,
11404            )
11405            .unwrap();
11406        (client_ctx, route_channel, route_epoch)
11407    }
11408
11409    struct FakeProcessLiveness {
11410        live: Option<bool>,
11411    }
11412
11413    impl ModuleProcessLiveness for FakeProcessLiveness {
11414        fn process_live(&self, _module_id: &str) -> Option<bool> {
11415            self.live
11416        }
11417    }
11418
11419    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11420    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11421    {
11422        let registry = Arc::new(Registry::default());
11423        let supervisor_handle = SupervisorHandle::new();
11424        let supervisor = Supervisor::new_for_test(
11425            Arc::clone(&registry),
11426            RestartPolicy::new(1, Duration::from_millis(10)),
11427        )
11428        .with_handle(supervisor_handle.clone());
11429        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11430        let module = supervisor
11431            .spawn(ModuleSpec {
11432                script: None,
11433                carry_containment: false,
11434                module_id: "stderr-tail-wire".to_string(),
11435                program: fake_aft_stub_path(),
11436                args: Vec::new(),
11437                env: vec![
11438                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11439                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11440                ],
11441                reserved: false,
11442                reserved_prefixes: Vec::new(),
11443                protocol: ModuleProtocol::Subc,
11444                overlap: Default::default(),
11445            })
11446            .unwrap();
11447
11448        let deadline = Instant::now() + Duration::from_secs(5);
11449        loop {
11450            let tail = module.stderr_tail(None, None);
11451            if tail
11452                .entries
11453                .iter()
11454                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11455                && tail.entries.iter().any(|entry| {
11456                    matches!(
11457                        entry,
11458                        TailEntry::Line {
11459                            truncated: true,
11460                            ..
11461                        }
11462                    )
11463                })
11464            {
11465                break;
11466            }
11467            assert!(
11468                Instant::now() < deadline,
11469                "module did not produce a truncated line and restart boundary: {tail:?}"
11470            );
11471            sleep(Duration::from_millis(10)).await;
11472        }
11473
11474        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11475        let request = ClientControlRequest::SupervisorStderrTail {
11476            module_id: "stderr-tail-wire".to_string(),
11477            max_lines: None,
11478            max_bytes: None,
11479        };
11480        let frame = Frame::build(
11481            FrameType::Request,
11482            control_flags(),
11483            0,
11484            0,
11485            1,
11486            serde_json::to_vec(&request).unwrap(),
11487        )
11488        .unwrap();
11489        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11490        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11491        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11492            serde_json::from_slice(&responses[0].body).unwrap()
11493        else {
11494            panic!("expected supervisor.stderr_tail response");
11495        };
11496
11497        assert!(
11498            tail.entries
11499                .iter()
11500                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11501            "the control response lost the restart boundary"
11502        );
11503        let Some(StderrTailEntry::Line {
11504            text,
11505            truncated,
11506            at_ms,
11507        }) = tail.entries.iter().find(|entry| {
11508            matches!(
11509                entry,
11510                StderrTailEntry::Line {
11511                    truncated: true,
11512                    ..
11513                }
11514            )
11515        })
11516        else {
11517            panic!("the control response lost the truncated line");
11518        };
11519        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11520        assert!(*truncated);
11521        assert!(
11522            at_ms.is_some(),
11523            "the control response lost the line's capture time"
11524        );
11525    }
11526
11527    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11528    /// read done on the worker thread would stall every other task until it
11529    /// finished; the read must run off the worker so this test's own task keeps
11530    /// running while the read is paused.
11531    #[tokio::test(flavor = "current_thread")]
11532    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11533        let dir = ScratchDir::new("terminals-off-worker");
11534        let journal_path = dir.join("terminals.jsonl");
11535        let registry = Arc::new(Registry::default());
11536        let supervisor_handle = SupervisorHandle::new();
11537        let supervisor =
11538            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11539                .with_handle(supervisor_handle.clone())
11540                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11541        let module = supervisor
11542            .spawn(ModuleSpec {
11543                script: None,
11544                carry_containment: false,
11545                module_id: "terminal-off-worker".to_string(),
11546                program: fake_aft_stub_path(),
11547                args: Vec::new(),
11548                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11549                reserved: false,
11550                reserved_prefixes: Vec::new(),
11551                protocol: ModuleProtocol::Subc,
11552                overlap: Default::default(),
11553            })
11554            .unwrap();
11555        let deadline = Instant::now() + Duration::from_secs(5);
11556        while module.terminal_history().entries.len() != 2 {
11557            assert!(Instant::now() < deadline, "module did not record two exits");
11558            sleep(Duration::from_millis(10)).await;
11559        }
11560
11561        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11562        let handler =
11563            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11564        let frame = Frame::build(
11565            FrameType::Request,
11566            control_flags(),
11567            0,
11568            0,
11569            1,
11570            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11571                module_id: "terminal-off-worker".to_string(),
11572            })
11573            .unwrap(),
11574        )
11575        .unwrap();
11576        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11577        let spawned_at = std::time::Instant::now();
11578        let read = tokio::spawn({
11579            let handler = Arc::clone(&handler);
11580            async move { handler.handle_control_frame(&ctx, frame).await }
11581        });
11582        // Waiting for the pause from a blocking thread keeps this task pending,
11583        // so the runtime's single worker is free to run the read task.
11584        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11585            .await
11586            .unwrap()
11587            .expect("the history read reached its pause");
11588        let elapsed = spawned_at.elapsed();
11589        assert!(
11590            elapsed < Duration::from_secs(2) && !read.is_finished(),
11591            "this task could not run while the history read was paused \
11592             (resumed after {elapsed:?}, read finished: {})",
11593            read.is_finished()
11594        );
11595
11596        drop(release);
11597        let responses = read.await.unwrap().unwrap();
11598        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11599        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11600            panic!("expected supervisor.terminals response");
11601        };
11602        assert_eq!(terminals.entries.len(), 2);
11603        assert_eq!(terminals.journal_skipped_lines, 0);
11604        assert_eq!(terminals.journal_read_errors, 0);
11605    }
11606
11607    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11608    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11609        let registry = Arc::new(Registry::default());
11610        let supervisor_handle = SupervisorHandle::new();
11611        let supervisor =
11612            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11613                .with_handle(supervisor_handle.clone());
11614        let module = supervisor
11615            .spawn(ModuleSpec {
11616                script: None,
11617                carry_containment: false,
11618                module_id: "terminal-golden".to_string(),
11619                program: fake_aft_stub_path(),
11620                args: Vec::new(),
11621                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11622                reserved: false,
11623                reserved_prefixes: Vec::new(),
11624                protocol: ModuleProtocol::Subc,
11625                overlap: Default::default(),
11626            })
11627            .unwrap();
11628
11629        let deadline = Instant::now() + Duration::from_secs(5);
11630        while module.terminal_history().entries.len() != 2 {
11631            assert!(
11632                Instant::now() < deadline,
11633                "module did not retain two terminal exits: {:?}",
11634                module.terminal_history()
11635            );
11636            sleep(Duration::from_millis(10)).await;
11637        }
11638
11639        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11640        let request = ClientControlRequest::SupervisorTerminals {
11641            module_id: "terminal-golden".to_string(),
11642        };
11643        let frame = Frame::build(
11644            FrameType::Request,
11645            control_flags(),
11646            0,
11647            0,
11648            1,
11649            serde_json::to_vec(&request).unwrap(),
11650        )
11651        .unwrap();
11652        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11653        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11654        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11655        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11656            panic!("expected supervisor.terminals response");
11657        };
11658        assert_eq!(terminals.entries.len(), 2);
11659        assert_eq!(terminals.dropped, 0);
11660
11661        let mut rendered = serde_json::to_value(response).unwrap();
11662        // Wall-clock fields are the observation contract, but not stable fixture
11663        // bytes; normalize only them after the real handler has shaped the response.
11664        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11665        for (index, entry) in rendered["entries"]
11666            .as_array_mut()
11667            .expect("terminal response entries array")
11668            .iter_mut()
11669            .enumerate()
11670        {
11671            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11672        }
11673
11674        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11675            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11676        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11677        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11678            std::fs::write(&golden_path, &serialized).unwrap();
11679        }
11680        let expected: Value =
11681            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11682        assert_eq!(rendered, expected);
11683    }
11684
11685    #[test]
11686    fn hello_registers_manifest_and_returns_ack() {
11687        let registry = Arc::new(Registry::default());
11688        let handler = ControlHandler::new(Arc::clone(&registry));
11689        let conn = ConnectionId::new(1);
11690
11691        let responses = handler
11692            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11693            .unwrap();
11694
11695        assert_eq!(responses.len(), 1);
11696        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11697        assert_eq!(responses[0].header.channel, 0);
11698        assert_eq!(responses[0].header.corr, 7);
11699        let ack = parse_ack(&responses[0]);
11700        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11701        assert!(ack
11702            .subc_capabilities
11703            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11704        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11705        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11706        assert!(ack
11707            .subc_ops
11708            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11709        assert!(ack
11710            .subc_ops
11711            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11712        assert!(ack
11713            .subc_ops
11714            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11715
11716        let registration = registry.get_module("aft").unwrap().unwrap();
11717        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11718        assert_eq!(registration.state, ChannelState::Active);
11719        assert_eq!(registration.connection_id, conn);
11720        assert_eq!(registration.control_ops, module_baseline_control_ops());
11721        assert!(registration.manifest.display_name.is_none());
11722    }
11723
11724    #[test]
11725    fn hello_display_name_refuses_invalid_manifest_by_field() {
11726        let registry = Arc::new(Registry::default());
11727        let handler = ControlHandler::new(Arc::clone(&registry));
11728        for (index, invalid) in [
11729            json!(""),
11730            json!("a".repeat(41)),
11731            json!(" Routing"),
11732            json!("a\nb"),
11733            json!("a\u{202e}b"),
11734            json!(7),
11735        ]
11736        .into_iter()
11737        .enumerate()
11738        {
11739            let module_id = format!("bad-display-name-{index}");
11740            let mut body = serde_json::to_value(ModuleHelloBody {
11741                manifest: manifest(&module_id, PROTOCOL_VERSION),
11742                protocol_ver: PROTOCOL_VERSION,
11743                control_ops: None,
11744                launch_nonce: None,
11745            })
11746            .unwrap();
11747            body["manifest"]["display_name"] = invalid;
11748            let hello = Frame::build(
11749                FrameType::Hello,
11750                control_flags(),
11751                0,
11752                0,
11753                7,
11754                serde_json::to_vec(&body).unwrap(),
11755            )
11756            .unwrap();
11757            let response = handler
11758                .handle_control(ConnectionId::new(100 + index as u64), hello)
11759                .unwrap();
11760            assert_eq!(response[0].header.ty, FrameType::Error);
11761            let error = parse_error(&response[0]);
11762            assert_eq!(error["code"], "invalid_manifest");
11763            assert!(error["message"].as_str().unwrap().contains("display_name"));
11764            assert!(registry.get_module(&module_id).unwrap().is_none());
11765        }
11766    }
11767
11768    #[test]
11769    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11770        let invalid_identifiers = [
11771            ("case_change", "credentials-Provider/v1"),
11772            ("leading_zero", "credentials-provider/v01"),
11773            ("trailing_hyphen", "credentials-provider-/v1"),
11774            ("consecutive_hyphens", "credentials--provider/v1"),
11775            ("uppercase", "Credentials-provider/v1"),
11776            ("missing_v", "credentials-provider/1"),
11777            ("whitespace", "credentials provider/v1"),
11778            ("zero_version", "credentials-provider/v0"),
11779            ("out_of_range_version", "credentials-provider/v4294967296"),
11780            (
11781                "overlength_name",
11782                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11783            ),
11784        ];
11785        let mut cases = invalid_identifiers
11786            .into_iter()
11787            .map(|(name, identifier)| {
11788                (
11789                    format!("identifier_{name}"),
11790                    "capabilities.provides[0]".to_string(),
11791                    identifier.to_string(),
11792                    json!({ "provides": [identifier] }),
11793                    None,
11794                )
11795            })
11796            .collect::<Vec<_>>();
11797        cases.extend([
11798            (
11799                "unknown_need".to_string(),
11800                "capabilities.requires[0].need".to_string(),
11801                "deferred".to_string(),
11802                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11803                None,
11804            ),
11805            (
11806                "duplicate_provides".to_string(),
11807                "capabilities.provides[1]".to_string(),
11808                "credentials-provider/v1".to_string(),
11809                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11810                None,
11811            ),
11812            (
11813                "duplicate_must_never_reach".to_string(),
11814                "capabilities.must_never_reach[1]".to_string(),
11815                "credentials-provider/v1".to_string(),
11816                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11817                None,
11818            ),
11819            (
11820                "duplicate_requires_same_need".to_string(),
11821                "capabilities.requires[1]".to_string(),
11822                "credentials-provider/v1".to_string(),
11823                json!({ "requires": [
11824                    { "capability": "credentials-provider/v1", "need": "required" },
11825                    { "capability": "credentials-provider/v1", "need": "required" }
11826                ] }),
11827                None,
11828            ),
11829            (
11830                "duplicate_requires_conflicting_need".to_string(),
11831                "capabilities.requires[1]".to_string(),
11832                "credentials-provider/v1".to_string(),
11833                json!({ "requires": [
11834                    { "capability": "credentials-provider/v1", "need": "required" },
11835                    { "capability": "credentials-provider/v1", "need": "optional" }
11836                ] }),
11837                None,
11838            ),
11839            (
11840                "capabilities_root_pointer".to_string(),
11841                "runtime_computed[0]".to_string(),
11842                "/capabilities".to_string(),
11843                json!({}),
11844                Some(json!(["/capabilities"])),
11845            ),
11846            (
11847                "capabilities_descendant_pointer".to_string(),
11848                "runtime_computed[0]".to_string(),
11849                "/capabilities/provides".to_string(),
11850                json!({}),
11851                Some(json!(["/capabilities/provides"])),
11852            ),
11853            (
11854                "malformed_pointer_without_leading_slash".to_string(),
11855                "runtime_computed[0]".to_string(),
11856                "capabilities".to_string(),
11857                json!({}),
11858                Some(json!(["capabilities"])),
11859            ),
11860            (
11861                "malformed_pointer_escape".to_string(),
11862                "runtime_computed[0]".to_string(),
11863                "/roles/~2/tools".to_string(),
11864                json!({}),
11865                Some(json!(["/roles/~2/tools"])),
11866            ),
11867            (
11868                "unknown_capabilities_field".to_string(),
11869                "capabilities.future".to_string(),
11870                "<array>".to_string(),
11871                json!({ "future": [] }),
11872                None,
11873            ),
11874        ]);
11875
11876        for (index, (name, field, value, capabilities, runtime_computed)) in
11877            cases.into_iter().enumerate()
11878        {
11879            let registry = Arc::new(Registry::default());
11880            let handler = ControlHandler::new(Arc::clone(&registry));
11881            let response = handler
11882                .handle_control(
11883                    ConnectionId::new((index + 1) as u64),
11884                    capability_grammar_hello_frame(
11885                        capabilities,
11886                        runtime_computed,
11887                        index as u64 + 1,
11888                    ),
11889                )
11890                .expect("invalid HELLO returns a refusal");
11891
11892            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11893            let error = parse_error(&response[0]);
11894            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11895            let message = error["message"]
11896                .as_str()
11897                .expect("error message is a string");
11898            assert!(
11899                message.contains(&field),
11900                "{name}: field missing from {message}"
11901            );
11902            assert!(
11903                message.contains(&value),
11904                "{name}: value missing from {message}"
11905            );
11906            assert_eq!(
11907                registry
11908                    .active_registration_count()
11909                    .expect("registry reads"),
11910                0,
11911                "{name}: refused HELLO must not create a catalog entry"
11912            );
11913        }
11914    }
11915
11916    #[test]
11917    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
11918        let registry = Arc::new(Registry::default());
11919        let handler = ControlHandler::new(Arc::clone(&registry));
11920        let capabilities = json!({
11921            "provides": ["credentials-provider/v1"],
11922            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
11923            "must_never_reach": ["federation-transport/v1"]
11924        });
11925        let response = handler
11926            .handle_control(
11927                ConnectionId::new(99),
11928                capability_grammar_hello_frame(
11929                    capabilities.clone(),
11930                    Some(json!(["/roles/0/tools"])),
11931                    99,
11932                ),
11933            )
11934            .expect("valid HELLO registers");
11935        assert_eq!(response[0].header.ty, FrameType::HelloAck);
11936
11937        let request = Frame::build(
11938            FrameType::Request,
11939            control_flags(),
11940            0,
11941            0,
11942            100,
11943            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
11944                .expect("catalog request serializes"),
11945        )
11946        .expect("catalog request frame builds");
11947        let response = handler
11948            .handle_catalog_list(request, None)
11949            .expect("catalog list succeeds");
11950        let ClientControlResponse::CatalogList { modules, .. } =
11951            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
11952        else {
11953            panic!("catalog request must return catalog.list");
11954        };
11955        assert_eq!(modules.len(), 1);
11956        assert_eq!(
11957            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
11958            capabilities
11959        );
11960    }
11961
11962    #[test]
11963    fn catalog_list_mirrors_management_operation_description() {
11964        let registry = Arc::new(Registry::default());
11965        let handler = ControlHandler::new(Arc::clone(&registry));
11966        let description = "List managed records and return their identifiers and metadata.";
11967        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
11968        manifest.provides = vec![ProviderRole::ManagementSurface {
11969            operations: vec![ManagementOperation {
11970                name: "records.list".to_string(),
11971                kind: ManagementOperationKind::Query,
11972                description: Some(description.to_string()),
11973            }],
11974            config_schema: json!({"type": "object"}),
11975            observability: vec![ObservabilitySurface {
11976                name: "records.stats".to_string(),
11977                kind: ObservabilityKind::Snapshot,
11978            }],
11979            identity_scope: vec![IdentityScope::Project],
11980            concurrency: Concurrency::ModuleManaged,
11981        }];
11982        registry
11983            .register_with_control_ops(
11984                manifest,
11985                PROTOCOL_VERSION,
11986                ConnectionId::new(99),
11987                Vec::new(),
11988            )
11989            .expect("described management manifest registers");
11990
11991        let request = Frame::build(
11992            FrameType::Request,
11993            control_flags(),
11994            0,
11995            0,
11996            100,
11997            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
11998                .expect("catalog request serializes"),
11999        )
12000        .expect("catalog request frame builds");
12001        let response = handler
12002            .handle_catalog_list(request, None)
12003            .expect("catalog list succeeds");
12004        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12005        assert_eq!(
12006            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12007            "catalog.list must preserve the declared operation description verbatim"
12008        );
12009    }
12010
12011    #[test]
12012    fn catalog_list_mirrors_registered_operation_delivery() {
12013        let registry = Arc::new(Registry::default());
12014        let handler = ControlHandler::new(Arc::clone(&registry));
12015        let delivery =
12016            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12017        let mut body = serde_json::to_value(ModuleHelloBody {
12018            manifest: manifest("watch-management", PROTOCOL_VERSION),
12019            protocol_ver: PROTOCOL_VERSION,
12020            control_ops: None,
12021            launch_nonce: None,
12022        })
12023        .unwrap();
12024        body["manifest"]["provides"] = json!([{
12025            "role": "management_surface",
12026            "operations": [
12027                {"name": "status", "kind": "query"},
12028                {"name": "future", "kind": "query"},
12029                {"name": "reset", "kind": "mutate"}
12030            ],
12031            "config_schema": {}, "observability": [], "identity_scope": []
12032        }]);
12033        body["manifest"]["operation_delivery"] = delivery.clone();
12034        let hello = Frame::build(
12035            FrameType::Hello,
12036            control_flags(),
12037            0,
12038            0,
12039            99,
12040            serde_json::to_vec(&body).unwrap(),
12041        )
12042        .unwrap();
12043        let response = handler
12044            .handle_control(ConnectionId::new(99), hello)
12045            .unwrap();
12046        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12047
12048        let (_, registrations) = registry.list_modules().unwrap();
12049        let registered = &registrations[0].manifest;
12050        assert!(registered.is_watch_operation("status"));
12051        assert!(!registered.is_watch_operation("future"));
12052        assert!(!registered.is_watch_operation("reset"));
12053        assert!(!registered.is_watch_operation("missing"));
12054
12055        let request = Frame::build(
12056            FrameType::Request,
12057            control_flags(),
12058            0,
12059            0,
12060            100,
12061            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12062        )
12063        .unwrap();
12064        let response = handler.handle_catalog_list(request, None).unwrap();
12065        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12066        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12067        let ClientControlResponse::CatalogList { modules, .. } =
12068            serde_json::from_slice(&response[0].body).unwrap()
12069        else {
12070            panic!("expected catalog.list");
12071        };
12072        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12073    }
12074
12075    #[test]
12076    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12077        let registry = Arc::new(Registry::default());
12078        let supervisor = SupervisorHandle::new();
12079        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12080        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12081        let descriptor = json!({
12082            "schema": "ckios.richui.manifest/1",
12083            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12084            "bytes": 4096,
12085            "chunks": 4
12086        });
12087        let connection = ConnectionId::new(201);
12088        let hello = handler
12089            .handle_control(
12090                connection,
12091                hello_frame_with_rich_ui(
12092                    "vault",
12093                    PROTOCOL_VERSION,
12094                    201,
12095                    Some("the-real-nonce"),
12096                    descriptor.clone(),
12097                ),
12098            )
12099            .unwrap();
12100        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12101
12102        let request =
12103            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12104        let provides = registry
12105            .get_module_by_connection(connection)
12106            .unwrap()
12107            .unwrap()
12108            .manifest
12109            .provides;
12110        handler
12111            .handle_catalog_update(connection, request, provides, None, Some(false))
12112            .unwrap();
12113
12114        let request = Frame::build(
12115            FrameType::Request,
12116            control_flags(),
12117            0,
12118            0,
12119            203,
12120            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12121        )
12122        .unwrap();
12123        let response = handler.handle_catalog_list(request, None).unwrap();
12124        let ClientControlResponse::CatalogList { modules, .. } =
12125            serde_json::from_slice(&response[0].body).unwrap()
12126        else {
12127            panic!("expected catalog.list");
12128        };
12129        assert_eq!(
12130            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12131            descriptor
12132        );
12133        assert!(modules[0].nonce_verified);
12134    }
12135
12136    fn hello_with_role_declarations(declarations: Value) -> Frame {
12137        let mut body = serde_json::to_value(ModuleHelloBody {
12138            manifest: manifest("role-test", PROTOCOL_VERSION),
12139            protocol_ver: PROTOCOL_VERSION,
12140            control_ops: None,
12141            launch_nonce: None,
12142        })
12143        .unwrap();
12144        body["manifest"]["role_declarations"] = declarations;
12145        Frame::build(
12146            FrameType::Hello,
12147            control_flags(),
12148            0,
12149            0,
12150            301,
12151            serde_json::to_vec(&body).unwrap(),
12152        )
12153        .unwrap()
12154    }
12155
12156    fn update_role_declarations_frame(declarations: Value) -> Frame {
12157        Frame::build(
12158            FrameType::Request,
12159            control_flags(),
12160            0,
12161            0,
12162            303,
12163            serde_json::to_vec(&json!({
12164                "op": "catalog.update_role_declarations",
12165                "role_declarations": declarations,
12166            }))
12167            .unwrap(),
12168        )
12169        .unwrap()
12170    }
12171
12172    #[tokio::test]
12173    async fn role_declarations_update_replaces_then_clears_catalog() {
12174        let registry = Arc::new(Registry::default());
12175        let handler = ControlHandler::new(Arc::clone(&registry));
12176        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12177        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12178        hello_via_sink(
12179            &handler,
12180            &ctx,
12181            &mut rx,
12182            hello_with_role_declarations(initial.clone()),
12183        )
12184        .await;
12185        assert_eq!(
12186            role_declarations_catalog(&handler).0["role_declarations"],
12187            initial
12188        );
12189        let before = registry.get_module("role-test").unwrap().unwrap();
12190        for declarations in [
12191            json!({"media-provider/v1": {"engines": ["new"]}}),
12192            json!({}),
12193        ] {
12194            let response = handler
12195                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12196                .await
12197                .unwrap();
12198            assert_eq!(response[0].header.ty, FrameType::Response);
12199            assert_eq!(
12200                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12201                json!({"op": "catalog.update_role_declarations"})
12202            );
12203            let (raw, entry) = role_declarations_catalog(&handler);
12204            assert_eq!(
12205                serde_json::to_value(entry.role_declarations).unwrap(),
12206                declarations
12207            );
12208            if declarations.as_object().unwrap().is_empty() {
12209                assert!(raw.get("role_declarations").is_none());
12210            } else {
12211                assert_eq!(raw["role_declarations"], declarations);
12212            }
12213            let after = registry.get_module("role-test").unwrap().unwrap();
12214            let mut expected = before.manifest.clone();
12215            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12216            assert_eq!(after.manifest, expected);
12217            assert_eq!(after.ready, before.ready);
12218        }
12219    }
12220
12221    #[tokio::test]
12222    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12223        let registry = Arc::new(Registry::default());
12224        let handler = ControlHandler::new(registry);
12225        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12226        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12227        hello_via_sink(
12228            &handler,
12229            &ctx,
12230            &mut rx,
12231            hello_with_role_declarations(initial.clone()),
12232        )
12233        .await;
12234        for (invalid, reason) in [
12235            (json!(null), "role_declarations must be an object"),
12236            (json!([]), "role_declarations must be an object"),
12237            (
12238                json!({"bad key": {}}),
12239                "role_declarations key must use capability-name grammar",
12240            ),
12241            (
12242                json!({"media-provider/v1": []}),
12243                "role_declarations values must be objects",
12244            ),
12245            (
12246                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12247                "role_declarations exceeds 16384 compact JSON bytes",
12248            ),
12249        ] {
12250            let response = handler
12251                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12252                .await
12253                .unwrap();
12254            let error = parse_error(&response[0]);
12255            assert_eq!(error["code"], "invalid_role_declarations");
12256            assert_eq!(error["message"], reason);
12257            assert_eq!(
12258                role_declarations_catalog(&handler).0["role_declarations"],
12259                initial
12260            );
12261        }
12262    }
12263
12264    #[tokio::test]
12265    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12266        let registry = Arc::new(Registry::default());
12267        let handler = ControlHandler::new(Arc::clone(&registry));
12268        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12269        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12270        hello_via_sink(
12271            &handler,
12272            &owner,
12273            &mut owner_rx,
12274            hello_with_role_declarations(initial.clone()),
12275        )
12276        .await;
12277        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12278        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12279        let response = handler
12280            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12281            .await
12282            .unwrap();
12283        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12284        hello_via_sink(
12285            &handler,
12286            &other,
12287            &mut other_rx,
12288            hello_frame("other", PROTOCOL_VERSION, 304),
12289        )
12290        .await;
12291        let response = handler
12292            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12293            .await
12294            .unwrap();
12295        assert_eq!(response[0].header.ty, FrameType::Response);
12296        assert_eq!(
12297            serde_json::to_value(
12298                registry
12299                    .get_module("role-test")
12300                    .unwrap()
12301                    .unwrap()
12302                    .manifest
12303                    .role_declarations
12304            )
12305            .unwrap(),
12306            initial
12307        );
12308        assert_eq!(
12309            serde_json::to_value(
12310                registry
12311                    .get_module("other")
12312                    .unwrap()
12313                    .unwrap()
12314                    .manifest
12315                    .role_declarations
12316            )
12317            .unwrap(),
12318            replacement
12319        );
12320    }
12321
12322    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12323        let request = Frame::build(
12324            FrameType::Request,
12325            control_flags(),
12326            0,
12327            0,
12328            302,
12329            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12330        )
12331        .unwrap();
12332        let response = handler.handle_catalog_list(request, None).unwrap();
12333        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12334        let ClientControlResponse::CatalogList { mut modules, .. } =
12335            serde_json::from_slice(&response[0].body).unwrap()
12336        else {
12337            panic!("expected catalog.list");
12338        };
12339        (raw["modules"][0].clone(), modules.remove(0))
12340    }
12341
12342    #[test]
12343    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12344        let registry = Arc::new(Registry::default());
12345        let handler = ControlHandler::new(Arc::clone(&registry));
12346        let declarations = json!({
12347            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12348            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12349        });
12350        let connection = ConnectionId::new(301);
12351        let response = handler
12352            .handle_control(
12353                connection,
12354                hello_with_role_declarations(declarations.clone()),
12355            )
12356            .unwrap();
12357        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12358        let registered = registry
12359            .get_module_by_connection(connection)
12360            .unwrap()
12361            .unwrap()
12362            .manifest;
12363        // Compared as JSON values, not bytes: object key order is not part of
12364        // the relay's promise, and workspace builds unify serde_json's
12365        // preserve_order feature, which changes the order a literal keeps.
12366        assert_eq!(
12367            serde_json::to_value(&registered.role_declarations).unwrap(),
12368            declarations
12369        );
12370        let (raw, entry) = role_declarations_catalog(&handler);
12371        assert_eq!(raw["role_declarations"], declarations);
12372        assert_eq!(entry.role_declarations, registered.role_declarations);
12373
12374        let request =
12375            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12376        handler
12377            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12378            .unwrap();
12379        let (raw, entry) = role_declarations_catalog(&handler);
12380        assert_eq!(raw["role_declarations"], declarations);
12381        assert_eq!(entry.role_declarations, registered.role_declarations);
12382    }
12383
12384    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12385        let registry = Arc::new(Registry::default());
12386        let handler = ControlHandler::new(Arc::clone(&registry));
12387        let capture = EventCapture::default();
12388        let _subscriber =
12389            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12390        let response = handler
12391            .handle_control(
12392                ConnectionId::new(301),
12393                hello_with_role_declarations(declarations),
12394            )
12395            .unwrap();
12396        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12397        assert!(registry
12398            .get_module_by_connection(ConnectionId::new(301))
12399            .unwrap()
12400            .unwrap()
12401            .manifest
12402            .role_declarations
12403            .is_empty());
12404        let (raw, entry) = role_declarations_catalog(&handler);
12405        assert!(raw.get("role_declarations").is_none());
12406        assert!(entry.role_declarations.is_empty());
12407        let warnings: Vec<_> = capture
12408            .events()
12409            .into_iter()
12410            .filter(|event| {
12411                event.fields.get("message").map(String::as_str)
12412                    == Some("dropping whole role_declarations map from HELLO")
12413            })
12414            .collect();
12415        assert_eq!(warnings.len(), 1);
12416        assert_eq!(warnings[0].level, tracing::Level::WARN);
12417        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12418        assert_eq!(warnings[0].fields["reason"], reason);
12419    }
12420
12421    #[test]
12422    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12423        for value in [
12424            json!(null),
12425            json!(false),
12426            json!(0),
12427            json!("opaque"),
12428            json!([]),
12429        ] {
12430            assert_hello_drops_role_declarations_with_warning(
12431                json!({"routing/v1": {}, "broken/v1": value}),
12432                "role_declarations values must be objects",
12433            );
12434        }
12435        assert_hello_drops_role_declarations_with_warning(
12436            json!([]),
12437            "role_declarations must be an object",
12438        );
12439    }
12440
12441    #[test]
12442    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12443        assert_hello_drops_role_declarations_with_warning(
12444            json!({"routing/v1": {}, "bad key": {}}),
12445            "role_declarations key must use capability-name grammar",
12446        );
12447    }
12448
12449    #[test]
12450    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12451        assert_hello_drops_role_declarations_with_warning(
12452            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12453            "role_declarations exceeds 16384 compact JSON bytes",
12454        );
12455    }
12456
12457    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12458        let mut body = serde_json::to_value(ModuleHelloBody {
12459            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12460            protocol_ver: PROTOCOL_VERSION,
12461            control_ops: None,
12462            launch_nonce: None,
12463        })
12464        .unwrap();
12465        body["manifest"]["provides"] = json!([{
12466            "role": "management_surface",
12467            "operations": [
12468                {"name": "diagnostics.findings", "kind": "query"},
12469                {"name": "reset", "kind": "mutate"}
12470            ],
12471            "config_schema": {}, "observability": [], "identity_scope": []
12472        }]);
12473        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12474        if let Some(flow_operations) = flow_operations {
12475            body["manifest"]["flow_operations"] = flow_operations;
12476        }
12477        Frame::build(
12478            FrameType::Hello,
12479            control_flags(),
12480            0,
12481            0,
12482            401,
12483            serde_json::to_vec(&body).unwrap(),
12484        )
12485        .unwrap()
12486    }
12487
12488    #[test]
12489    fn catalog_list_mirrors_flow_operations_unchanged() {
12490        // Order is kept as declared (not sorted) and an empty list stays an
12491        // affirmative "none", distinct from an absent declaration.
12492        for (capability, flow_operations) in [
12493            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12494            ("call-modes/v1", json!(["diagnostics.findings"])),
12495            ("flow-scopes/v1", json!([])),
12496        ] {
12497            let registry = Arc::new(Registry::default());
12498            let handler = ControlHandler::new(Arc::clone(&registry));
12499            let connection = ConnectionId::new(401);
12500            let response = handler
12501                .handle_control(
12502                    connection,
12503                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12504                )
12505                .unwrap();
12506            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12507            let registered = registry
12508                .get_module_by_connection(connection)
12509                .unwrap()
12510                .unwrap()
12511                .manifest;
12512            assert_eq!(
12513                serde_json::to_value(&registered.flow_operations).unwrap(),
12514                flow_operations
12515            );
12516            let (raw, entry) = role_declarations_catalog(&handler);
12517            assert_eq!(raw["flow_operations"], flow_operations);
12518            assert_eq!(entry.flow_operations, registered.flow_operations);
12519        }
12520
12521        let registry = Arc::new(Registry::default());
12522        let handler = ControlHandler::new(Arc::clone(&registry));
12523        let response = handler
12524            .handle_control(
12525                ConnectionId::new(401),
12526                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12527            )
12528            .unwrap();
12529        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12530        let (raw, entry) = role_declarations_catalog(&handler);
12531        assert!(raw.get("flow_operations").is_none());
12532        assert_eq!(entry.flow_operations, None);
12533    }
12534
12535    #[test]
12536    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12537        let oversized: serde_json::Map<String, Value> = (0..257)
12538            .map(|n| (format!("tool:t{n}"), json!(true)))
12539            .collect();
12540        for (capabilities, map, valid) in [
12541            (
12542                json!(["scope-federated/v1"]),
12543                json!({"tool:read":true,"management:reset":true}),
12544                true,
12545            ),
12546            (json!(["scope-federated/v1"]), json!({}), true),
12547            (json!([]), json!({"tool:read":true}), false),
12548            (
12549                json!(["scope-federated/v1"]),
12550                json!({"tool:valid":true,"tool:bad":false}),
12551                false,
12552            ),
12553            (
12554                json!(["scope-federated/v1"]),
12555                json!({"tool:valid":true,"management:missing":true}),
12556                false,
12557            ),
12558            (
12559                json!(["scope-federated/v1"]),
12560                Value::Object(oversized),
12561                false,
12562            ),
12563        ] {
12564            let capture = EventCapture::default();
12565            let _subscriber = tracing::subscriber::set_default(
12566                tracing_subscriber::registry().with(capture.clone()),
12567            );
12568            let registry = Arc::new(Registry::default());
12569            let handler = ControlHandler::new(Arc::clone(&registry));
12570            let hello = hello_with_flow_operations(capabilities, None);
12571            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12572            body["manifest"]["operation_deferral"] = map.clone();
12573            let hello = Frame::build(
12574                FrameType::Hello,
12575                control_flags(),
12576                0,
12577                0,
12578                401,
12579                serde_json::to_vec(&body).unwrap(),
12580            )
12581            .unwrap();
12582            let response = handler
12583                .handle_control(ConnectionId::new(401), hello)
12584                .unwrap();
12585            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12586            let (raw, entry) = role_declarations_catalog(&handler);
12587            if valid {
12588                assert_eq!(raw["operation_deferral"], map);
12589                assert_eq!(
12590                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12591                    map
12592                );
12593            } else {
12594                assert!(entry.operation_deferral.is_none());
12595                assert!(raw.get("operation_deferral").is_none());
12596                assert_eq!(
12597                    capture
12598                        .events()
12599                        .iter()
12600                        .filter(|event| event.fields.get("message").map(String::as_str)
12601                            == Some("dropping operation_deferral from HELLO"))
12602                        .count(),
12603                    1
12604                );
12605            }
12606        }
12607    }
12608
12609    fn assert_hello_drops_flow_operations_with_warning(
12610        capabilities: Value,
12611        flow_operations: Value,
12612        reason: &str,
12613    ) {
12614        let registry = Arc::new(Registry::default());
12615        let handler = ControlHandler::new(Arc::clone(&registry));
12616        let capture = EventCapture::default();
12617        let _subscriber =
12618            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12619        let response = handler
12620            .handle_control(
12621                ConnectionId::new(401),
12622                hello_with_flow_operations(capabilities, Some(flow_operations)),
12623            )
12624            .unwrap();
12625        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12626        let registered = registry
12627            .get_module_by_connection(ConnectionId::new(401))
12628            .unwrap()
12629            .expect("the module still registers")
12630            .manifest;
12631        assert_eq!(registered.module_id, "flow-ops");
12632        assert_eq!(registered.flow_operations, None);
12633        let (raw, entry) = role_declarations_catalog(&handler);
12634        assert_eq!(raw["module_id"], "flow-ops");
12635        assert!(raw.get("flow_operations").is_none());
12636        assert_eq!(entry.flow_operations, None);
12637        let warnings: Vec<_> = capture
12638            .events()
12639            .into_iter()
12640            .filter(|event| {
12641                event.fields.get("message").map(String::as_str)
12642                    == Some("dropping flow_operations from HELLO")
12643            })
12644            .collect();
12645        assert_eq!(warnings.len(), 1);
12646        assert_eq!(warnings[0].level, tracing::Level::WARN);
12647        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12648        assert_eq!(warnings[0].fields["reason"], reason);
12649    }
12650
12651    #[test]
12652    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12653        assert_hello_drops_flow_operations_with_warning(
12654            json!(["flow-scopes/v1"]),
12655            json!(["diagnostics.findings", "missing"]),
12656            "flow_operations names 'missing', which is not a declared management operation",
12657        );
12658    }
12659
12660    #[test]
12661    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12662        assert_hello_drops_flow_operations_with_warning(
12663            json!([]),
12664            json!(["diagnostics.findings"]),
12665            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12666        );
12667        // A run-only capability does not admit flows either.
12668        assert_hello_drops_flow_operations_with_warning(
12669            json!(["agent-run-scopes/v1"]),
12670            json!([]),
12671            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12672        );
12673    }
12674
12675    #[test]
12676    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12677        assert_hello_drops_flow_operations_with_warning(
12678            json!(["flow-scopes/v1"]),
12679            json!(["reset", "reset"]),
12680            "flow_operations names 'reset' more than once",
12681        );
12682        assert_hello_drops_flow_operations_with_warning(
12683            json!(["flow-scopes/v1"]),
12684            json!(vec!["reset"; 257]),
12685            "flow_operations lists 257 names, more than 256",
12686        );
12687        assert_hello_drops_flow_operations_with_warning(
12688            json!(["flow-scopes/v1"]),
12689            json!("reset"),
12690            "flow_operations must be an array of operation names",
12691        );
12692    }
12693
12694    #[test]
12695    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12696        let registry = Arc::new(Registry::default());
12697        let handler = ControlHandler::new(registry.clone());
12698        let descriptor = json!({
12699            "schema": "ckios.richui.manifest/1",
12700            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12701            "bytes": 128,
12702            "chunks": 2
12703        });
12704        let malformed = [
12705            ("schema", json!("")),
12706            ("schema", json!("a".repeat(65))),
12707            ("schema", json!("Bad schema")),
12708            (
12709                "manifest_digest",
12710                json!(format!("sha256:{}", "A".repeat(64))),
12711            ),
12712            ("manifest_digest", json!("sha256:abc")),
12713            ("bytes", json!(0)),
12714            ("bytes", json!(16_777_217)),
12715            ("bytes", json!("128")),
12716            ("chunks", json!(0)),
12717            ("chunks", json!(1025)),
12718            ("chunks", json!("2")),
12719        ];
12720        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12721            let mut invalid = descriptor.clone();
12722            invalid[field] = invalid_value;
12723            let response = handler
12724                .handle_control(
12725                    ConnectionId::new(210 + index as u64),
12726                    hello_frame_with_rich_ui(
12727                        &format!("bad-rich-ui-{index}"),
12728                        PROTOCOL_VERSION,
12729                        210 + index as u64,
12730                        None,
12731                        invalid,
12732                    ),
12733                )
12734                .unwrap();
12735            assert_eq!(response[0].header.ty, FrameType::Error);
12736            let error = parse_error(&response[0]);
12737            assert_eq!(error["code"], "invalid_manifest");
12738            assert!(error["message"]
12739                .as_str()
12740                .unwrap()
12741                .contains(&format!("rich_ui.{field}")));
12742            assert!(registry
12743                .get_module(&format!("bad-rich-ui-{index}"))
12744                .unwrap()
12745                .is_none());
12746        }
12747    }
12748
12749    #[test]
12750    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12751        let registry = Arc::new(Registry::default());
12752        let handler = ControlHandler::new(Arc::clone(&registry));
12753        let connection = ConnectionId::new(219);
12754        registry
12755            .register_with_control_ops(
12756                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12757                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12758                        "bad schema",
12759                        format!("sha256:{}", "a".repeat(64)),
12760                        128,
12761                        2,
12762                    )))
12763                    .build(),
12764                PROTOCOL_VERSION,
12765                connection,
12766                Vec::new(),
12767            )
12768            .unwrap();
12769        let request =
12770            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12771        let response = handler
12772            .handle_catalog_update(connection, request, Vec::new(), None, None)
12773            .unwrap();
12774        assert_eq!(response[0].header.ty, FrameType::Error);
12775        let error = parse_error(&response[0]);
12776        assert_eq!(error["code"], "invalid_manifest");
12777        assert!(error["message"]
12778            .as_str()
12779            .unwrap()
12780            .contains("rich_ui.schema"));
12781    }
12782
12783    #[test]
12784    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12785        let registry = Arc::new(Registry::default());
12786        let supervisor = SupervisorHandle::new();
12787        supervisor.open_swap("provider", "candidate-nonce".to_string());
12788        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12789        let connection = ConnectionId::new(218);
12790        let hello = handler
12791            .handle_control(
12792                connection,
12793                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12794            )
12795            .unwrap();
12796        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12797        assert!(registry.list_modules().unwrap().1.is_empty());
12798
12799        registry.promote_candidate("provider").unwrap().unwrap();
12800        let request = Frame::build(
12801            FrameType::Request,
12802            control_flags(),
12803            0,
12804            0,
12805            219,
12806            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12807        )
12808        .unwrap();
12809        let response = handler.handle_catalog_list(request, None).unwrap();
12810        let ClientControlResponse::CatalogList { modules, .. } =
12811            serde_json::from_slice(&response[0].body).unwrap()
12812        else {
12813            panic!("expected catalog.list");
12814        };
12815        assert_eq!(modules.len(), 1);
12816        assert!(modules[0].nonce_verified);
12817    }
12818
12819    #[test]
12820    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12821        for provenance_json in [
12822            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12823            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12824        ] {
12825            let registry = Arc::new(Registry::default());
12826            let handler = ControlHandler::new(registry);
12827            let hello = Frame::build(
12828                FrameType::Hello,
12829                control_flags(),
12830                0,
12831                0,
12832                220,
12833                serde_json::to_vec(&ModuleHelloBody {
12834                    manifest: ModuleManifest::builder("built", "0.1.0")
12835                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12836                        .build(),
12837                    protocol_ver: PROTOCOL_VERSION,
12838                    control_ops: None,
12839                    launch_nonce: None,
12840                })
12841                .unwrap(),
12842            )
12843            .unwrap();
12844            assert_eq!(
12845                handler
12846                    .handle_control(ConnectionId::new(220), hello)
12847                    .unwrap()[0]
12848                    .header
12849                    .ty,
12850                FrameType::HelloAck
12851            );
12852            let request = Frame::build(
12853                FrameType::Request,
12854                control_flags(),
12855                0,
12856                0,
12857                221,
12858                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12859            )
12860            .unwrap();
12861            let response = handler.handle_catalog_list(request, None).unwrap();
12862            let ClientControlResponse::CatalogList { modules, .. } =
12863                serde_json::from_slice(&response[0].body).unwrap()
12864            else {
12865                panic!("expected catalog.list");
12866            };
12867            assert_eq!(modules.len(), 1);
12868            assert_eq!(
12869                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12870                format!(
12871                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12872                )
12873                .as_bytes()
12874            );
12875        }
12876    }
12877
12878    #[test]
12879    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12880        let registry = Arc::new(Registry::default());
12881        let handler = ControlHandler::new(Arc::clone(&registry));
12882        let hello = Frame::build(
12883            FrameType::Hello,
12884            control_flags(),
12885            0,
12886            0,
12887            220,
12888            serde_json::to_vec(&ModuleHelloBody {
12889                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12890                protocol_ver: PROTOCOL_VERSION,
12891                control_ops: None,
12892                launch_nonce: Some("unverified".to_string()),
12893            })
12894            .unwrap(),
12895        )
12896        .unwrap();
12897        assert_eq!(
12898            handler
12899                .handle_control(ConnectionId::new(220), hello)
12900                .unwrap()[0]
12901                .header
12902                .ty,
12903            FrameType::HelloAck
12904        );
12905        let request = Frame::build(
12906            FrameType::Request,
12907            control_flags(),
12908            0,
12909            0,
12910            221,
12911            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12912        )
12913        .unwrap();
12914        let response = handler.handle_catalog_list(request, None).unwrap();
12915        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
12916        assert!(wire["modules"][0].get("provenance").is_none());
12917        let ClientControlResponse::CatalogList { modules, .. } =
12918            serde_json::from_slice(&response[0].body).unwrap()
12919        else {
12920            panic!("expected catalog.list");
12921        };
12922        assert_eq!(
12923            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12924            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
12925        );
12926        assert!(!modules[0].nonce_verified);
12927        assert!(modules[0].provenance.is_none());
12928    }
12929
12930    // Preserve the legacy-field byte pins while discovery adds optional facts.
12931    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
12932        assert_eq!(entry.first_party, Some(false));
12933        entry.incarnation = None;
12934        entry.spawn = None;
12935        entry.first_party = None;
12936        entry.origin = None;
12937        entry.requested_declarations_digest = None;
12938        entry.approved_declarations_digest = None;
12939        entry
12940    }
12941
12942    #[test]
12943    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
12944        let registry = Arc::new(Registry::default());
12945        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
12946            [("vault".to_string(), true), ("squatter".to_string(), true)],
12947            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
12948        );
12949        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
12950        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
12951            provides: vec!["credentials-provider/v1".to_string()],
12952            requires: Vec::new(),
12953            must_never_reach: Vec::new(),
12954        });
12955        let frame = Frame::build(
12956            FrameType::Hello,
12957            control_flags(),
12958            0,
12959            0,
12960            77,
12961            serde_json::to_vec(&ModuleHelloBody {
12962                manifest: squatter,
12963                protocol_ver: PROTOCOL_VERSION,
12964                control_ops: None,
12965                launch_nonce: None,
12966            })
12967            .expect("HELLO serializes"),
12968        )
12969        .expect("HELLO frame builds");
12970        let response = handler
12971            .handle_control(ConnectionId::new(77), frame)
12972            .expect("reserved claim receives a typed refusal");
12973        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
12974        assert_eq!(
12975            registry
12976                .active_registration_count()
12977                .expect("registry reads"),
12978            0,
12979            "a reserved capability refusal must not leave a catalog entry"
12980        );
12981    }
12982
12983    #[test]
12984    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
12985        for settlement in ["timeout", "inconclusive", "drop"] {
12986            let breakers = RouteBindBreakers::default();
12987            let RouteBindAdmission::Admitted {
12988                guard: mut old,
12989                probe: false,
12990            } = breakers.admit("prov")
12991            else {
12992                panic!("ordinary relay admitted")
12993            };
12994            let RouteBindAdmission::Admitted {
12995                guard: mut opener, ..
12996            } = breakers.admit("prov")
12997            else {
12998                panic!("second relay admitted")
12999            };
13000            assert!(
13001                !opener
13002                    .record_timeout(1, Duration::ZERO)
13003                    .unwrap()
13004                    .reopened_after_probe
13005            );
13006            let RouteBindAdmission::Admitted {
13007                guard: mut probe,
13008                probe: true,
13009            } = breakers.admit("prov")
13010            else {
13011                panic!("one cooldown probe admitted")
13012            };
13013            match settlement {
13014                "timeout" => assert!(
13015                    !old.record_timeout(1, Duration::ZERO)
13016                        .unwrap()
13017                        .reopened_after_probe
13018                ),
13019                "inconclusive" => old.record_inconclusive(),
13020                "drop" => drop(old),
13021                _ => unreachable!(),
13022            }
13023            assert!(
13024                matches!(
13025                    breakers.admit("prov"),
13026                    RouteBindAdmission::Refused {
13027                        probe_in_flight: true,
13028                        ..
13029                    }
13030                ),
13031                "{settlement} of a pre-open relay cannot release the real probe"
13032            );
13033            assert!(
13034                probe
13035                    .record_timeout(1, Duration::ZERO)
13036                    .unwrap()
13037                    .reopened_after_probe
13038            );
13039            assert!(matches!(
13040                breakers.admit("prov"),
13041                RouteBindAdmission::Admitted { probe: true, .. }
13042            ));
13043        }
13044        let breakers = RouteBindBreakers::default();
13045        let admit = || match breakers.admit("prov") {
13046            RouteBindAdmission::Admitted { guard, .. } => guard,
13047            _ => panic!("relay admitted"),
13048        };
13049        admit().record_timeout(1, Duration::ZERO);
13050        let mut old_probe = admit();
13051        breakers.reset_for_new_module_connection("prov");
13052        admit().record_timeout(1, Duration::ZERO);
13053        let _new_probe = admit();
13054        old_probe.record_inconclusive();
13055        assert!(matches!(
13056            breakers.admit("prov"),
13057            RouteBindAdmission::Refused {
13058                probe_in_flight: true,
13059                ..
13060            }
13061        ));
13062    }
13063
13064    #[tokio::test]
13065    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13066        for candidate in [false, true] {
13067            let registry = Arc::new(Registry::default());
13068            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13069                [("vault".to_string(), true), ("squatter".to_string(), true)],
13070                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13071            );
13072            let conn = ConnectionId::new(77);
13073            let (ctx, mut rx) = route_ctx(conn);
13074            let initial = capability_manifest("squatter", &[], &[]);
13075            if candidate {
13076                registry
13077                    .register_candidate_with_control_ops(
13078                        initial.clone(),
13079                        PROTOCOL_VERSION,
13080                        conn,
13081                        module_baseline_control_ops(),
13082                    )
13083                    .unwrap();
13084                handler
13085                    .forwarding
13086                    .register_candidate_module_connection(
13087                        conn,
13088                        "squatter".to_string(),
13089                        PROTOCOL_VERSION,
13090                        manifest_concurrency(&initial),
13091                        ctx.egress.clone(),
13092                    )
13093                    .unwrap();
13094            } else {
13095                hello_via_sink(
13096                    &handler,
13097                    &ctx,
13098                    &mut rx,
13099                    hello_frame_with_manifest(initial.clone(), 1),
13100                )
13101                .await;
13102            }
13103            let response = handler
13104                .handle_control_frame(
13105                    &ctx,
13106                    catalog_update_with_capabilities_frame(
13107                        2,
13108                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13109                            .capabilities
13110                            .unwrap(),
13111                    ),
13112                )
13113                .await
13114                .unwrap();
13115            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13116            assert_eq!(
13117                registry
13118                    .get_module_by_connection(conn)
13119                    .unwrap()
13120                    .unwrap()
13121                    .manifest,
13122                initial
13123            );
13124        }
13125    }
13126
13127    #[test]
13128    #[cfg(not(feature = "dev-desktop-approval"))]
13129    fn server_describe_default_build_advertises_no_config_capability() {
13130        let assert_default = |handler: &ControlHandler| {
13131            let request = Frame::build(
13132                FrameType::Request,
13133                control_flags(),
13134                0,
13135                0,
13136                79,
13137                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13138            )
13139            .unwrap();
13140            let responses = handler.handle_server_describe(request).unwrap();
13141            assert_eq!(responses.len(), 1);
13142            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13143            assert_eq!(response["op"], "server.describe");
13144            let capabilities = response["capabilities"]
13145                .as_array()
13146                .expect("capability array");
13147            assert!(
13148                !capabilities.is_empty(),
13149                "exercise an actual describe response, not an empty fixture"
13150            );
13151            assert!(
13152                capabilities
13153                    .iter()
13154                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13155                "a default build must not announce configuration authority: {capabilities:?}"
13156            );
13157        };
13158        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13159        #[cfg(unix)]
13160        {
13161            // A local store does not prove that project-membership validation,
13162            // active-scope usage tracking and approved-program launch selection
13163            // are connected. Defaults must not advertise that authority.
13164            let (_rig, _owner, _supervisor, handler, _spec) =
13165                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13166                );
13167            assert_default(&handler);
13168        }
13169    }
13170
13171    #[test]
13172    fn server_describe_surfaces_required_capability_verdict_fields() {
13173        let registry = Arc::new(Registry::default());
13174        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13175            [
13176                ("consumer".to_string(), true),
13177                ("provider".to_string(), false),
13178            ],
13179            BTreeMap::new(),
13180        );
13181        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13182        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13183            provides: Vec::new(),
13184            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13185                capability: "credentials-provider/v1".to_string(),
13186                need: subc_protocol::manifest::CapabilityNeed::Required,
13187            }],
13188            must_never_reach: Vec::new(),
13189        });
13190        let hello = Frame::build(
13191            FrameType::Hello,
13192            control_flags(),
13193            0,
13194            0,
13195            78,
13196            serde_json::to_vec(&ModuleHelloBody {
13197                manifest: consumer,
13198                protocol_ver: PROTOCOL_VERSION,
13199                control_ops: None,
13200                launch_nonce: None,
13201            })
13202            .expect("HELLO serializes"),
13203        )
13204        .expect("HELLO frame builds");
13205        handler
13206            .handle_control(ConnectionId::new(78), hello)
13207            .expect("consumer registers");
13208        let describe = Frame::build(
13209            FrameType::Request,
13210            control_flags(),
13211            0,
13212            0,
13213            79,
13214            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13215                .expect("request serializes"),
13216        )
13217        .expect("describe frame builds");
13218        let response = handler
13219            .handle_server_describe(describe)
13220            .expect("server.describe succeeds");
13221        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13222        let requirement = &rendered["capability_requirements"][0];
13223        assert_eq!(requirement["consumer"], "consumer");
13224        assert_eq!(requirement["verdict"], "never_provided");
13225        assert_eq!(requirement["episode_seq"], 1);
13226        assert_eq!(requirement["config_satisfiable"], false);
13227        assert_eq!(requirement["runtime_available"], false);
13228        assert!(requirement["detail"]
13229            .as_str()
13230            .expect("detail string")
13231            .contains("credentials-provider/v1"));
13232    }
13233
13234    /// Register a consumer that requires `project-identity/v1` and the provider
13235    /// of it, optionally mark daemon shutdown as begun, then deregister the
13236    /// provider as its connection closes. Returns the `capability.requirement`
13237    /// events that deregistration logged and the verdict the evaluator then
13238    /// holds for the requirement (the one `route.open` refusals read).
13239    fn deregister_required_provider(
13240        daemon_shutdown_begun: bool,
13241    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13242        const CAPABILITY: &str = "project-identity/v1";
13243        let registry = Arc::new(Registry::default());
13244        let daemon_shutdown = DaemonShutdownFlag::default();
13245        let handler = ControlHandler::new(Arc::clone(&registry))
13246            .with_capability_config(
13247                [
13248                    ("consumer".to_string(), true),
13249                    ("provider".to_string(), true),
13250                ],
13251                BTreeMap::new(),
13252            )
13253            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13254        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13255        consumer.capabilities = Some(CapabilityDeclarations {
13256            provides: Vec::new(),
13257            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13258                capability: CAPABILITY.to_string(),
13259                need: subc_protocol::manifest::CapabilityNeed::Required,
13260            }],
13261            must_never_reach: Vec::new(),
13262        });
13263        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13264        let provider_conn = ConnectionId::new(182);
13265        for (conn, manifest, corr) in [
13266            (ConnectionId::new(181), consumer, 181),
13267            (provider_conn, provider, 182),
13268        ] {
13269            let hello = handler
13270                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13271                .expect("module registers");
13272            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13273        }
13274        assert_eq!(
13275            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13276            Some(CapabilityVerdict::Provided),
13277            "the registered provider must satisfy the requirement first"
13278        );
13279        if daemon_shutdown_begun {
13280            daemon_shutdown.set_for_test();
13281        }
13282
13283        let capture = EventCapture::default();
13284        let _subscriber =
13285            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13286        handler
13287            .cleanup_connection(provider_conn)
13288            .expect("provider deregisters");
13289        let events = capture
13290            .events()
13291            .into_iter()
13292            .filter(|event| {
13293                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13294            })
13295            .collect();
13296        (
13297            events,
13298            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13299        )
13300    }
13301
13302    #[test]
13303    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13304        let (events, verdict) = deregister_required_provider(true);
13305        assert_eq!(
13306            verdict,
13307            Some(CapabilityVerdict::NeverProvided),
13308            "shutdown must not change the verdict route.open refusals read"
13309        );
13310        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13311        let event = &events[0];
13312        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13313        assert_eq!(
13314            event.fields.get("cause").map(String::as_str),
13315            Some("\"daemon_shutdown\""),
13316            "{event:?}"
13317        );
13318        assert_eq!(
13319            event.fields.get("verdict").map(String::as_str),
13320            Some("\"never_provided\""),
13321            "{event:?}"
13322        );
13323    }
13324
13325    #[test]
13326    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13327        let (events, verdict) = deregister_required_provider(false);
13328        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13329        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13330        let event = &events[0];
13331        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13332        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13333        assert_eq!(
13334            event.fields.get("verdict").map(String::as_str),
13335            Some("\"never_provided\""),
13336            "{event:?}"
13337        );
13338    }
13339
13340    #[test]
13341    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13342        let registry = Arc::new(Registry::default());
13343        let handler = ControlHandler::new(Arc::clone(&registry));
13344        let hello = handler
13345            .handle_control(
13346                ConnectionId::new(101),
13347                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13348            )
13349            .expect("legacy HELLO registers");
13350        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13351
13352        let request = Frame::build(
13353            FrameType::Request,
13354            control_flags(),
13355            0,
13356            0,
13357            102,
13358            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13359                .expect("catalog request serializes"),
13360        )
13361        .expect("catalog request frame builds");
13362        let response = handler
13363            .handle_catalog_list(request, None)
13364            .expect("catalog list succeeds");
13365        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13366        assert!(
13367            body["modules"][0].get("capabilities").is_none(),
13368            "legacy manifest must retain an absent capabilities field on catalog.list"
13369        );
13370    }
13371
13372    #[test]
13373    fn hello_ack_omits_storage_when_no_storage_config() {
13374        let registry = Arc::new(Registry::default());
13375        let handler = ControlHandler::new(Arc::clone(&registry));
13376        let responses = handler
13377            .handle_control(
13378                ConnectionId::new(1),
13379                hello_frame("aft", PROTOCOL_VERSION, 7),
13380            )
13381            .unwrap();
13382        let ack = parse_ack(&responses[0]);
13383        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13384        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13385    }
13386
13387    #[tokio::test]
13388    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13389        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13390        let registry = Arc::new(Registry::default());
13391        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13392        let responses = handler
13393            .handle_control(
13394                ConnectionId::new(1),
13395                hello_frame("aft", PROTOCOL_VERSION, 7),
13396            )
13397            .unwrap();
13398        let ack = parse_ack(&responses[0]);
13399        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13400
13401        let described = handler
13402            .handle_control_frame(
13403                &route_ctx(ConnectionId::new(2)).0,
13404                Frame::build(
13405                    FrameType::Request,
13406                    control_flags(),
13407                    0,
13408                    0,
13409                    9,
13410                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13411                )
13412                .unwrap(),
13413            )
13414            .await
13415            .unwrap();
13416        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13417            serde_json::from_slice(&described[0].body).unwrap()
13418        else {
13419            panic!("server.describe answered with another shape");
13420        };
13421        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13422    }
13423
13424    #[test]
13425    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13426        // With a central sqlite storage policy, each registering module gets its
13427        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13428        let registry = Arc::new(Registry::default());
13429        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13430            crate::daemon_config::StorageConfig::Sqlite {
13431                data_home: std::path::PathBuf::from("/data"),
13432            },
13433        ));
13434
13435        let responses = handler
13436            .handle_control(
13437                ConnectionId::new(1),
13438                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13439            )
13440            .unwrap();
13441        let ack = parse_ack(&responses[0]);
13442        assert_eq!(
13443            ack.storage,
13444            Some(serde_json::json!({
13445                "module_id": "alfonso-routing",
13446                "storage_namespace": "default",
13447                "isolation": { "kind": "module" },
13448                "backend": {
13449                    "backend": "sqlite",
13450                    "path": "/data/cortexkit/alfonso-routing/store.db"
13451                }
13452            })),
13453            "the delivered descriptor is the module's own sqlite store path"
13454        );
13455    }
13456
13457    #[test]
13458    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13459        let registry = Arc::new(Registry::default());
13460        let handler = ControlHandler::new(Arc::clone(&registry));
13461        let conn = ConnectionId::new(1);
13462        let responses = handler
13463            .handle_control(
13464                conn,
13465                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13466            )
13467            .unwrap();
13468        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13469        let registration = registry.get_module("aft").unwrap().unwrap();
13470        assert_eq!(registration.control_ops, module_baseline_control_ops());
13471
13472        let frame =
13473            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13474        assert!(handler
13475            .guard_module_control_op(&frame, "aft", "route.bind")
13476            .unwrap()
13477            .is_none());
13478        let error = handler
13479            .guard_module_control_op(&frame, "aft", "test.synthetic")
13480            .unwrap()
13481            .expect("synthetic ungranted op should be rejected");
13482        assert_eq!(error.header.ty, FrameType::Error);
13483        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13484    }
13485
13486    #[test]
13487    fn hello_control_ops_some_adds_optional_grants() {
13488        let registry = Arc::new(Registry::default());
13489        let handler = ControlHandler::new(Arc::clone(&registry));
13490        handler
13491            .handle_control(
13492                ConnectionId::new(1),
13493                hello_frame_with_control_ops(
13494                    "aft",
13495                    PROTOCOL_VERSION,
13496                    7,
13497                    Some(vec![
13498                        "future.synthetic".to_string(),
13499                        "route.bind".to_string(),
13500                    ]),
13501                ),
13502            )
13503            .unwrap();
13504        let registration = registry.get_module("aft").unwrap().unwrap();
13505        assert_eq!(
13506            registration.control_ops,
13507            vec![
13508                "route.bind".to_string(),
13509                "route.status".to_string(),
13510                "future.synthetic".to_string(),
13511            ]
13512        );
13513        let frame =
13514            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13515        assert!(handler
13516            .guard_module_control_op(&frame, "aft", "future.synthetic")
13517            .unwrap()
13518            .is_none());
13519    }
13520
13521    #[tokio::test]
13522    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13523        let registry = Arc::new(Registry::default());
13524        let forwarding = Arc::new(ForwardingTable::default());
13525        let handler =
13526            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13527        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13528        hello_via_sink(
13529            &handler,
13530            &module_ctx,
13531            &mut module_rx,
13532            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13533        )
13534        .await;
13535
13536        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13537        let responses = handler
13538            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13539            .await
13540            .unwrap();
13541        assert_eq!(responses.len(), 1);
13542        assert_eq!(responses[0].header.ty, FrameType::Error);
13543        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13544        assert!(module_rx.try_recv().is_err());
13545    }
13546
13547    #[tokio::test]
13548    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13549        let registry = Arc::new(Registry::default());
13550        let forwarding = Arc::new(ForwardingTable::default());
13551        let handler =
13552            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13553        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13554        hello_via_sink(
13555            &handler,
13556            &module_ctx,
13557            &mut module_rx,
13558            hello_frame_with_control_ops(
13559                "aft",
13560                PROTOCOL_VERSION,
13561                7,
13562                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13563            ),
13564        )
13565        .await;
13566
13567        let project_root = unique_project_root("demux");
13568        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13569        let route_handler = handler.clone();
13570        let route_task = tokio::spawn(async move {
13571            route_handler
13572                .handle_control_frame(
13573                    &route_client_ctx,
13574                    route_open_frame(100, "aft", project_root),
13575                )
13576                .await
13577                .unwrap()
13578        });
13579        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13580            .await
13581            .unwrap()
13582            .unwrap();
13583        assert!(matches!(
13584            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13585            ModuleControlRequest::RouteBind { .. }
13586        ));
13587
13588        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13589        let health_handler = handler.clone();
13590        let health_task = tokio::spawn(async move {
13591            health_handler
13592                .handle_control_frame(
13593                    &health_client_ctx,
13594                    supervisor_health_probe_frame(101, "aft"),
13595                )
13596                .await
13597                .unwrap()
13598        });
13599        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13600            .await
13601            .unwrap()
13602            .unwrap();
13603        assert_eq!(
13604            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13605            ModuleControlRequest::HealthCheck {}
13606        );
13607
13608        handler
13609            .handle_control_frame(
13610                &module_ctx,
13611                health_response(health_frame.header.corr, HealthStatus::Degraded),
13612            )
13613            .await
13614            .unwrap();
13615        let health_response = health_task.await.unwrap();
13616        assert_eq!(health_response.len(), 1);
13617        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13618            ClientControlResponse::SupervisorHealthProbe {
13619                module_id,
13620                status,
13621                detail,
13622                metrics,
13623            } => {
13624                assert_eq!(module_id, "aft");
13625                assert_eq!(status, HealthStatus::Degraded);
13626                assert_eq!(detail.as_deref(), Some("warming"));
13627                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13628            }
13629            other => panic!("unexpected health response: {other:?}"),
13630        }
13631
13632        handler
13633            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13634            .await
13635            .unwrap();
13636        let route_response = route_task.await.unwrap();
13637        assert!(route_response.is_empty());
13638        let published = route_client_rx.recv().await.unwrap();
13639        assert!(matches!(
13640            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13641            ClientControlResponse::RouteOpen { .. }
13642        ));
13643    }
13644
13645    /// Start one `route.open` on `client_connection` and return its still-running
13646    /// handler task together with the `route.bind` the module received for it.
13647    /// The handler blocks until the module answers, so it has to run as a task
13648    /// while the test drives the module side.
13649    async fn relay_route_open(
13650        handler: &ControlHandler,
13651        client_connection: ConnectionId,
13652        client_egress: &FrameSink,
13653        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13654        corr: u64,
13655        module_id: &str,
13656        project_root_label: &str,
13657    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13658        let ctx = RouteCtx {
13659            connection_id: client_connection,
13660            egress: client_egress.clone(),
13661        };
13662        let handler = handler.clone();
13663        let project_root = unique_project_root(project_root_label);
13664        let module_id = module_id.to_string();
13665        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13666        let task = tokio::spawn(async move {
13667            let _guard = tracing::dispatcher::set_default(&dispatch);
13668            handler
13669                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13670                .await
13671                .unwrap()
13672        });
13673        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13674            .await
13675            .expect("module receives the relayed route.bind")
13676            .expect("module egress is open");
13677        (task, bind.frame)
13678    }
13679
13680    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13681        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13682            ModuleControlRequest::RouteBind {
13683                route_channel,
13684                epoch,
13685                ..
13686            } => (route_channel, epoch),
13687            other => panic!("expected a route.bind request, got {other:?}"),
13688        }
13689    }
13690
13691    fn published_route(frame: &Frame) -> (u16, u32) {
13692        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13693            ClientControlResponse::RouteOpen {
13694                route_channel,
13695                route_epoch,
13696                ..
13697            } => (route_channel, route_epoch),
13698            other => panic!("expected a route.open response, got {other:?}"),
13699        }
13700    }
13701
13702    /// Reproduction of a production outage. A client had `route.open`s in
13703    /// flight to a module and was already marked closing -- its egress had refused a
13704    /// module frame, so the daemon asked its connection to end -- while its sink
13705    /// was still open. When the module acked those binds, the daemon refused to
13706    /// commit a route for a closing client, and that refusal was returned from
13707    /// the MODULE connection's frame handler, where a router error that has no
13708    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13709    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13710    /// its tools for hours -- one client's teardown took down a connection
13711    /// carrying ~170 other routes.
13712    ///
13713    /// The window is opened here by calling the production path that opens it
13714    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13715    /// state that matters is "in `closing_connections`, sink still open, relay
13716    /// still pending", and it lasts only from the close request until the
13717    /// connection loop reacts to it; a socket-level test can flood a client into
13718    /// that escalation but cannot pin the module's ack inside the window. Closing
13719    /// the socket instead takes the other path entirely -- connection teardown
13720    /// removes the pending relay under the same lock, so the ack finds nothing.
13721    #[tokio::test]
13722    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13723        let registry = Arc::new(Registry::default());
13724        let forwarding = Arc::new(ForwardingTable::default());
13725        let handler =
13726            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13727
13728        let module_connection = ConnectionId::new(30);
13729        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13730        hello_via_sink(
13731            &handler,
13732            &module_ctx,
13733            &mut module_rx,
13734            hello_frame("aft", PROTOCOL_VERSION, 7),
13735        )
13736        .await;
13737
13738        let dying_client = ConnectionId::new(31);
13739        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13740
13741        // A published route on the dying client. The escalation below only marks
13742        // a connection closing for a route it has already published.
13743        let (first_task, first_bind) = relay_route_open(
13744            &handler,
13745            dying_client,
13746            &dying_ctx.egress,
13747            &mut module_rx,
13748            100,
13749            "aft",
13750            "closing-first",
13751        )
13752        .await;
13753        handler
13754            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13755            .await
13756            .unwrap();
13757        assert!(first_task.await.unwrap().is_empty());
13758        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13759
13760        // A second route.open from the same client, relayed and awaiting its ack.
13761        let (second_task, second_bind) = relay_route_open(
13762            &handler,
13763            dying_client,
13764            &dying_ctx.egress,
13765            &mut module_rx,
13766            101,
13767            "aft",
13768            "closing-second",
13769        )
13770        .await;
13771        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13772
13773        // The window: the client is closing, its sink is still open, and its
13774        // second bind is still pending.
13775        assert!(forwarding
13776            .escalate_client_delivery_failure(
13777                dying_client,
13778                first_channel,
13779                first_epoch,
13780                CloseReason::new(
13781                    "module_to_client_delivery_failed",
13782                    "client egress refused a module frame",
13783                ),
13784                crate::forwarding::UndeliveredFrame {
13785                    module_id: None,
13786                    sink: &dying_ctx.egress,
13787                },
13788            )
13789            .unwrap());
13790        assert!(!dying_ctx.egress.is_closed());
13791
13792        // The frame that used to end the module connection.
13793        let ack = handler
13794            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13795            .await;
13796        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13797        if module_loop_error.is_some() {
13798            // What the server's connection loop does with a router error that has
13799            // no ERROR-frame translation: end the connection, which releases the
13800            // module's registration and every route on it.
13801            handler.cleanup_connection(module_connection).unwrap();
13802        }
13803        // Read the module's next frame before opening the co-tenant's route, so
13804        // the GOODBYE assertion below is about THIS ack and not about later
13805        // traffic. `None` means the module was told nothing.
13806        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13807            .await
13808            .ok()
13809            .flatten();
13810
13811        // 1. The module connection is still registered.
13812        assert!(
13813            registry
13814                .get_module_by_connection(module_connection)
13815                .unwrap()
13816                .is_some(),
13817            "one client's closing connection ended the shared module connection: \
13818             {module_loop_error:?}"
13819        );
13820        // ...and still serving: another client can open and use a route on it.
13821        let cotenant = ConnectionId::new(32);
13822        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13823        let (cotenant_task, cotenant_bind) = relay_route_open(
13824            &handler,
13825            cotenant,
13826            &cotenant_ctx.egress,
13827            &mut module_rx,
13828            102,
13829            "aft",
13830            "closing-cotenant",
13831        )
13832        .await;
13833        handler
13834            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13835            .await
13836            .unwrap();
13837        assert!(cotenant_task.await.unwrap().is_empty());
13838        let (cotenant_channel, cotenant_epoch) =
13839            published_route(&cotenant_rx.recv().await.unwrap());
13840        assert!(matches!(
13841            forwarding
13842                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13843                .unwrap(),
13844            DataRoute::Client(DataRouteState::Bound(_))
13845        ));
13846
13847        // 2. The module was told to drop the binding it created for the route
13848        //    that will never be published.
13849        let goodbye = post_ack_module_frame
13850            .expect("module receives a GOODBYE for the abandoned route channel");
13851        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13852        assert_eq!(goodbye.header.channel, abandoned_channel);
13853        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13854
13855        // 3. The dying client received nothing: no route was ever published to
13856        //    it. Its route.open is answered as unavailable, which the connection
13857        //    loop would write to a socket that is already going away.
13858        assert!(dying_rx.try_recv().is_err());
13859        let second_response = second_task.await.unwrap();
13860        assert_eq!(second_response.len(), 1);
13861        assert_eq!(
13862            parse_error(&second_response[0])["code"],
13863            "target_unavailable"
13864        );
13865    }
13866
13867    /// One `catalog.list` as a client sees it: the generation and the listed
13868    /// module ids with their readiness.
13869    async fn catalog_snapshot(
13870        handler: &ControlHandler,
13871        client_ctx: &RouteCtx,
13872        corr: u64,
13873    ) -> (u64, Vec<(String, bool)>) {
13874        let body =
13875            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13876        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13877        let reply = handler
13878            .handle_control_frame(client_ctx, request)
13879            .await
13880            .unwrap()
13881            .pop()
13882            .unwrap();
13883        let ClientControlResponse::CatalogList {
13884            generation,
13885            modules,
13886            ..
13887        } = serde_json::from_slice(&reply.body).unwrap()
13888        else {
13889            panic!("not a catalog.list reply");
13890        };
13891        (
13892            generation,
13893            modules
13894                .into_iter()
13895                .map(|entry| (entry.module_id, entry.ready))
13896                .collect(),
13897        )
13898    }
13899
13900    /// A handler whose HELLO for module "aft" on connection 40 is parked
13901    /// between reserving its registry entry and installing its forwarding
13902    /// endpoint. Returns the handler, the two-party barrier (wait once to know
13903    /// the HELLO is parked, once more to release it), the HELLO's thread, and
13904    /// the module's context and receiver.
13905    fn hello_held_before_forwarding() -> (
13906        ControlHandler,
13907        Arc<std::sync::Barrier>,
13908        std::thread::JoinHandle<Vec<Frame>>,
13909        RouteCtx,
13910        mpsc::Receiver<crate::router::OutboundFrame>,
13911    ) {
13912        let hold = Arc::new(std::sync::Barrier::new(2));
13913        let handler = ControlHandler::with_forwarding(
13914            Arc::new(Registry::default()),
13915            Arc::new(ForwardingTable::default()),
13916        )
13917        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
13918        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
13919        let hello = {
13920            let handler = handler.clone();
13921            let module_ctx = module_ctx.clone();
13922            std::thread::spawn(move || {
13923                handler
13924                    .handle_hello(
13925                        module_ctx.connection_id,
13926                        Some(module_ctx.egress.clone()),
13927                        hello_frame("aft", PROTOCOL_VERSION, 7),
13928                    )
13929                    .unwrap()
13930            })
13931        };
13932        (handler, hold, hello, module_ctx, module_rx)
13933    }
13934
13935    /// If a lookup can acquire the registry while publication is parked, let
13936    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
13937    /// after the lookup has tried the lock. Both schedules avoid timing guesses
13938    /// and return the actual lookup result, including an unpublished snapshot
13939    /// when the publication lock is missing.
13940    fn lookup_during_hello_publication<T: Send + 'static>(
13941        registry: &Registry,
13942        hold: &std::sync::Barrier,
13943        lookup: impl FnOnce() -> T + Send + 'static,
13944    ) -> T {
13945        let attempted = registry.observe_next_lock_attempt();
13946        let reader = std::thread::spawn(lookup);
13947        if attempted.recv().unwrap() {
13948            let result = reader.join().unwrap();
13949            hold.wait();
13950            result
13951        } else {
13952            hold.wait();
13953            reader.join().unwrap()
13954        }
13955    }
13956
13957    #[test]
13958    fn catalog_read_after_hello_ack_waits_for_publication() {
13959        let registry = Arc::new(Registry::default());
13960        let hold = Arc::new(std::sync::Barrier::new(2));
13961        let mut handler = ControlHandler::with_forwarding(
13962            Arc::clone(&registry),
13963            Arc::new(ForwardingTable::default()),
13964        );
13965        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
13966        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
13967        let hello = {
13968            let handler = handler.clone();
13969            std::thread::spawn(move || {
13970                handler
13971                    .handle_hello(
13972                        module_ctx.connection_id,
13973                        Some(module_ctx.egress),
13974                        hello_frame("aft", PROTOCOL_VERSION, 7),
13975                    )
13976                    .unwrap()
13977            })
13978        };
13979        hold.wait();
13980        assert_eq!(
13981            module_rx.try_recv().unwrap().frame.header.ty,
13982            FrameType::HelloAck
13983        );
13984        let replies = lookup_during_hello_publication(&registry, &hold, move || {
13985            // A different connection can issue catalog.list as soon as the
13986            // module has read its ACK, even while HELLO has not returned.
13987            let request = Frame::build(
13988                FrameType::Request,
13989                control_flags(),
13990                0,
13991                0,
13992                300,
13993                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13994            )
13995            .unwrap();
13996            handler.handle_catalog_list(request, None).unwrap()
13997        });
13998        assert!(hello.join().unwrap().is_empty());
13999        let ClientControlResponse::CatalogList {
14000            generation,
14001            modules,
14002            ..
14003        } = serde_json::from_slice(&replies[0].body).unwrap()
14004        else {
14005            panic!("not a catalog.list reply");
14006        };
14007        assert_eq!(
14008            modules
14009                .iter()
14010                .map(|entry| entry.module_id.as_str())
14011                .collect::<Vec<_>>(),
14012            vec!["aft"]
14013        );
14014        assert_eq!(generation, 1);
14015    }
14016
14017    /// While a HELLO has reserved its registry entry but its forwarding
14018    /// endpoint is not installed yet, `route.open` to the module can only be
14019    /// refused. `catalog.list` must not list the module in that window: a
14020    /// client that opens a route as soon as it sees a module listed and ready
14021    /// would be refused for a module the daemon had just advertised. The
14022    /// refusal in the window stays the retryable `target_unavailable`, never
14023    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14024    /// Once the HELLO completes, the module is listed and a route to it opens.
14025    #[tokio::test]
14026    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14027        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14028        let client = ConnectionId::new(41);
14029        let (client_ctx, mut client_rx) = route_ctx(client);
14030
14031        hold.wait();
14032        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14033        assert!(handler.registry.get_module("aft").unwrap().is_some());
14034        assert!(!handler
14035            .forwarding
14036            .has_live_module_connection("aft")
14037            .unwrap());
14038        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14039        assert!(
14040            listed.is_empty(),
14041            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14042        );
14043        let refused = handler
14044            .handle_control_frame(
14045                &client_ctx,
14046                route_open_frame(301, "aft", unique_project_root("listed-window")),
14047            )
14048            .await
14049            .unwrap();
14050        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14051        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14052        let duplicate = handler
14053            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14054            .await
14055            .unwrap();
14056        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14057
14058        hold.wait();
14059        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14060        let ack = module_rx.try_recv().unwrap().frame;
14061        assert_eq!(ack.header.ty, FrameType::HelloAck);
14062        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14063        assert_eq!(listed, vec![("aft".to_string(), true)]);
14064
14065        let (open_task, bind) = relay_route_open(
14066            &handler,
14067            client,
14068            &client_ctx.egress,
14069            &mut module_rx,
14070            303,
14071            "aft",
14072            "listed-after",
14073        )
14074        .await;
14075        assert!(handler
14076            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14077            .await
14078            .unwrap()
14079            .is_empty());
14080        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14081        published_route(&client_rx.try_recv().unwrap().frame);
14082    }
14083
14084    /// A catalog watcher keys on the generation: when it changes, it re-reads
14085    /// the listing. So the generation must advance exactly when the module
14086    /// appears. If it advanced while the module was still hidden, a watcher
14087    /// would read the new generation without the module, and the module would
14088    /// later appear under that same generation with nothing telling the
14089    /// watcher to look again.
14090    #[tokio::test]
14091    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14092        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14093        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14094        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14095
14096        hold.wait();
14097        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14098        assert!(listed.is_empty());
14099        assert_eq!(
14100            during, before,
14101            "the generation moved while the module was not listed"
14102        );
14103
14104        hold.wait();
14105        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14106        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14107        assert_eq!(listed, vec![("aft".to_string(), true)]);
14108        assert_eq!(
14109            after,
14110            before + 1,
14111            "the module appeared without exactly one generation bump"
14112        );
14113    }
14114
14115    /// A HELLO whose forwarding endpoint cannot be installed (here the
14116    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14117    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14118    /// and the catalog generation where it was.
14119    #[tokio::test]
14120    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14121        let registry = Arc::new(Registry::default());
14122        let handler = ControlHandler::with_forwarding(
14123            Arc::clone(&registry),
14124            Arc::new(ForwardingTable::default()),
14125        );
14126        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14127        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14128        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14129        drop(module_rx);
14130
14131        let replies = handler
14132            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14133            .await
14134            .unwrap();
14135        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14136        assert!(registry.get_module("aft").unwrap().is_none());
14137        assert!(registry
14138            .get_module_by_connection(module_ctx.connection_id)
14139            .unwrap()
14140            .is_none());
14141        assert_eq!(
14142            catalog_snapshot(&handler, &client_ctx, 301).await,
14143            (before, Vec::new())
14144        );
14145    }
14146
14147    /// A handler whose `route.open` parks after queueing the route.bind and
14148    /// before marking it enqueued, with module "aft" registered on connection
14149    /// 40. Returns the two-party barrier that parks and releases it.
14150    async fn route_open_held_after_bind_send() -> (
14151        ControlHandler,
14152        Arc<tokio::sync::Barrier>,
14153        RouteCtx,
14154        mpsc::Receiver<crate::router::OutboundFrame>,
14155    ) {
14156        let hold = Arc::new(tokio::sync::Barrier::new(2));
14157        let handler = ControlHandler::with_forwarding(
14158            Arc::new(Registry::default()),
14159            Arc::new(ForwardingTable::default()),
14160        )
14161        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14162        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14163        hello_via_sink(
14164            &handler,
14165            &module_ctx,
14166            &mut module_rx,
14167            hello_frame("aft", PROTOCOL_VERSION, 7),
14168        )
14169        .await;
14170        (handler, hold, module_ctx, module_rx)
14171    }
14172
14173    /// A fast module acks the route.bind, and the reader commits the route,
14174    /// before `route.open` has marked the relay enqueued. The daemon used to
14175    /// read the missing relay as an abandoned bind and send the module a
14176    /// GOODBYE for the route it had just committed: the client was told its
14177    /// route was open, the module unbound the channel, and the client's first
14178    /// request was dropped on the module side as unbound.
14179    #[tokio::test]
14180    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14181        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14182        let client = ConnectionId::new(41);
14183        let (client_ctx, mut client_rx) = route_ctx(client);
14184
14185        let (open_task, bind) = relay_route_open(
14186            &handler,
14187            client,
14188            &client_ctx.egress,
14189            &mut module_rx,
14190            200,
14191            "aft",
14192            "acked-before-mark",
14193        )
14194        .await;
14195        let (module_channel, module_epoch) = route_bind_channel(&bind);
14196        // route.open is now parked between queueing the bind and marking it.
14197        hold.wait().await;
14198
14199        // The module answers inside that window, and the route commits.
14200        assert!(handler
14201            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14202            .await
14203            .unwrap()
14204            .is_empty());
14205        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14206
14207        hold.wait().await;
14208        assert!(
14209            open_task.await.unwrap().is_empty(),
14210            "route.open answers accepted"
14211        );
14212
14213        // Every frame route.open could have sent is already queued, because it
14214        // has returned; the module must have been sent nothing.
14215        match module_rx.try_recv() {
14216            Err(mpsc::error::TryRecvError::Empty) => {}
14217            Ok(outbound) => panic!(
14218                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14219                outbound.frame.header.ty,
14220                outbound.frame.header.channel,
14221                outbound.frame.header.epoch
14222            ),
14223            Err(err) => panic!("module egress closed: {err}"),
14224        }
14225
14226        // The client's first request on the route is the next thing the module
14227        // reads, on the binding it just created.
14228        let router = Router::with_control_handler(Arc::new(handler.clone()));
14229        let request = Frame::build(
14230            FrameType::Request,
14231            Flags::new(true, Priority::Interactive, false),
14232            client_channel,
14233            client_epoch,
14234            201,
14235            b"first request".to_vec(),
14236        )
14237        .unwrap();
14238        router
14239            .route_for_connection(&client_ctx, request)
14240            .await
14241            .unwrap();
14242        let delivered = module_rx.try_recv().unwrap().frame;
14243        assert_eq!(delivered.header.ty, FrameType::Request);
14244        assert_eq!(
14245            (delivered.header.channel, delivered.header.epoch),
14246            (module_channel, module_epoch)
14247        );
14248        assert_eq!(delivered.body, b"first request");
14249    }
14250
14251    /// The client goes away while `route.open` is still queueing the bind, so
14252    /// the relay is dropped with no module reply. The teardown cannot send the
14253    /// GOODBYE itself (it could reach the module ahead of the bind), so
14254    /// `route.open` must send it once the bind is queued; otherwise the module
14255    /// keeps a binding the daemon will never commit.
14256    #[tokio::test]
14257    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14258        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14259        let client = ConnectionId::new(42);
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            300,
14268            "aft",
14269            "released-before-mark",
14270        )
14271        .await;
14272        let (module_channel, module_epoch) = route_bind_channel(&bind);
14273        hold.wait().await;
14274
14275        handler.cleanup_connection(client).unwrap();
14276        assert!(
14277            module_rx.try_recv().is_err(),
14278            "client teardown must not GOODBYE a bind route.open is still queueing"
14279        );
14280
14281        hold.wait().await;
14282        let response = open_task.await.unwrap();
14283        assert_eq!(response.len(), 1);
14284        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14285
14286        let goodbye = module_rx
14287            .try_recv()
14288            .expect("module is told to drop the binding the daemon abandoned")
14289            .frame;
14290        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14291        assert_eq!(
14292            (goodbye.header.channel, goodbye.header.epoch),
14293            (module_channel, module_epoch)
14294        );
14295        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14296    }
14297
14298    /// The module acks inside the same window, but the client's egress closed
14299    /// first, so the reader refuses to commit. The ack proves the module holds
14300    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14301    /// send a second one.
14302    #[tokio::test]
14303    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14304        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14305        let client = ConnectionId::new(43);
14306        let (client_ctx, client_rx) = route_ctx(client);
14307
14308        let (open_task, bind) = relay_route_open(
14309            &handler,
14310            client,
14311            &client_ctx.egress,
14312            &mut module_rx,
14313            400,
14314            "aft",
14315            "gone-client-before-mark",
14316        )
14317        .await;
14318        let (module_channel, module_epoch) = route_bind_channel(&bind);
14319        hold.wait().await;
14320
14321        drop(client_rx);
14322        assert!(client_ctx.egress.is_closed());
14323        handler
14324            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14325            .await
14326            .unwrap();
14327
14328        hold.wait().await;
14329        let response = open_task.await.unwrap();
14330        assert_eq!(response.len(), 1);
14331        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14332
14333        let goodbye = module_rx
14334            .try_recv()
14335            .expect("module is told to drop the binding it acked")
14336            .frame;
14337        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14338        assert_eq!(
14339            (goodbye.header.channel, goodbye.header.epoch),
14340            (module_channel, module_epoch)
14341        );
14342        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14343        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14344    }
14345
14346    /// The fence at the module-loop boundary, stated as its own contract: which
14347    /// forwarding failures are allowed to end the module connection that is being
14348    /// served. A `ConnectionClosing` naming some client is about that client, and
14349    /// a module connection is shared; the same error naming the module's own
14350    /// connection is about this connection and must stay fatal, as must failures
14351    /// that are about the forwarding table itself.
14352    #[test]
14353    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14354        let handler = ControlHandler::default();
14355        let module_connection = ConnectionId::new(30);
14356        let client_connection = ConnectionId::new(31);
14357
14358        handler
14359            .refuse_to_end_module_connection_for_a_client(
14360                module_connection,
14361                77,
14362                ForwardingError::ConnectionClosing {
14363                    connection_id: client_connection,
14364                },
14365            )
14366            .expect("a closing client must never end the module connection");
14367
14368        assert!(matches!(
14369            handler.refuse_to_end_module_connection_for_a_client(
14370                module_connection,
14371                78,
14372                ForwardingError::ConnectionClosing {
14373                    connection_id: module_connection,
14374                },
14375            ),
14376            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14377                connection_id
14378            })) if connection_id == module_connection
14379        ));
14380        assert!(matches!(
14381            handler.refuse_to_end_module_connection_for_a_client(
14382                module_connection,
14383                79,
14384                ForwardingError::Poisoned,
14385            ),
14386            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14387        ));
14388        assert!(matches!(
14389            handler.refuse_to_end_module_connection_for_a_client(
14390                module_connection,
14391                80,
14392                ForwardingError::StaleModuleEndpoint,
14393            ),
14394            Err(RouterError::Forwarding(
14395                ForwardingError::StaleModuleEndpoint
14396            ))
14397        ));
14398    }
14399
14400    /// The spawn-attestation guard is what stops a connected module from claiming
14401    /// another module's identity and being stamped `Reserved` for it. Every other
14402    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14403    /// correct one is what the rest of the flow needs -- so the guard's rejection
14404    /// branch was never the subject of an assertion, only its acceptance branch.
14405    ///
14406    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14407    /// whole subc-core library suite green; only the forwarding integration tests
14408    /// notice, and they notice for unrelated reasons. This test exists so the
14409    /// refusal itself is asserted where the guard lives: it fails if the identity
14410    /// check stops refusing, which is the direction that matters, since a guard
14411    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14412    #[tokio::test]
14413    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14414        let registry = Arc::new(Registry::default());
14415        let forwarding = Arc::new(ForwardingTable::default());
14416        let supervisor = SupervisorHandle::new();
14417        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14418        let handler =
14419            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14420                .with_supervisor(supervisor);
14421
14422        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14423        hello_via_sink(
14424            &handler,
14425            &target_ctx,
14426            &mut target_rx,
14427            hello_frame("target", PROTOCOL_VERSION, 1),
14428        )
14429        .await;
14430
14431        // A real supervised module id presenting the wrong nonce. This is the
14432        // impersonation case: the attacker knows a privileged module_id, which is
14433        // public, and guesses at the nonce, which is not.
14434        let wrong_nonce = handler
14435            .handle_control_frame(
14436                &route_ctx(ConnectionId::new(91)).0,
14437                route_open_frame_with_admission_facts(
14438                    20,
14439                    "target",
14440                    unique_project_root("admission-facts"),
14441                    Some(subc_control::ConsumerIdentity {
14442                        module_id: "fed".to_string(),
14443                        launch_nonce: "not-the-real-nonce".to_string(),
14444                    }),
14445                    None,
14446                ),
14447            )
14448            .await
14449            .unwrap();
14450        assert_eq!(
14451            parse_error(&wrong_nonce[0])["code"],
14452            "bad_consumer_identity",
14453            "a mismatched launch nonce must be refused, not stamped Reserved"
14454        );
14455
14456        // A module id the supervisor never spawned at all, so no nonce exists to
14457        // compare against. An implementation that treats "no record" as "nothing
14458        // to check" fails open here while passing the case above.
14459        let never_spawned = handler
14460            .handle_control_frame(
14461                &route_ctx(ConnectionId::new(92)).0,
14462                route_open_frame_with_admission_facts(
14463                    21,
14464                    "target",
14465                    unique_project_root("admission-facts"),
14466                    Some(subc_control::ConsumerIdentity {
14467                        module_id: "never-spawned".to_string(),
14468                        launch_nonce: "any-nonce".to_string(),
14469                    }),
14470                    None,
14471                ),
14472            )
14473            .await
14474            .unwrap();
14475        assert_eq!(
14476            parse_error(&never_spawned[0])["code"],
14477            "bad_consumer_identity",
14478            "an unspawned module_id must be refused rather than accepted for lack of a record"
14479        );
14480    }
14481
14482    /// The refusal test above proves the guard says NO. Nothing proved it can say
14483    /// YES, and the difference is not academic: replacing the whole authorization
14484    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14485    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14486    /// library tests GREEN. The one that notices does so by HANGING, because it
14487    /// waits for a bind that can no longer happen.
14488    ///
14489    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14490    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14491    /// hangs too and gets blamed on the runner. So a total revocation of the
14492    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14493    /// to code.
14494    ///
14495    /// The bias is structural rather than accidental. A REFUSAL looks like a
14496    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14497    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14498    /// suite for that reason, and this one is the purest case in the daemon.
14499    ///
14500    /// This test asserts the EFFECT rather than the absence of an error: the module
14501    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14502    /// A guard that admitted nobody would produce no bind at all; one that admitted
14503    /// everybody would stamp the wrong principal, which the refusal test catches.
14504    #[tokio::test]
14505    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14506        let registry = Arc::new(Registry::default());
14507        let forwarding = Arc::new(ForwardingTable::default());
14508        let supervisor = SupervisorHandle::new();
14509        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14510        let handler =
14511            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14512                .with_supervisor(supervisor);
14513
14514        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14515        hello_via_sink(
14516            &handler,
14517            &target_ctx,
14518            &mut target_rx,
14519            hello_frame("target", PROTOCOL_VERSION, 1),
14520        )
14521        .await;
14522
14523        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14524        let route_handler = handler.clone();
14525        let route_task = tokio::spawn(async move {
14526            route_handler
14527                .handle_control_frame(
14528                    &client_ctx,
14529                    route_open_frame_with_admission_facts(
14530                        30,
14531                        "target",
14532                        unique_project_root("admission-facts"),
14533                        Some(subc_control::ConsumerIdentity {
14534                            module_id: "fed".to_string(),
14535                            launch_nonce: "fed-nonce".to_string(),
14536                        }),
14537                        None,
14538                    ),
14539                )
14540                .await
14541                .unwrap()
14542        });
14543
14544        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14545        // the very mutation it exists to catch -- a guard that admits nobody -- no
14546        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14547        // exact defect being fixed: a total revocation detected only as a stalled
14548        // suite, which reads as flakiness and invites a retry. An acceptance test
14549        // that waits for an effect must bound the wait, or a red becomes a hang.
14550        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14551            .await
14552            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14553            .expect("module control channel closed before route.bind");
14554        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14555        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14556            panic!("expected route.bind")
14557        };
14558        assert_eq!(
14559            principal,
14560            Some(Principal::Reserved {
14561                module_id: "fed".to_string()
14562            }),
14563            "a correctly attested consumer must be stamped Reserved for its own id"
14564        );
14565
14566        handler
14567            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14568            .await
14569            .unwrap();
14570        assert!(route_task.await.unwrap().is_empty());
14571        assert!(
14572            matches!(
14573                serde_json::from_slice::<ClientControlResponse>(
14574                    &client_rx.recv().await.unwrap().body
14575                )
14576                .unwrap(),
14577                ClientControlResponse::RouteOpen { .. }
14578            ),
14579            "the route must actually open, not merely avoid an error"
14580        );
14581    }
14582
14583    #[tokio::test(start_paused = true)]
14584    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14585        let registry = Arc::new(Registry::default());
14586        let forwarding = Arc::new(ForwardingTable::default());
14587        let supervisor = SupervisorHandle::new();
14588        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14589        let handler =
14590            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14591                .with_supervisor(supervisor);
14592
14593        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14594        hello_via_sink(
14595            &handler,
14596            &target_ctx,
14597            &mut target_rx,
14598            hello_frame("target", PROTOCOL_VERSION, 1),
14599        )
14600        .await;
14601
14602        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14603        let direct_handler = handler.clone();
14604        let direct_open = tokio::spawn(async move {
14605            direct_handler
14606                .handle_control_frame(
14607                    &direct_ctx,
14608                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14609                )
14610                .await
14611                .unwrap()
14612        });
14613        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14614            .await
14615            .expect("no direct route.bind within 5s")
14616            .expect("target control channel closed before direct route.bind");
14617        handler
14618            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14619            .await
14620            .unwrap();
14621        assert!(direct_open.await.unwrap().is_empty());
14622        let _ = direct_rx.recv().await.unwrap();
14623
14624        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14625        let reserved_handler = handler.clone();
14626        let reserved_open = tokio::spawn(async move {
14627            reserved_handler
14628                .handle_control_frame(
14629                    &reserved_ctx,
14630                    route_open_frame_with_admission_facts(
14631                        3,
14632                        "target",
14633                        unique_project_root("admission-facts"),
14634                        Some(ConsumerIdentity {
14635                            module_id: "fed".to_string(),
14636                            launch_nonce: "fed-nonce".to_string(),
14637                        }),
14638                        None,
14639                    ),
14640                )
14641                .await
14642                .unwrap()
14643        });
14644        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14645            .await
14646            .expect("no reserved route.bind within 5s")
14647            .expect("target control channel closed before reserved route.bind");
14648        handler
14649            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14650            .await
14651            .unwrap();
14652        assert!(reserved_open.await.unwrap().is_empty());
14653        let _ = reserved_rx.recv().await.unwrap();
14654
14655        forwarding
14656            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14657            .unwrap();
14658        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14659        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14660            module_id: Some("target".to_string()),
14661        })
14662        .unwrap();
14663        let census_frame =
14664            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14665        let response = handler
14666            .handle_control_frame(&census_ctx, census_frame)
14667            .await
14668            .unwrap()
14669            .pop()
14670            .unwrap();
14671        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14672        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14673        assert!(matches!(
14674            decoded,
14675            ClientControlResponse::SupervisorRoutes { .. }
14676        ));
14677        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14678        assert_eq!(routes.len(), 2);
14679        assert!(routes.iter().all(|route| route["draining"] == true));
14680        // The census carries WHY: the reason the drain was begun with, in the
14681        // route.closing vocabulary, on every draining route this drain marked.
14682        assert!(
14683            routes.iter().all(|route| route["drain_reason"] == "reload"),
14684            "draining routes must name the drain's reason: {routes:?}"
14685        );
14686        assert!(routes.iter().any(|route| {
14687            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14688        }));
14689        assert!(routes.iter().any(|route| {
14690            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14691        }));
14692
14693        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14694            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14695        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14696            std::fs::write(
14697                &golden_path,
14698                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14699            )
14700            .unwrap();
14701        }
14702        let expected: Value =
14703            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14704        assert_eq!(actual, expected);
14705    }
14706
14707    async fn query_live_roots(
14708        handler: &ControlHandler,
14709        module_ctx: &RouteCtx,
14710    ) -> ModuleControlResponseToModule {
14711        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14712        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14713        let response = handler
14714            .handle_control_frame(module_ctx, frame)
14715            .await
14716            .unwrap()
14717            .pop()
14718            .unwrap();
14719        serde_json::from_slice(&response.body).unwrap()
14720    }
14721
14722    #[tokio::test(start_paused = true)]
14723    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14724        let registry = Arc::new(Registry::default());
14725        let forwarding = Arc::new(ForwardingTable::default());
14726        let handler = ControlHandler::with_forwarding(registry, forwarding);
14727        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14728        hello_via_sink(
14729            &handler,
14730            &target_ctx,
14731            &mut target_rx,
14732            hello_frame("target", PROTOCOL_VERSION, 1),
14733        )
14734        .await;
14735        let root = unique_project_root("live-roots-known");
14736        let path = ProjectRootId::from_path_allowing_missing(root.path())
14737            .unwrap()
14738            .as_path()
14739            .to_path_buf();
14740        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14741        let open_handler = handler.clone();
14742        let opened = tokio::spawn(async move {
14743            open_handler
14744                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14745                .await
14746                .unwrap()
14747        });
14748        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14749            .await
14750            .unwrap()
14751            .unwrap();
14752        handler
14753            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14754            .await
14755            .unwrap();
14756        assert!(opened.await.unwrap().is_empty());
14757        let _ = client_rx.recv().await.unwrap();
14758
14759        let root = unique_project_root("live-roots-pending");
14760        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14761            .unwrap()
14762            .as_path()
14763            .to_path_buf();
14764        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14765        let open_handler = handler.clone();
14766        let pending = tokio::spawn(async move {
14767            open_handler
14768                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14769                .await
14770                .unwrap()
14771        });
14772        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14773            .await
14774            .unwrap()
14775            .unwrap();
14776        let actual = query_live_roots(&handler, &target_ctx).await;
14777        let ModuleControlResponseToModule::LiveRoots {
14778            roots,
14779            unknown_root_bindings,
14780            total_bindings,
14781        } = actual
14782        else {
14783            panic!("expected live roots")
14784        };
14785        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14786        assert_eq!(unknown_root_bindings, 0);
14787        assert_eq!(
14788            roots.len(),
14789            2,
14790            "root-known arm must retain each canonical root"
14791        );
14792        assert_eq!(
14793            total_bindings,
14794            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14795        );
14796        let counts = roots
14797            .iter()
14798            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14799            .collect::<Vec<_>>();
14800        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14801        expected.sort_by(|a, b| a.0.cmp(&b.0));
14802        assert_eq!(
14803            counts, expected,
14804            "roots must sort by path and count pending separately"
14805        );
14806        handler
14807            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14808            .await
14809            .unwrap();
14810        assert!(pending.await.unwrap().is_empty());
14811    }
14812
14813    #[tokio::test(start_paused = true)]
14814    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14815        let forwarding = Arc::new(ForwardingTable::default());
14816        let handler =
14817            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14818        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14819        hello_via_sink(
14820            &handler,
14821            &target_ctx,
14822            &mut target_rx,
14823            hello_frame("target", PROTOCOL_VERSION, 1),
14824        )
14825        .await;
14826        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14827        let pending = forwarding
14828            .begin_route_bind_relay_for_test(
14829                client_ctx.connection_id,
14830                client_ctx.egress.clone(),
14831                2,
14832                "target",
14833            )
14834            .unwrap();
14835        forwarding
14836            .complete_pending_relay(
14837                target_ctx.connection_id,
14838                pending.corr,
14839                RouteBindRelayOutcome::Accepted,
14840            )
14841            .unwrap();
14842        let actual = query_live_roots(&handler, &target_ctx).await;
14843        let ModuleControlResponseToModule::LiveRoots {
14844            roots,
14845            unknown_root_bindings,
14846            total_bindings,
14847        } = actual
14848        else {
14849            panic!("expected live roots")
14850        };
14851        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14852        assert_eq!(
14853            unknown_root_bindings, 1,
14854            "unknown-root arm must not read as no bindings"
14855        );
14856        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14857        assert_eq!(
14858            total_bindings,
14859            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14860        );
14861    }
14862
14863    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14864    /// so the ack has to be on its outbound queue before the module is
14865    /// routable. The connection loop writes a handler's replies only after the
14866    /// handler returns; this test stops in exactly that gap, runs a real
14867    /// route.open from another connection, and only then writes whatever the
14868    /// HELLO handler returned, the way the loop would. If the ack were still a
14869    /// reply, the route.bind request would reach the module first.
14870    #[tokio::test(start_paused = true)]
14871    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14872        let forwarding = Arc::new(ForwardingTable::default());
14873        let handler =
14874            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14875        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14876        let replies = handler
14877            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14878            .await
14879            .unwrap();
14880        let queued_by_hello = module_rx.len();
14881
14882        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14883        let open_handler = handler.clone();
14884        let open = tokio::spawn(async move {
14885            open_handler
14886                .handle_control_frame(
14887                    &client_ctx,
14888                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14889                )
14890                .await
14891                .unwrap()
14892        });
14893        // Let the route.open run until its route.bind is on the module's queue.
14894        let mut spins = 0;
14895        while module_rx.len() == queued_by_hello {
14896            spins += 1;
14897            assert!(spins < 10_000, "route.open never queued a route.bind");
14898            tokio::task::yield_now().await;
14899        }
14900
14901        // Now the connection loop's half: write the HELLO handler's replies.
14902        for reply in replies {
14903            module_ctx.egress.send(reply).await.unwrap();
14904        }
14905
14906        let first = module_rx.recv().await.unwrap().frame;
14907        assert_eq!(
14908            first.header.ty,
14909            FrameType::HelloAck,
14910            "the first frame a registering module reads must be its HELLO_ACK"
14911        );
14912        assert_eq!(first.header.corr, 7);
14913        let second = module_rx.recv().await.unwrap().frame;
14914        assert_eq!(second.header.ty, FrameType::Request);
14915        assert!(
14916            matches!(
14917                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
14918                ModuleControlRequest::RouteBind { .. }
14919            ),
14920            "the route.bind follows the ack"
14921        );
14922        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
14923
14924        handler
14925            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
14926            .await
14927            .unwrap();
14928        assert!(open.await.unwrap().is_empty());
14929        let _ = client_rx.recv().await.unwrap();
14930    }
14931
14932    #[tokio::test(start_paused = true)]
14933    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
14934        let handler = ControlHandler::with_forwarding(
14935            Arc::new(Registry::default()),
14936            Arc::new(ForwardingTable::default()),
14937        );
14938        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
14939        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
14940        hello_via_sink(
14941            &handler,
14942            &first_ctx,
14943            &mut first_rx,
14944            hello_frame("first", PROTOCOL_VERSION, 1),
14945        )
14946        .await;
14947        hello_via_sink(
14948            &handler,
14949            &second_ctx,
14950            &mut second_rx,
14951            hello_frame("second", PROTOCOL_VERSION, 2),
14952        )
14953        .await;
14954        let root = unique_project_root("second-only");
14955        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
14956        let cloned = handler.clone();
14957        let open = tokio::spawn(async move {
14958            cloned
14959                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
14960                .await
14961                .unwrap()
14962        });
14963        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
14964            .await
14965            .unwrap()
14966            .unwrap();
14967        let first = query_live_roots(&handler, &first_ctx).await;
14968        let second = query_live_roots(&handler, &second_ctx).await;
14969        assert!(
14970            matches!(
14971                first,
14972                ModuleControlResponseToModule::LiveRoots {
14973                    total_bindings: 0,
14974                    ..
14975                }
14976            ),
14977            "cross-module scope must not expose another module's roots"
14978        );
14979        assert!(
14980            matches!(
14981                second,
14982                ModuleControlResponseToModule::LiveRoots {
14983                    total_bindings: 1,
14984                    ..
14985                }
14986            ),
14987            "second module must see its pending route"
14988        );
14989        handler
14990            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
14991            .await
14992            .unwrap();
14993        assert!(open.await.unwrap().is_empty());
14994    }
14995
14996    #[tokio::test(start_paused = true)]
14997    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
14998        let handler = ControlHandler::with_forwarding(
14999            Arc::new(Registry::default()),
15000            Arc::new(ForwardingTable::default()),
15001        );
15002        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15003        hello_via_sink(
15004            &handler,
15005            &target_ctx,
15006            &mut target_rx,
15007            hello_frame("target", PROTOCOL_VERSION, 1),
15008        )
15009        .await;
15010        let actual = query_live_roots(&handler, &target_ctx).await;
15011        let ModuleControlResponseToModule::LiveRoots {
15012            roots,
15013            unknown_root_bindings,
15014            total_bindings,
15015        } = actual
15016        else {
15017            panic!("expected live roots")
15018        };
15019        assert!(roots.is_empty());
15020        assert_eq!(unknown_root_bindings, 0);
15021        assert_eq!(total_bindings, 0);
15022        assert_eq!(
15023            total_bindings,
15024            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15025        );
15026    }
15027
15028    /// Read the vendored fed corpus rather than hand-building a package.
15029    ///
15030    /// A hand-built object encodes what the test author believed the carrier
15031    /// emits. These vectors are what it actually emits, and one of them exists
15032    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15033    /// ignores additive unknown fields at the traversal emit terminus."
15034    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15035        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15036            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15037        let text = std::fs::read_to_string(&path)
15038            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15039        let vectors: Vec<(String, Value)> = text
15040            .lines()
15041            .filter(|line| !line.trim().is_empty())
15042            .map(|line| {
15043                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15044                let id = entry["corpus_id"]
15045                    .as_str()
15046                    .expect("every vector carries a corpus_id")
15047                    .to_string();
15048                (id, entry["package"].clone())
15049            })
15050            .collect();
15051        // Pin the count: a corpus that silently shrinks would take its coverage
15052        // with it, and a suite reading N-1 vectors reports the same clean pass
15053        // as one reading N.
15054        assert_eq!(
15055            vectors.len(),
15056            3,
15057            "vendored fed corpus changed size; re-sync from subc-federation"
15058        );
15059
15060        // Pin what makes the corpus DISCRIMINATING, not just present.
15061        //
15062        // The relay test below takes its expected value from the corpus, so the
15063        // corpus supplies the test's power to detect a lossy relay rather than
15064        // its correctness. A relay that dropped unrecognised fields would still
15065        // be caught -- but only by a package carrying fields it does not know.
15066        // Shrink every package to the handful of keys any implementation would
15067        // recognise and the test keeps passing over an input that can no longer
15068        // fail, which is the same clean green as a corpus that shrank away.
15069        //
15070        // So assert the precondition rather than duplicating the packages here:
15071        // at least one vector must carry a field beyond the small common set.
15072        // That is one claim to maintain instead of nine, and it fails loudly if
15073        // a re-sync ever flattens the corpus.
15074        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15075        let richest = vectors
15076            .iter()
15077            .filter_map(|(_, package)| package.as_object())
15078            .map(|object| {
15079                object
15080                    .keys()
15081                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15082                    .count()
15083            })
15084            .max()
15085            .unwrap_or(0);
15086        assert!(
15087            richest >= 2,
15088            "vendored corpus no longer carries a package with unmodelled fields, \
15089             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15090        );
15091
15092        vectors
15093    }
15094
15095    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15096    ///
15097    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15098    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15099    /// three-key object, so a relay that quietly dropped fields it did not
15100    /// recognise would satisfy it. These vectors carry nine keys including ones
15101    /// this crate has no type for, so a typed relay fails here and only here.
15102    #[tokio::test]
15103    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15104        for (corpus_id, package) in fed_admission_facts_vectors() {
15105            let registry = Arc::new(Registry::default());
15106            let forwarding = Arc::new(ForwardingTable::default());
15107            let supervisor = SupervisorHandle::new();
15108            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15109            let handler =
15110                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15111                    .with_supervisor(supervisor)
15112                    .with_admission_facts_config(
15113                        Some("fed".to_string()),
15114                        Some(vec!["target".to_string()]),
15115                    );
15116
15117            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15118            hello_via_sink(
15119                &handler,
15120                &target_ctx,
15121                &mut target_rx,
15122                hello_frame("target", PROTOCOL_VERSION, 1),
15123            )
15124            .await;
15125
15126            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15127            let route_handler = handler.clone();
15128            let expected = package.clone();
15129            let route_task = tokio::spawn(async move {
15130                route_handler
15131                    .handle_control_frame(
15132                        &client_ctx,
15133                        route_open_frame_with_admission_facts(
15134                            20,
15135                            "target",
15136                            unique_project_root("admission-facts"),
15137                            Some(subc_control::ConsumerIdentity {
15138                                module_id: "fed".to_string(),
15139                                launch_nonce: "fed-nonce".to_string(),
15140                            }),
15141                            Some(package),
15142                        ),
15143                    )
15144                    .await
15145                    .unwrap()
15146            });
15147
15148            let bind_frame = target_rx.recv().await.unwrap();
15149            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15150            let ModuleControlRequest::RouteBind {
15151                admission_facts, ..
15152            } = bind
15153            else {
15154                panic!("{corpus_id}: expected route.bind")
15155            };
15156            assert_eq!(
15157                admission_facts,
15158                Some(expected),
15159                "{corpus_id}: relay must not add, drop or reshape any field"
15160            );
15161
15162            handler
15163                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15164                .await
15165                .unwrap();
15166            route_task.await.unwrap();
15167        }
15168    }
15169
15170    #[tokio::test]
15171    async fn route_bind_never_relays_the_openers_build_class() {
15172        let registry = Arc::new(Registry::default());
15173        let forwarding = Arc::new(ForwardingTable::default());
15174        let handler =
15175            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15176        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15177        hello_via_sink(
15178            &handler,
15179            &target_ctx,
15180            &mut target_rx,
15181            hello_frame("target", PROTOCOL_VERSION, 1),
15182        )
15183        .await;
15184
15185        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15186        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15187        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15188            busy_refusals: None,
15189            target: RouteTarget::ToolProvider {
15190                module_id: "target".to_string(),
15191            },
15192            identity,
15193            consumer_identity: None,
15194            consumer_capabilities: None,
15195            role_versions: None,
15196            admission_facts: None,
15197            scope: None,
15198        })
15199        .unwrap();
15200        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15201
15202        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15203        let route_handler = handler.clone();
15204        let route_task = tokio::spawn(async move {
15205            route_handler
15206                .handle_control_frame(&client_ctx, open)
15207                .await
15208                .unwrap()
15209        });
15210        let bind_frame = target_rx.recv().await.unwrap();
15211        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15212        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15213            panic!("expected route.bind")
15214        };
15215        assert_eq!(
15216            identity.build_class, None,
15217            "route.bind carried the build class"
15218        );
15219        assert!(
15220            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15221            "the route.bind bytes still name build_class"
15222        );
15223        handler
15224            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15225            .await
15226            .unwrap();
15227        route_task.await.unwrap();
15228    }
15229
15230    #[tokio::test]
15231    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15232        let registry = Arc::new(Registry::default());
15233        let forwarding = Arc::new(ForwardingTable::default());
15234        let supervisor = SupervisorHandle::new();
15235        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15236        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15237        let handler =
15238            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15239                .with_supervisor(supervisor)
15240                .with_admission_facts_config(
15241                    Some("fed".to_string()),
15242                    Some(vec!["target".to_string()]),
15243                );
15244
15245        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15246        hello_via_sink(
15247            &handler,
15248            &target_ctx,
15249            &mut target_rx,
15250            hello_frame("target", PROTOCOL_VERSION, 1),
15251        )
15252        .await;
15253        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15254        hello_via_sink(
15255            &handler,
15256            &other_ctx,
15257            &mut other_rx,
15258            hello_frame("other", PROTOCOL_VERSION, 2),
15259        )
15260        .await;
15261
15262        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15263        let expected_facts = facts.clone();
15264        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15265        let route_handler = handler.clone();
15266        let route_task = tokio::spawn(async move {
15267            route_handler
15268                .handle_control_frame(
15269                    &client_ctx,
15270                    route_open_frame_with_admission_facts(
15271                        10,
15272                        "target",
15273                        unique_project_root("admission-facts"),
15274                        Some(subc_control::ConsumerIdentity {
15275                            module_id: "fed".to_string(),
15276                            launch_nonce: "fed-nonce".to_string(),
15277                        }),
15278                        Some(facts.clone()),
15279                    ),
15280                )
15281                .await
15282                .unwrap()
15283        });
15284        let bind_frame = target_rx.recv().await.unwrap();
15285        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15286        let ModuleControlRequest::RouteBind {
15287            admission_facts, ..
15288        } = bind
15289        else {
15290            panic!("expected route.bind")
15291        };
15292        assert_eq!(admission_facts, Some(expected_facts));
15293        handler
15294            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15295            .await
15296            .unwrap();
15297        assert!(route_task.await.unwrap().is_empty());
15298        assert!(matches!(
15299            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15300                .unwrap(),
15301            ClientControlResponse::RouteOpen { .. }
15302        ));
15303
15304        let direct = handler
15305            .handle_control_frame(
15306                &route_ctx(ConnectionId::new(73)).0,
15307                route_open_frame_with_admission_facts(
15308                    11,
15309                    "target",
15310                    unique_project_root("admission-facts"),
15311                    None,
15312                    Some(json!({"x": 1})),
15313                ),
15314            )
15315            .await
15316            .unwrap();
15317        assert_eq!(
15318            parse_error(&direct[0])["code"],
15319            "admission_facts_not_permitted"
15320        );
15321
15322        let different_reserved = handler
15323            .handle_control_frame(
15324                &route_ctx(ConnectionId::new(77)).0,
15325                route_open_frame_with_admission_facts(
15326                    15,
15327                    "target",
15328                    unique_project_root("admission-facts"),
15329                    Some(subc_control::ConsumerIdentity {
15330                        module_id: "other".to_string(),
15331                        launch_nonce: "other-nonce".to_string(),
15332                    }),
15333                    Some(json!({"x": 1})),
15334                ),
15335            )
15336            .await
15337            .unwrap();
15338        assert_eq!(
15339            parse_error(&different_reserved[0])["code"],
15340            "admission_facts_not_permitted"
15341        );
15342
15343        let other_target = handler
15344            .handle_control_frame(
15345                &route_ctx(ConnectionId::new(74)).0,
15346                route_open_frame_with_admission_facts(
15347                    12,
15348                    "other",
15349                    unique_project_root("admission-facts"),
15350                    Some(subc_control::ConsumerIdentity {
15351                        module_id: "fed".to_string(),
15352                        launch_nonce: "fed-nonce".to_string(),
15353                    }),
15354                    Some(json!({"x": 1})),
15355                ),
15356            )
15357            .await
15358            .unwrap();
15359        assert_eq!(
15360            parse_error(&other_target[0])["code"],
15361            "admission_facts_target_not_allowed"
15362        );
15363
15364        let nonexistent = handler
15365            .handle_control_frame(
15366                &route_ctx(ConnectionId::new(75)).0,
15367                route_open_frame_with_admission_facts(
15368                    13,
15369                    "missing",
15370                    unique_project_root("admission-facts"),
15371                    None,
15372                    Some(json!({"x": 1})),
15373                ),
15374            )
15375            .await
15376            .unwrap();
15377        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15378
15379        let described = handler
15380            .handle_control_frame(
15381                &route_ctx(ConnectionId::new(76)).0,
15382                Frame::build(
15383                    FrameType::Request,
15384                    control_flags(),
15385                    0,
15386                    0,
15387                    14,
15388                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15389                )
15390                .unwrap(),
15391            )
15392            .await
15393            .unwrap();
15394        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15395            serde_json::from_slice(&described[0].body).unwrap()
15396        else {
15397            panic!("expected server.describe response")
15398        };
15399        assert!(capabilities
15400            .iter()
15401            .any(|cap| cap == "admission_facts_relay_v1"));
15402    }
15403
15404    #[tokio::test]
15405    async fn admission_facts_without_configured_carrier_are_rejected() {
15406        let registry = Arc::new(Registry::default());
15407        let forwarding = Arc::new(ForwardingTable::default());
15408        let handler = ControlHandler::with_forwarding(registry, forwarding);
15409        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15410        hello_via_sink(
15411            &handler,
15412            &target_ctx,
15413            &mut target_rx,
15414            hello_frame("target", PROTOCOL_VERSION, 1),
15415        )
15416        .await;
15417
15418        let responses = handler
15419            .handle_control_frame(
15420                &route_ctx(ConnectionId::new(79)).0,
15421                route_open_frame_with_admission_facts(
15422                    16,
15423                    "target",
15424                    unique_project_root("admission-facts"),
15425                    None,
15426                    Some(json!({"x": 1})),
15427                ),
15428            )
15429            .await
15430            .unwrap();
15431        assert_eq!(
15432            parse_error(&responses[0])["code"],
15433            "admission_facts_not_permitted"
15434        );
15435    }
15436
15437    #[tokio::test]
15438    async fn route_open_relays_consumer_capabilities_verbatim() {
15439        let registry = Arc::new(Registry::default());
15440        let forwarding = Arc::new(ForwardingTable::default());
15441        let handler =
15442            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15443        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15444        hello_via_sink(
15445            &handler,
15446            &module_ctx,
15447            &mut module_rx,
15448            hello_frame("aft", PROTOCOL_VERSION, 7),
15449        )
15450        .await;
15451
15452        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15453        let expected_for_request = expected.clone();
15454        let project_root = unique_project_root("consumer-capabilities-present");
15455        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15456        let route_handler = handler.clone();
15457        let route_task = tokio::spawn(async move {
15458            route_handler
15459                .handle_control_frame(
15460                    &client_ctx,
15461                    route_open_frame_with_consumer_capabilities(
15462                        401,
15463                        "aft",
15464                        project_root,
15465                        Some(expected_for_request),
15466                    ),
15467                )
15468                .await
15469                .unwrap()
15470        });
15471        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15472            .await
15473            .unwrap()
15474            .unwrap();
15475        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15476        let ModuleControlRequest::RouteBind {
15477            consumer_capabilities,
15478            ..
15479        } = bind
15480        else {
15481            panic!("expected route.bind request, got {bind:?}");
15482        };
15483        assert_eq!(consumer_capabilities, Some(expected.clone()));
15484
15485        handler
15486            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15487            .await
15488            .unwrap();
15489        let route_response = route_task.await.unwrap();
15490        assert!(route_response.is_empty());
15491        let published = client_rx.recv().await.unwrap();
15492        assert!(matches!(
15493            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15494            ClientControlResponse::RouteOpen { .. }
15495        ));
15496    }
15497
15498    #[tokio::test]
15499    async fn route_open_without_consumer_capabilities_relays_none() {
15500        let registry = Arc::new(Registry::default());
15501        let forwarding = Arc::new(ForwardingTable::default());
15502        let handler =
15503            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15504        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15505        hello_via_sink(
15506            &handler,
15507            &module_ctx,
15508            &mut module_rx,
15509            hello_frame("aft", PROTOCOL_VERSION, 7),
15510        )
15511        .await;
15512
15513        let project_root = unique_project_root("consumer-capabilities-absent");
15514        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15515        let route_handler = handler.clone();
15516        let route_task = tokio::spawn(async move {
15517            route_handler
15518                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15519                .await
15520                .unwrap()
15521        });
15522        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15523            .await
15524            .unwrap()
15525            .unwrap();
15526        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15527        let ModuleControlRequest::RouteBind {
15528            consumer_capabilities,
15529            ..
15530        } = bind
15531        else {
15532            panic!("expected route.bind request, got {bind:?}");
15533        };
15534        assert_eq!(consumer_capabilities, None);
15535
15536        handler
15537            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15538            .await
15539            .unwrap();
15540        let route_response = route_task.await.unwrap();
15541        assert!(route_response.is_empty());
15542        let published = client_rx.recv().await.unwrap();
15543        assert!(matches!(
15544            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15545            ClientControlResponse::RouteOpen { .. }
15546        ));
15547    }
15548
15549    /// Opens a route to a freshly registered `aft` with `sent` as the
15550    /// route.open's role_versions, acks the bind, and returns the role_versions
15551    /// the module's bind carried.
15552    async fn bind_role_versions_for(
15553        sent: Option<BTreeMap<String, String>>,
15554        connection: u64,
15555    ) -> Option<BTreeMap<String, String>> {
15556        let registry = Arc::new(Registry::default());
15557        let forwarding = Arc::new(ForwardingTable::default());
15558        let handler =
15559            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15560        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15561        hello_via_sink(
15562            &handler,
15563            &module_ctx,
15564            &mut module_rx,
15565            hello_frame("aft", PROTOCOL_VERSION, 7),
15566        )
15567        .await;
15568        let project_root = unique_project_root("role-versions");
15569        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15570        let route_handler = handler.clone();
15571        let route_task = tokio::spawn(async move {
15572            route_handler
15573                .handle_control_frame(
15574                    &client_ctx,
15575                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15576                )
15577                .await
15578                .unwrap()
15579        });
15580        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15581            .await
15582            .expect("a well-formed route.open reaches the module as a bind")
15583            .unwrap();
15584        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15585        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15586            panic!("expected route.bind request, got {bind:?}");
15587        };
15588        handler
15589            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15590            .await
15591            .unwrap();
15592        assert!(route_task.await.unwrap().is_empty());
15593        let published = client_rx.recv().await.unwrap();
15594        assert!(matches!(
15595            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15596            ClientControlResponse::RouteOpen { .. }
15597        ));
15598        role_versions
15599    }
15600
15601    #[tokio::test]
15602    async fn route_open_relays_role_versions_verbatim() {
15603        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15604        assert_eq!(
15605            bind_role_versions_for(Some(sent.clone()), 141).await,
15606            Some(sent)
15607        );
15608    }
15609
15610    /// An empty map declares nothing, so the provider sees no field rather
15611    /// than an empty object it would have to treat as a second "none".
15612    #[tokio::test]
15613    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15614        assert_eq!(bind_role_versions_for(None, 143).await, None);
15615        assert_eq!(
15616            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15617            None
15618        );
15619    }
15620
15621    #[tokio::test]
15622    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15623        let registry = Arc::new(Registry::default());
15624        let forwarding = Arc::new(ForwardingTable::default());
15625        let handler =
15626            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15627        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15628        hello_via_sink(
15629            &handler,
15630            &module_ctx,
15631            &mut module_rx,
15632            hello_frame("aft", PROTOCOL_VERSION, 7),
15633        )
15634        .await;
15635
15636        let nine: BTreeMap<String, String> = (0..9)
15637            .map(|index| (format!("role-{index}"), "v1".to_string()))
15638            .collect();
15639        for (label, malformed) in [
15640            (
15641                "invalid role name",
15642                role_versions(&[("Tool_Provider", "v1")]),
15643            ),
15644            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15645            ("nine entries", nine),
15646        ] {
15647            // A refused open answers at once; one that reached the module
15648            // would wait for its bind ack and trip this timeout.
15649            let responses = tokio::time::timeout(
15650                Duration::from_secs(1),
15651                handler.handle_control_frame(
15652                    &route_ctx(ConnectionId::new(148)).0,
15653                    route_open_frame_with_role_versions(
15654                        404,
15655                        "aft",
15656                        unique_project_root("role-versions-malformed"),
15657                        Some(malformed),
15658                    ),
15659                ),
15660            )
15661            .await
15662            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15663            .unwrap();
15664            assert_eq!(responses.len(), 1, "{label}");
15665            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15666            let error = parse_error(&responses[0]);
15667            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15668            assert_eq!(
15669                error["detail"]["field"], "role_versions",
15670                "{label}: {error}"
15671            );
15672            assert!(
15673                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15674                "{label}: a malformed declaration is terminal"
15675            );
15676            assert!(
15677                module_rx.try_recv().is_err(),
15678                "{label}: the module must never see a bind"
15679            );
15680        }
15681    }
15682
15683    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15684    /// consumer can tell this daemon forwards the field from one that would
15685    /// drop it.
15686    #[tokio::test]
15687    async fn route_role_versions_capability_is_advertised() {
15688        let handler = ControlHandler::new(Arc::new(Registry::default()));
15689        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15690        let ack = hello_via_sink(
15691            &handler,
15692            &ctx,
15693            &mut rx,
15694            hello_frame("m", PROTOCOL_VERSION, 1),
15695        )
15696        .await;
15697        let ack = parse_ack(&ack);
15698        assert!(
15699            ack.subc_capabilities
15700                .iter()
15701                .any(|c| c == "route-role-versions/v1"),
15702            "{:?}",
15703            ack.subc_capabilities
15704        );
15705
15706        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15707        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15708        let reply = handler
15709            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15710            .await
15711            .unwrap()
15712            .pop()
15713            .unwrap();
15714        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15715            serde_json::from_slice(&reply.body).unwrap()
15716        else {
15717            panic!("not a server.describe reply");
15718        };
15719        assert!(
15720            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15721            "{capabilities:?}"
15722        );
15723    }
15724
15725    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15726    /// catalog entry without `events` (the module declares none) from a daemon
15727    /// that never reports declared events.
15728    #[tokio::test]
15729    async fn catalog_events_capability_is_advertised() {
15730        let handler = ControlHandler::new(Arc::new(Registry::default()));
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(&route_ctx(ConnectionId::new(151)).0, 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_CATALOG_EVENTS_V1),
15748            "{capabilities:?}"
15749        );
15750    }
15751
15752    #[tokio::test]
15753    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15754        let handler = ControlHandler::new(Arc::new(Registry::default()));
15755        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15756        let ack = hello_via_sink(
15757            &handler,
15758            &module,
15759            &mut module_rx,
15760            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15761        )
15762        .await;
15763        let ack = parse_ack(&ack);
15764        assert!(
15765            ack.subc_capabilities
15766                .iter()
15767                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15768            "{:?}",
15769            ack.subc_capabilities
15770        );
15771        assert!(ack
15772            .subc_capabilities
15773            .iter()
15774            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15775
15776        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15777        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15778        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15779        let reply = handler
15780            .handle_control_frame(&client, frame)
15781            .await
15782            .unwrap()
15783            .pop()
15784            .unwrap();
15785        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15786            serde_json::from_slice(&reply.body).unwrap()
15787        else {
15788            panic!("not a server.describe reply");
15789        };
15790        assert!(
15791            capabilities
15792                .iter()
15793                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15794            "{capabilities:?}"
15795        );
15796        assert!(capabilities
15797            .iter()
15798            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15799    }
15800
15801    #[tokio::test]
15802    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15803        let handler = ControlHandler::new(Arc::new(Registry::default()));
15804        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15805        let ack = hello_via_sink(
15806            &handler,
15807            &module,
15808            &mut rx,
15809            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15810        )
15811        .await;
15812        assert!(parse_ack(&ack)
15813            .subc_capabilities
15814            .iter()
15815            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15816        assert!(parse_ack(&ack)
15817            .subc_capabilities
15818            .iter()
15819            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15820        assert!(parse_ack(&ack)
15821            .subc_capabilities
15822            .iter()
15823            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15824        let (client, _rx) = route_ctx(ConnectionId::new(157));
15825        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15826        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15827        let reply = handler
15828            .handle_control_frame(&client, frame)
15829            .await
15830            .unwrap()
15831            .pop()
15832            .unwrap();
15833        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15834            serde_json::from_slice(&reply.body).unwrap()
15835        else {
15836            panic!("server.describe reply")
15837        };
15838        assert!(capabilities
15839            .iter()
15840            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15841        assert!(capabilities
15842            .iter()
15843            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15844        assert!(capabilities
15845            .iter()
15846            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15847    }
15848
15849    #[tokio::test]
15850    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15851        let handler = ControlHandler::new(Arc::new(Registry::default()));
15852        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15853        let ack = hello_via_sink(
15854            &handler,
15855            &module,
15856            &mut rx,
15857            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15858        )
15859        .await;
15860        assert!(parse_ack(&ack)
15861            .subc_capabilities
15862            .iter()
15863            .any(|cap| cap == "scope-workdir/v1"));
15864        let (client, _rx) = route_ctx(ConnectionId::new(159));
15865        let frame = Frame::build(
15866            FrameType::Request,
15867            control_flags(),
15868            0,
15869            0,
15870            5,
15871            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15872        )
15873        .unwrap();
15874        let reply = handler
15875            .handle_control_frame(&client, frame)
15876            .await
15877            .unwrap()
15878            .remove(0);
15879        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15880            serde_json::from_slice(&reply.body).unwrap()
15881        else {
15882            panic!("server.describe reply")
15883        };
15884        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15885    }
15886
15887    #[tokio::test]
15888    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15889        let handler = ControlHandler::new(Arc::new(Registry::default()));
15890        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15891        let ack = hello_via_sink(
15892            &handler,
15893            &module,
15894            &mut rx,
15895            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15896        )
15897        .await;
15898        assert!(parse_ack(&ack)
15899            .subc_capabilities
15900            .iter()
15901            .any(|cap| cap == "worker-runs/v1"));
15902        let (client, _rx) = route_ctx(ConnectionId::new(161));
15903        let frame = Frame::build(
15904            FrameType::Request,
15905            control_flags(),
15906            0,
15907            0,
15908            5,
15909            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15910        )
15911        .unwrap();
15912        let reply = handler
15913            .handle_control_frame(&client, frame)
15914            .await
15915            .unwrap()
15916            .remove(0);
15917        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15918            serde_json::from_slice(&reply.body).unwrap()
15919        else {
15920            panic!("server.describe reply")
15921        };
15922        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
15923    }
15924
15925    #[tokio::test]
15926    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
15927        let handler = ControlHandler::new(Arc::new(Registry::default()));
15928        let (module, mut rx) = route_ctx(ConnectionId::new(154));
15929        let ack = hello_via_sink(
15930            &handler,
15931            &module,
15932            &mut rx,
15933            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
15934        )
15935        .await;
15936        assert!(parse_ack(&ack)
15937            .subc_capabilities
15938            .iter()
15939            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
15940        let (client, _rx) = route_ctx(ConnectionId::new(155));
15941        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15942        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15943        let reply = handler
15944            .handle_control_frame(&client, frame)
15945            .await
15946            .unwrap()
15947            .pop()
15948            .unwrap();
15949        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15950            serde_json::from_slice(&reply.body).unwrap()
15951        else {
15952            panic!("not a server.describe reply")
15953        };
15954        assert!(capabilities
15955            .iter()
15956            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
15957    }
15958
15959    #[tokio::test]
15960    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
15961        let registry = Arc::new(Registry::default());
15962        let forwarding = Arc::new(ForwardingTable::default());
15963        let handler =
15964            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15965                .with_health_probe_timeout(Duration::from_secs(5));
15966        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
15967        hello_via_sink(
15968            &handler,
15969            &module_ctx,
15970            &mut module_rx,
15971            non_routable_hello_frame_with_control_ops(
15972                "mcp",
15973                300,
15974                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
15975            ),
15976        )
15977        .await;
15978        assert!(registry
15979            .get_module("mcp")
15980            .unwrap()
15981            .unwrap()
15982            .manifest
15983            .provides
15984            .is_empty());
15985
15986        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
15987        let route_response = handler
15988            .handle_control_frame(
15989                &route_client_ctx,
15990                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
15991            )
15992            .await
15993            .unwrap();
15994        assert_eq!(route_response[0].header.ty, FrameType::Error);
15995        assert_eq!(
15996            parse_error(&route_response[0])["code"],
15997            "target_unavailable"
15998        );
15999        assert!(parse_error(&route_response[0])["message"]
16000            .as_str()
16001            .unwrap()
16002            .contains("does not provide the requested target"));
16003        assert!(module_rx.try_recv().is_err());
16004
16005        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16006        let health_handler = handler.clone();
16007        let health_task = tokio::spawn(async move {
16008            health_handler
16009                .handle_control_frame(
16010                    &health_client_ctx,
16011                    supervisor_health_probe_frame(302, "mcp"),
16012                )
16013                .await
16014                .unwrap()
16015        });
16016        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16017            .await
16018            .unwrap()
16019            .unwrap();
16020        assert_eq!(
16021            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16022            ModuleControlRequest::HealthCheck {}
16023        );
16024        handler
16025            .handle_control_frame(
16026                &module_ctx,
16027                health_response(health_frame.header.corr, HealthStatus::Ok),
16028            )
16029            .await
16030            .unwrap();
16031        let health_response = health_task.await.unwrap();
16032        assert_eq!(health_response[0].header.ty, FrameType::Response);
16033        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16034            ClientControlResponse::SupervisorHealthProbe {
16035                module_id, status, ..
16036            } => {
16037                assert_eq!(module_id, "mcp");
16038                assert_eq!(status, HealthStatus::Ok);
16039            }
16040            other => panic!("unexpected health response: {other:?}"),
16041        }
16042
16043        // Exercise the forwarding cleanup path directly while leaving the registry
16044        // advertisement in place. If cleanup leaves a stale control sink behind,
16045        // the next probe will enqueue onto it and wait for the long probe timeout
16046        // instead of returning an immediate no-connection error.
16047        forwarding
16048            .cleanup_connection(module_ctx.connection_id)
16049            .unwrap();
16050        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16051        let cleanup_response = tokio::time::timeout(
16052            Duration::from_millis(200),
16053            handler.handle_control_frame(
16054                &cleanup_probe_ctx,
16055                supervisor_health_probe_frame(303, "mcp"),
16056            ),
16057        )
16058        .await
16059        .expect("probe should fail immediately when the control lane is gone")
16060        .unwrap();
16061        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16062        assert_eq!(
16063            parse_error(&cleanup_response[0])["code"],
16064            "target_unavailable"
16065        );
16066        assert!(parse_error(&cleanup_response[0])["message"]
16067            .as_str()
16068            .unwrap()
16069            .contains("no module connection"));
16070
16071        handler
16072            .cleanup_connection(module_ctx.connection_id)
16073            .unwrap();
16074    }
16075
16076    #[tokio::test]
16077    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16078        let registry = Arc::new(Registry::default());
16079        let supervisor_handle = SupervisorHandle::new();
16080        let supervisor =
16081            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16082                .with_handle(supervisor_handle.clone())
16083                .with_connection_file_path(
16084                    std::env::temp_dir()
16085                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16086                );
16087        let module = supervisor
16088            .supervise_configured(
16089                ModuleSpec {
16090                    script: None,
16091                    carry_containment: false,
16092                    module_id: "warming".to_string(),
16093                    program: fake_aft_stub_path(),
16094                    args: Vec::new(),
16095                    env: Vec::new(),
16096                    reserved: false,
16097                    reserved_prefixes: Vec::new(),
16098                    protocol: ModuleProtocol::Subc,
16099                    overlap: Default::default(),
16100                },
16101                true,
16102            )
16103            .unwrap();
16104        assert_eq!(module.state().unwrap(), ModuleState::Running);
16105
16106        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16107        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16108        let response = handler
16109            .handle_control_frame(
16110                &ctx,
16111                route_open_frame(304, "warming", unique_project_root("warming")),
16112            )
16113            .await
16114            .unwrap();
16115        module.stop().await.unwrap();
16116
16117        assert_eq!(response[0].header.ty, FrameType::Error);
16118        let error = parse_error(&response[0]);
16119        assert_eq!(error["code"], "module_warming");
16120        assert!(error["message"]
16121            .as_str()
16122            .unwrap()
16123            .contains("state=running, enabled=true, live=false"));
16124    }
16125
16126    #[test]
16127    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16128        let handler = ControlHandler::new(Arc::new(Registry::default()));
16129        let capture = EventCapture::default();
16130        let _subscriber =
16131            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16132        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16133        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16134        let pending = (0..limit).collect::<Vec<_>>();
16135        let response = handler
16136            .route_open_capacity_refusal(
16137                &ctx,
16138                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16139                "busy",
16140                pending.len(),
16141                limit,
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(&"\"open_admission_full\"".to_string())
16151            })
16152            .expect("connection 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        // Refused before `handle_route_open` parses the request, so the caller
16156        // fields are read from the frame itself.
16157        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16158        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16159    }
16160
16161    #[test]
16162    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16163        let handler = ControlHandler::new(Arc::new(Registry::default()));
16164        let capture = EventCapture::default();
16165        let _subscriber =
16166            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16167        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16168        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16169        let guards = (0..limit)
16170            .map(|_| {
16171                handler
16172                    .route_bind_concurrency
16173                    .try_admit("busy", limit)
16174                    .unwrap()
16175            })
16176            .collect::<Vec<_>>();
16177        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16178            Err(in_flight) => in_flight,
16179            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16180        };
16181        let response = handler
16182            .route_open_target_capacity_refusal(
16183                &ctx,
16184                &RouteOpenCaller::unknown(),
16185                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16186                "busy",
16187                in_flight,
16188            )
16189            .unwrap();
16190        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16191        let event = capture
16192            .events()
16193            .into_iter()
16194            .find(|event| {
16195                event.target == "control"
16196                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16197            })
16198            .expect("target admission refusal event");
16199        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16200        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16201        drop(guards);
16202    }
16203
16204    #[cfg(unix)]
16205    #[tokio::test(start_paused = true)]
16206    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16207        let registry = Arc::new(Registry::default());
16208        let handle = SupervisorHandle::new();
16209        let supervisor =
16210            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16211                .with_handle(handle.clone());
16212        let module = supervisor
16213            .spawn(crate::ModuleSpec {
16214                script: None,
16215                carry_containment: false,
16216                module_id: "retry-list".into(),
16217                program: PathBuf::from("/bin/sh"),
16218                args: vec!["-c".into(), "exit 17".into()],
16219                env: vec![],
16220                reserved: false,
16221                reserved_prefixes: vec![],
16222                protocol: ModuleProtocol::None,
16223                overlap: Default::default(),
16224            })
16225            .unwrap();
16226        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16227        while module.state().unwrap() != crate::ModuleState::Failed {
16228            assert!(
16229                std::time::Instant::now() < deadline,
16230                "waiting for budget failure"
16231            );
16232            tokio::task::yield_now().await;
16233        }
16234        let handler = ControlHandler::new(registry).with_supervisor(handle);
16235        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16236        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16237        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16238        assert_eq!(body["modules"][0]["state"], "failed");
16239        let retry = body["modules"][0]["next_retry_at_ms"]
16240            .as_u64()
16241            .expect("scheduled retry on the wire");
16242        let now = std::time::SystemTime::now()
16243            .duration_since(std::time::UNIX_EPOCH)
16244            .unwrap()
16245            .as_millis() as u64;
16246        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16247        module.set_enabled(false).await.unwrap();
16248        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16249        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16250        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16251        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16252    }
16253
16254    #[tokio::test]
16255    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16256        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16257        let supervisor =
16258            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16259        let module = supervisor
16260            .spawn(crate::ModuleSpec {
16261                script: None,
16262                carry_containment: false,
16263                module_id: "pid-read-budget".into(),
16264                program: std::env::current_exe().unwrap(),
16265                args: vec![
16266                    "--exact".into(),
16267                    "control::tests::pid_resource_read_fixture".into(),
16268                ],
16269                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16270                    .into_iter()
16271                    .map(|key| (key.into(), dir.display().to_string()))
16272                    .chain(std::iter::once((
16273                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16274                        "1".into(),
16275                    )))
16276                    .collect(),
16277                reserved: false,
16278                reserved_prefixes: Vec::new(),
16279                protocol: ModuleProtocol::None,
16280                overlap: Default::default(),
16281            })
16282            .unwrap();
16283        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16284        while !matches!(
16285            module.child_resource_usage(),
16286            subc_control::ChildResourceUsage::Measured(_)
16287        ) {
16288            assert!(
16289                tokio::time::Instant::now() < ready_deadline,
16290                "fixture process was not measurable"
16291            );
16292            tokio::time::sleep(Duration::from_millis(10)).await;
16293        }
16294        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16295        let reading = {
16296            let _guard = crate::subtree_resources::fault_read_guard().await;
16297            crate::subtree_resources::read_process(module.clone()).await
16298        };
16299        stop_resource_fixture(&module, &dir).await;
16300        assert!(
16301            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16302            "{reading:?}"
16303        );
16304    }
16305
16306    #[test]
16307    fn pid_resource_read_fixture() {
16308        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16309            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16310            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16311            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16312                std::thread::sleep(Duration::from_millis(5));
16313            }
16314            std::fs::write(dir.join("module-stopped"), "").unwrap();
16315        }
16316    }
16317
16318    async fn stop_resource_fixture(
16319        module: &crate::supervise::SupervisedModule,
16320        dir: &std::path::Path,
16321    ) {
16322        let stopping = module.stop();
16323        tokio::pin!(stopping);
16324        tokio::select! {
16325            result = &mut stopping => result.unwrap(),
16326            () = async {
16327                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16328                    tokio::time::sleep(Duration::from_millis(5)).await;
16329                }
16330                std::fs::write(dir.join("stop-module"), "").unwrap();
16331            } => stopping.await.unwrap(),
16332        }
16333        #[cfg(windows)]
16334        assert!(
16335            dir.join("module-stopped").exists(),
16336            "the resource fixture must exit cooperatively, not wait for the drain kill"
16337        );
16338        assert_eq!(
16339            module.state().unwrap(),
16340            crate::supervise::ModuleState::Stopped
16341        );
16342    }
16343
16344    #[tokio::test]
16345    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16346        let registry = Arc::new(Registry::default());
16347        let handle = SupervisorHandle::new();
16348        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16349            .with_handle(handle.clone());
16350        supervisor
16351            .supervise_configured(
16352                crate::ModuleSpec {
16353                    script: None,
16354                    module_id: "disabled-resource-reading".into(),
16355                    program: std::env::current_exe().unwrap(),
16356                    args: Vec::new(),
16357                    env: Vec::new(),
16358                    reserved: false,
16359                    reserved_prefixes: Vec::new(),
16360                    protocol: ModuleProtocol::None,
16361                    overlap: Default::default(),
16362                    carry_containment: false,
16363                },
16364                false,
16365            )
16366            .unwrap();
16367        let handler = ControlHandler::new(registry).with_supervisor(handle);
16368        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16369        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16370        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16371        assert!(body["modules"][0].get("tree").is_none());
16372        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16373    }
16374
16375    #[tokio::test]
16376    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16377        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16378        let registry = Arc::new(Registry::default());
16379        let handle = SupervisorHandle::new();
16380        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16381            .with_handle(handle.clone());
16382        let module = supervisor
16383            .spawn(crate::ModuleSpec {
16384                script: None,
16385                carry_containment: false,
16386                module_id: "list-process-priority".into(),
16387                program: std::env::current_exe().unwrap(),
16388                args: vec![
16389                    "--exact".into(),
16390                    "control::tests::pid_resource_read_fixture".into(),
16391                ],
16392                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16393                    .into_iter()
16394                    .map(|key| (key.into(), dir.display().to_string()))
16395                    .chain(std::iter::once((
16396                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16397                        "1".into(),
16398                    )))
16399                    .collect(),
16400                reserved: false,
16401                reserved_prefixes: Vec::new(),
16402                protocol: ModuleProtocol::None,
16403                overlap: Default::default(),
16404            })
16405            .unwrap();
16406        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16407        loop {
16408            let image = module.running_image_agreement().await;
16409            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16410                break;
16411            }
16412            assert!(
16413                tokio::time::Instant::now() < ready_deadline,
16414                "the fixture process never became observable: {image:?}"
16415            );
16416            tokio::time::sleep(Duration::from_millis(10)).await;
16417        }
16418        let guard = crate::subtree_resources::fault_read_guard().await;
16419        let (target, release, _) = crate::subtree_resources::held();
16420        module.set_subtree_target_for_test(target);
16421        let handler = ControlHandler::new(registry).with_supervisor(handle);
16422        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16423        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16424        drop(release);
16425        drop(guard);
16426        stop_resource_fixture(&module, &dir).await;
16427        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16428        assert_eq!(
16429            body["modules"][0]["resources"]["status"], "measured",
16430            "the optional tree timeout must not discard the process reading: {body}"
16431        );
16432        assert!(body["modules"][0].get("tree").is_none());
16433        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16434        assert_eq!(
16435            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16436            "the tree timeout must not hide a completed image observation"
16437        );
16438    }
16439
16440    #[cfg(any(target_os = "linux", target_os = "macos"))]
16441    #[tokio::test]
16442    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16443        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16444            .with_daemon_provenance(
16445                std::process::id(),
16446                0,
16447                Some(std::env::current_exe().unwrap()),
16448                None,
16449                None,
16450            );
16451        let (probe, release, began) = ExecutableIdentityProbe::held();
16452        handler.daemon_provenance.probe = probe;
16453        let observe = |handler: ControlHandler, corr| {
16454            tokio::spawn(async move {
16455                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16456                let frame =
16457                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16458                        .unwrap();
16459                handler
16460                    .handle_supervisor_provenance(&ctx, frame, None)
16461                    .await
16462                    .unwrap()
16463            })
16464        };
16465        let explicit = observe(handler.clone(), 114);
16466        began.await.unwrap();
16467        let concurrent = observe(handler.clone(), 115);
16468        // Keep explicit provenance waiting on its first image observation beyond
16469        // the list deadline; release it only after the concurrent list replies.
16470        tokio::time::sleep(Duration::from_millis(300)).await;
16471        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16472        let list = tokio::time::timeout(
16473            Duration::from_secs(1),
16474            handler.handle_supervisor_list(frame),
16475        )
16476        .await;
16477        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16478        drop(release);
16479        let replies = explicit.await.unwrap();
16480        let concurrent_replies = concurrent.await.unwrap();
16481        assert!(
16482            explicit_was_pending,
16483            "explicit provenance must await the full observation"
16484        );
16485        let list = list
16486            .expect("a concurrent explicit probe must not stall list")
16487            .unwrap();
16488        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16489        assert_eq!(list_body["op"], "supervisor.list");
16490        for replies in [replies, concurrent_replies] {
16491            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16492            assert_eq!(
16493                body["daemon"]["daemon_observed"]["running_image"]["status"],
16494                "match"
16495            );
16496        }
16497    }
16498
16499    #[tokio::test]
16500    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16501        let registry = Arc::new(Registry::default());
16502        let handle = SupervisorHandle::new();
16503        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16504            .with_handle(handle.clone());
16505        let module = supervisor
16506            .supervise_configured(
16507                crate::ModuleSpec {
16508                    script: None,
16509                    carry_containment: false,
16510                    module_id: "memory-read".into(),
16511                    program: PathBuf::from("disabled-module"),
16512                    args: Vec::new(),
16513                    env: Vec::new(),
16514                    reserved: false,
16515                    reserved_prefixes: Vec::new(),
16516                    protocol: ModuleProtocol::Subc,
16517                    overlap: Default::default(),
16518                },
16519                true,
16520            )
16521            .unwrap();
16522        let _guard = crate::subtree_resources::fault_read_guard().await;
16523        let (target, release, began) = crate::subtree_resources::held();
16524        // Optional list work may be skipped when its deadline is already spent.
16525        // Establish the stalled fixture before asking the list to observe it.
16526        let stalled_target = target.clone();
16527        let stalled = tokio::task::spawn_blocking(move || {
16528            stalled_target.tree(&subc_os::ProcessTable::default())
16529        });
16530        began.await.unwrap();
16531        module.set_subtree_target_for_test(target);
16532        let handler = ControlHandler::new(registry).with_supervisor(handle);
16533        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16534        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16535        let replies = handler
16536            .handle_client_control_request(
16537                &ctx,
16538                frame,
16539                ClientControlRequest::SupervisorList {},
16540                &mut None,
16541            )
16542            .await
16543            .unwrap();
16544        assert!(
16545            replies.is_empty(),
16546            "list reply must be detached from the connection reader"
16547        );
16548        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16549        let replies = handler
16550            .handle_client_control_request(
16551                &ctx,
16552                frame,
16553                ClientControlRequest::SupervisorSpawnSnapshot {},
16554                &mut None,
16555            )
16556            .await
16557            .unwrap();
16558        assert_eq!(
16559            replies.len(),
16560            1,
16561            "another request must complete while the subtree read stalls"
16562        );
16563        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16564            .await
16565            .unwrap()
16566            .unwrap();
16567        release.send(()).unwrap();
16568        drop(release);
16569        stalled.await.unwrap();
16570        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16571        assert!(
16572            body["modules"][0].get("tree").is_none(),
16573            "an unknown tree reading must be omitted after the bounded read expires"
16574        );
16575        // Lists export completed work rather than measuring synchronously.
16576        // Complete a refresh after the fixture is released before asserting
16577        // that a later list contains its measured tree.
16578        handler
16579            .resource_tracker
16580            .read(handler.supervisor.list(), false, "released_tree_fixture")
16581            .await;
16582        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16583        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16584        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16585        assert_eq!(
16586            body["modules"][0]["tree"]["source"], "process_tree",
16587            "the next request must export the completed refresh"
16588        );
16589        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16590    }
16591
16592    #[tokio::test]
16593    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16594        use subc_control::{
16595            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16596            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16597            TreeReading, TreeSource,
16598        };
16599        let registry = Arc::new(Registry::default());
16600        let handle = SupervisorHandle::new();
16601        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16602            .with_handle(handle.clone());
16603        supervisor
16604            .supervise_configured(
16605                crate::ModuleSpec {
16606                    script: None,
16607                    carry_containment: false,
16608                    module_id: "budget-worker".into(),
16609                    program: PathBuf::from("disabled-module"),
16610                    args: Vec::new(),
16611                    env: Vec::new(),
16612                    reserved: false,
16613                    reserved_prefixes: Vec::new(),
16614                    protocol: ModuleProtocol::Subc,
16615                    overlap: Default::default(),
16616                },
16617                true,
16618            )
16619            .unwrap();
16620        let handler = ControlHandler::new(registry).with_supervisor(handle);
16621        let now = u64::try_from(
16622            std::time::SystemTime::now()
16623                .duration_since(std::time::UNIX_EPOCH)
16624                .unwrap()
16625                .as_millis(),
16626        )
16627        .unwrap();
16628        let measured = now - 1_000;
16629        let hour = CpuLastHour::new(100, 60_000);
16630        let daemon = DaemonResources::new(7, 1, "test")
16631            .with_measured_at_ms(Some(measured))
16632            .with_resources(Some(ChildResourceUsage::Measured(
16633                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16634            )))
16635            .with_cpu_last_hour(Some(hour.clone()));
16636        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16637            .with_measured_at_ms(Some(measured))
16638            .with_cpu_last_hour(Some(hour.clone()));
16639        let tree = TreeReading::new(
16640            150,
16641            50,
16642            ChildMemoryKind::ResidentSet,
16643            1,
16644            TreeSource::ProcessTree,
16645        )
16646        .with_measured_at_ms(Some(measured));
16647        handler.resource_tracker.seed_committed_for_test(
16648            &handler.supervisor.list(),
16649            crate::resource_totals::Readings {
16650                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16651                daemon: Some(daemon),
16652                agent_commands: Some(vec![agents]),
16653                ..Default::default()
16654            },
16655            now,
16656        );
16657        list_diagnostics::scope(async {
16658            tokio::time::sleep(Duration::from_millis(110)).await;
16659            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16660            let request =
16661                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16662            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16663            let ClientControlResponse::SupervisorList {
16664                modules,
16665                daemon,
16666                agent_commands,
16667                ..
16668            } = serde_json::from_slice(&replies[0].body).unwrap()
16669            else {
16670                panic!("expected a list response")
16671            };
16672            assert!(matches!(
16673                modules[0].resources,
16674                Some(ChildResourceUsage::Unavailable {
16675                    reason: ChildResourceUnavailableReason::Unreadable
16676                })
16677            ));
16678            assert_eq!(
16679                (
16680                    modules[0].tree.as_ref().unwrap().cpu_ms,
16681                    modules[0].tree.as_ref().unwrap().measured_at_ms
16682                ),
16683                (150, Some(measured))
16684            );
16685            let daemon = daemon.unwrap();
16686            let agents = agent_commands.unwrap();
16687            assert_eq!(daemon.measured_at_ms, Some(measured));
16688            assert_eq!(
16689                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16690                (1, 50, Some(measured))
16691            );
16692            for hour in [
16693                modules[0].cpu_last_hour.as_ref(),
16694                daemon.cpu_last_hour.as_ref(),
16695                agents[0].cpu_last_hour.as_ref(),
16696            ] {
16697                let hour = hour.unwrap();
16698                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16699            }
16700        })
16701        .await;
16702    }
16703
16704    #[tokio::test]
16705    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16706        let registry = Arc::new(Registry::default());
16707        let handle = SupervisorHandle::new();
16708        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16709            .with_handle(handle.clone());
16710        supervisor
16711            .supervise_configured(
16712                crate::ModuleSpec {
16713                    script: None,
16714                    carry_containment: false,
16715                    module_id: "drift".into(),
16716                    program: PathBuf::from("disabled-module"),
16717                    args: Vec::new(),
16718                    env: Vec::new(),
16719                    reserved: false,
16720                    reserved_prefixes: Vec::new(),
16721                    protocol: ModuleProtocol::Subc,
16722                    overlap: Default::default(),
16723                },
16724                false,
16725            )
16726            .unwrap();
16727        let handler = ControlHandler::new(registry).with_supervisor(handle);
16728        for configured in [None, Some(false), Some(true)] {
16729            handler.capability_evaluator.configure(
16730                configured.map(|enabled| ("drift".to_string(), enabled)),
16731                BTreeMap::new(),
16732            );
16733            let frame =
16734                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16735            let replies = handler
16736                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16737                .await
16738                .unwrap();
16739            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16740            assert!(body.get("configured_enabled").is_none());
16741            assert_eq!(body["op"], "supervisor.ack");
16742            let frame =
16743                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16744            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16745            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16746            assert_eq!(
16747                body["modules"][0].get("configured_enabled"),
16748                configured.map(Value::Bool).as_ref()
16749            );
16750            assert!(body["modules"][0].get("tree").is_none());
16751            assert!(body["modules"][0].get("subtree").is_none());
16752        }
16753    }
16754
16755    #[tokio::test(flavor = "current_thread")]
16756    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16757        let handler = ControlHandler::new(Arc::new(Registry::default()));
16758        let capture = EventCapture::default();
16759        let _subscriber =
16760            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16761        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16762        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16763
16764        let _ = handler
16765            .handle_client_control_request(
16766                &ctx,
16767                frame,
16768                ClientControlRequest::SupervisorSetEnabled {
16769                    module_id: "broca".to_string(),
16770                    enabled: false,
16771                },
16772                &mut None,
16773            )
16774            .await
16775            .unwrap();
16776
16777        let events = capture
16778            .events()
16779            .into_iter()
16780            .filter(|event| {
16781                event.target == "control"
16782                    && event.fields.get("message").map(String::as_str)
16783                        == Some("supervisor request received")
16784            })
16785            .collect::<Vec<_>>();
16786        assert_eq!(events.len(), 1, "one supervisor request log line");
16787        let event = &events[0];
16788        assert_eq!(event.level, tracing::Level::INFO);
16789        assert_eq!(
16790            event.fields.get("op"),
16791            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16792        );
16793        assert_eq!(
16794            event.fields.get("module_id"),
16795            Some(&"\"broca\"".to_string())
16796        );
16797        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16798        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16799        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16800    }
16801
16802    #[tokio::test(flavor = "current_thread")]
16803    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16804        let registry = Arc::new(Registry::default());
16805        let module_connection = ConnectionId::new(303);
16806        registry
16807            .register_with_control_ops(
16808                manifest("aft", PROTOCOL_VERSION),
16809                PROTOCOL_VERSION,
16810                module_connection,
16811                module_baseline_control_ops(),
16812            )
16813            .unwrap();
16814        let handler = ControlHandler::new(registry);
16815        let capture = EventCapture::default();
16816        let _subscriber =
16817            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16818        let (ctx, _rx) = route_ctx(module_connection);
16819        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16820
16821        let _ = handler
16822            .handle_client_control_request(
16823                &ctx,
16824                frame,
16825                ClientControlRequest::SupervisorSetEnabled {
16826                    module_id: "broca".to_string(),
16827                    enabled: false,
16828                },
16829                &mut None,
16830            )
16831            .await
16832            .unwrap();
16833
16834        let callers = capture
16835            .events()
16836            .into_iter()
16837            .filter(|event| {
16838                event.fields.get("message").map(String::as_str)
16839                    == Some("supervisor request received")
16840            })
16841            .map(|event| event.fields.get("caller").cloned())
16842            .collect::<Vec<_>>();
16843        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16844    }
16845
16846    #[tokio::test(flavor = "current_thread")]
16847    async fn supervisor_list_does_not_log_request_received() {
16848        let handler = ControlHandler::new(Arc::new(Registry::default()));
16849        let capture = EventCapture::default();
16850        let _subscriber =
16851            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16852        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16853        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16854
16855        handler
16856            .handle_client_control_request(
16857                &ctx,
16858                frame,
16859                ClientControlRequest::SupervisorList {},
16860                &mut None,
16861            )
16862            .await
16863            .unwrap();
16864
16865        assert!(capture.events().into_iter().all(|event| {
16866            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16867        }));
16868    }
16869
16870    #[tokio::test(flavor = "current_thread")]
16871    async fn supervisor_rescan_preview_does_not_log_request_received() {
16872        let handler = ControlHandler::new(Arc::new(Registry::default()));
16873        let capture = EventCapture::default();
16874        let _subscriber =
16875            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16876        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16877        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16878
16879        handler
16880            .handle_client_control_request(
16881                &ctx,
16882                frame,
16883                ClientControlRequest::SupervisorRescan { preview: true },
16884                &mut None,
16885            )
16886            .await
16887            .unwrap();
16888
16889        assert!(capture.events().into_iter().all(|event| {
16890            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16891        }));
16892    }
16893
16894    struct ApproveOperator;
16895    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16896        fn prompt(
16897            &self,
16898            _: &str,
16899            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16900        ) -> crate::operator_confirm::ProviderResult {
16901            crate::operator_confirm::ProviderResult::Approved
16902        }
16903    }
16904
16905    #[tokio::test]
16906    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
16907        assert_eq!(
16908            ControlHandler::default().privileged_operator_prompt,
16909            PrivilegedOperatorPrompt::Log
16910        );
16911        for (initial, changed, running) in [
16912            ("log", "enforce", PrivilegedOperatorPrompt::Log),
16913            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
16914        ] {
16915            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
16916            let path = dir.join("subc.jsonc");
16917            std::fs::write(
16918                &path,
16919                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
16920            )
16921            .unwrap();
16922            let config = crate::daemon_config::load(&path).unwrap().unwrap();
16923            let registry = Arc::new(Registry::default());
16924            let handle = SupervisorHandle::new();
16925            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
16926                .with_handle(handle.clone());
16927            let handler = ControlHandler::new(registry)
16928                .with_supervisor(handle)
16929                .with_privileged_operator_prompt(config.privileged_operator_prompt)
16930                .with_supervisor_rescan(supervisor, &path, config.port);
16931            handler.forwarding.operator_confirms().configure(
16932                Arc::new(ApproveOperator),
16933                crate::operator_confirm::OperatorLimits::default(),
16934            );
16935            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
16936
16937            for (disk_mode, needs_restart) in [
16938                (Some(initial), false),
16939                (Some(changed), true),
16940                (Some(changed), true),
16941                (None, running == PrivilegedOperatorPrompt::Enforce),
16942                (Some(initial), false),
16943            ] {
16944                let mut doc = json!({"version":1});
16945                if let Some(mode) = disk_mode {
16946                    doc["privileged_operator_prompt"] = json!(mode);
16947                }
16948                std::fs::write(&path, doc.to_string()).unwrap();
16949                for preview in [true, false] {
16950                    let request = ClientControlRequest::SupervisorRescan { preview };
16951                    let frame = Frame::build(
16952                        FrameType::Request,
16953                        control_flags(),
16954                        0,
16955                        0,
16956                        1,
16957                        serde_json::to_vec(&request).unwrap(),
16958                    )
16959                    .unwrap();
16960                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
16961                    assert_eq!(frames.len(), 1);
16962                    let ClientControlResponse::SupervisorRescan { result } =
16963                        serde_json::from_slice(&frames[0].body).unwrap()
16964                    else {
16965                        panic!("expected a rescan response");
16966                    };
16967                    let expected = if needs_restart {
16968                        vec!["privileged_operator_prompt"]
16969                    } else {
16970                        Vec::new()
16971                    };
16972                    assert_eq!(result.restart_required, expected);
16973                    assert_eq!(handler.privileged_operator_prompt, running);
16974                    assert_eq!(
16975                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
16976                        running
16977                    );
16978                }
16979            }
16980        }
16981    }
16982
16983    #[tokio::test]
16984    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
16985        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
16986        let path = dir.join("subc.jsonc");
16987        let registry = Arc::new(Registry::default());
16988        let handle = SupervisorHandle::new();
16989        let supervisor =
16990            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
16991        let handler = ControlHandler::new(registry)
16992            .with_supervisor(handle)
16993            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
16994            .with_supervisor_rescan(supervisor, &path, None);
16995        handler.forwarding.operator_confirms().configure(
16996            Arc::new(ApproveOperator),
16997            crate::operator_confirm::OperatorLimits::default(),
16998        );
16999        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17000        for preview in [true, false] {
17001            std::fs::write(
17002                &path,
17003                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17004            )
17005            .unwrap();
17006            let request = ClientControlRequest::SupervisorRescan { preview };
17007            let frame = Frame::build(
17008                FrameType::Request,
17009                control_flags(),
17010                0,
17011                0,
17012                1,
17013                serde_json::to_vec(&request).unwrap(),
17014            )
17015            .unwrap();
17016            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17017            assert_eq!(frames.len(), 1);
17018            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17019            assert_eq!(
17020                handler.privileged_operator_prompt,
17021                PrivilegedOperatorPrompt::Enforce
17022            );
17023        }
17024    }
17025
17026    /// One wire code has several senders, so the refusal line names the check
17027    /// that refused. This drives the shared refusal path for ordinary refusals
17028    /// with an unregistered
17029    /// target and requires the branch label on the event.
17030    #[tokio::test]
17031    async fn route_open_refusal_names_the_check_that_refused() {
17032        let handler = ControlHandler::new(Arc::new(Registry::default()));
17033        let capture = EventCapture::default();
17034        let _subscriber =
17035            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17036        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17037        let response = handler
17038            .handle_control_frame(
17039                &ctx,
17040                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17041            )
17042            .await
17043            .unwrap();
17044
17045        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17046        let event = capture
17047            .events()
17048            .into_iter()
17049            .find(|event| {
17050                event.target == "control"
17051                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17052            })
17053            .expect("route.open refusal event");
17054        assert_eq!(
17055            event.fields.get("reason"),
17056            Some(&"\"not_registered\"".to_string())
17057        );
17058    }
17059
17060    #[tokio::test]
17061    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17062        let registry = Arc::new(Registry::default());
17063        let supervisor_handle = SupervisorHandle::new();
17064        let supervisor =
17065            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17066                .with_handle(supervisor_handle.clone())
17067                .with_connection_file_path(std::env::temp_dir().join(format!(
17068                    "subc-route-open-refusal-info-{}",
17069                    std::process::id()
17070                )));
17071        let module = supervisor
17072            .supervise_configured(
17073                ModuleSpec {
17074                    script: None,
17075                    carry_containment: false,
17076                    module_id: "warming".to_string(),
17077                    program: fake_aft_stub_path(),
17078                    args: Vec::new(),
17079                    env: Vec::new(),
17080                    reserved: false,
17081                    reserved_prefixes: Vec::new(),
17082                    protocol: ModuleProtocol::Subc,
17083                    overlap: Default::default(),
17084                },
17085                true,
17086            )
17087            .unwrap();
17088        assert_eq!(module.state().unwrap(), ModuleState::Running);
17089
17090        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17091        assert!(handler
17092            .counters()
17093            .snapshot()
17094            .get("route_open_refused_by_code")
17095            .is_none());
17096        let capture = EventCapture::default();
17097        let _subscriber =
17098            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17099        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17100        let response = handler
17101            .handle_control_frame(
17102                &ctx,
17103                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17104            )
17105            .await
17106            .unwrap();
17107        module.stop().await.unwrap();
17108
17109        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17110        let event = capture
17111            .events()
17112            .into_iter()
17113            .find(|event| {
17114                event.target == "control"
17115                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17116            })
17117            .expect("route.open refusal event");
17118        assert_eq!(
17119            event.fields.get("module_id"),
17120            Some(&"\"warming\"".to_string())
17121        );
17122        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17123        assert_eq!(
17124            event.fields.get("reason"),
17125            Some(&"\"supervised_not_registered\"".to_string())
17126        );
17127        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17128        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17129        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17130        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17131        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17132        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17133        assert_eq!(
17134            handler.counters().snapshot()["route_open_refused_by_code"],
17135            json!({ "module_warming": 1 })
17136        );
17137    }
17138
17139    const OUTAGE_START: &str = "route.open refusing module: not serving";
17140    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17141
17142    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17143        capture
17144            .events()
17145            .into_iter()
17146            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17147            .collect()
17148    }
17149
17150    fn supervise_stub(
17151        registry: &Arc<Registry>,
17152        module_id: &str,
17153        enabled: bool,
17154    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17155        let supervisor_handle = SupervisorHandle::new();
17156        let supervisor =
17157            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17158                .with_handle(supervisor_handle.clone())
17159                .with_connection_file_path(std::env::temp_dir().join(format!(
17160                    "subc-route-outage-{module_id}-{}",
17161                    std::process::id()
17162                )));
17163        let module = supervisor
17164            .supervise_configured(
17165                ModuleSpec {
17166                    script: None,
17167                    carry_containment: false,
17168                    module_id: module_id.to_string(),
17169                    program: fake_aft_stub_path(),
17170                    args: Vec::new(),
17171                    env: Vec::new(),
17172                    reserved: false,
17173                    reserved_prefixes: Vec::new(),
17174                    protocol: ModuleProtocol::Subc,
17175                    overlap: Default::default(),
17176                },
17177                enabled,
17178            )
17179            .unwrap();
17180        (supervisor_handle, module)
17181    }
17182
17183    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17184        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17185            module_id: module_id.to_string(),
17186            drain_timeout_ms: Some(50),
17187        })
17188        .unwrap();
17189        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17190    }
17191
17192    /// Two handlers built over one forwarding table must share one outage
17193    /// tracker; separate trackers would each log their own opening line for
17194    /// the same outage.
17195    #[test]
17196    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17197        let registry = Arc::new(Registry::default());
17198        let forwarding = Arc::new(ForwardingTable::default());
17199        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17200        let second = ControlHandler::with_forwarding(registry, forwarding);
17201        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17202    }
17203
17204    /// A client can name any module id it likes. Refusing an unknown one,
17205    /// however often, must not create outage state or outage lines, or the
17206    /// tracker would be a memory sink any client could fill.
17207    #[tokio::test(flavor = "current_thread")]
17208    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17209        let handler = ControlHandler::new(Arc::new(Registry::default()));
17210        let capture = EventCapture::default();
17211        let _subscriber =
17212            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17213        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17214        for corr in 0..8 {
17215            let response = handler
17216                .handle_control_frame(
17217                    &ctx,
17218                    route_open_frame(
17219                        380 + corr,
17220                        &format!("nobody-{corr}"),
17221                        unique_project_root("outage-unknown"),
17222                    ),
17223                )
17224                .await
17225                .unwrap();
17226            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17227        }
17228
17229        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17230        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17231        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17232    }
17233
17234    /// Drives the refusal path end to end: a supervised module that served
17235    /// before and stopped being registered with no instruction to stop is a
17236    /// WARN, and the same module refused after an operator `supervisor.restart`
17237    /// is an INFO.
17238    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17239    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17240        let registry = Arc::new(Registry::default());
17241        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17242        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17243        let capture = EventCapture::default();
17244        let _subscriber =
17245            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17246        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17247        // The stub never registers, so pretend it served once: otherwise every
17248        // refusal would fall in its startup window.
17249        handler.route_outages.record_accepted("outage-restart");
17250
17251        let response = handler
17252            .handle_control_frame(
17253                &ctx,
17254                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17255            )
17256            .await
17257            .unwrap();
17258        assert_eq!(response[0].header.ty, FrameType::Error);
17259        let starts = outage_lines(&capture, OUTAGE_START);
17260        assert_eq!(starts.len(), 1, "{starts:?}");
17261        assert_eq!(starts[0].level, tracing::Level::WARN);
17262        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17263        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17264        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17265        handler.route_outages.record_accepted("outage-restart");
17266        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17267
17268        // The missing connection file makes the stub exit immediately. Restart
17269        // is deliberately deferred while that exit is being recorded; Failed
17270        // means the zero restart budget and terminal record have been published.
17271        tokio::time::timeout(Duration::from_secs(10), async {
17272            while module.state().unwrap() != crate::ModuleState::Failed {
17273                tokio::task::yield_now().await;
17274            }
17275        })
17276        .await
17277        .expect("stub exit must be recorded before the operator restart");
17278
17279        let restart = handler
17280            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17281            .await
17282            .unwrap();
17283        assert_eq!(
17284            restart[0].header.ty,
17285            FrameType::Response,
17286            "{:?}",
17287            parse_error(&restart[0])
17288        );
17289        handler
17290            .handle_control_frame(
17291                &ctx,
17292                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17293            )
17294            .await
17295            .unwrap();
17296        module.stop().await.unwrap();
17297
17298        let starts = outage_lines(&capture, OUTAGE_START);
17299        assert_eq!(starts.len(), 2, "{starts:?}");
17300        assert_eq!(starts[1].level, tracing::Level::INFO);
17301        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17302    }
17303
17304    /// A restart refused before it touched the module (here: the module is
17305    /// disabled) must clear its operator mark, so the next real outage is
17306    /// still reported as a warning.
17307    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17308    async fn failed_operator_restart_leaves_no_operator_mark() {
17309        let registry = Arc::new(Registry::default());
17310        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17311        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17312        let capture = EventCapture::default();
17313        let _subscriber =
17314            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17315        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17316        handler.route_outages.record_accepted("outage-disabled");
17317
17318        let restart = handler
17319            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17320            .await
17321            .unwrap();
17322        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17323        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17324
17325        handler
17326            .handle_control_frame(
17327                &ctx,
17328                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17329            )
17330            .await
17331            .unwrap();
17332        let starts = outage_lines(&capture, OUTAGE_START);
17333        assert_eq!(starts.len(), 1, "{starts:?}");
17334        assert_eq!(starts[0].level, tracing::Level::WARN);
17335    }
17336
17337    #[tokio::test(flavor = "current_thread")]
17338    async fn route_open_unknown_module_escapes_target_module_id() {
17339        let handler = ControlHandler::new(Arc::new(Registry::default()));
17340        let capture = EventCapture::default();
17341        let _subscriber =
17342            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17343        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17344        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17345        let response = handler
17346            .handle_control_frame(
17347                &ctx,
17348                route_open_frame(
17349                    395,
17350                    hostile_module_id,
17351                    unique_project_root("hostile-target-module-id"),
17352                ),
17353            )
17354            .await
17355            .unwrap();
17356
17357        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17358        let event = capture
17359            .events()
17360            .into_iter()
17361            .find(|event| {
17362                event.target == "control"
17363                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17364            })
17365            .expect("route.open unknown-module refusal event");
17366        let logged = event.fields.get("module_id").expect("module_id field");
17367        assert!(!logged.bytes().any(|byte| byte < 0x20));
17368        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17369    }
17370
17371    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17372    /// the daemon-origin bit on the frame the client receives.
17373    #[tokio::test(flavor = "current_thread")]
17374    async fn route_open_refusal_carries_daemon_origin() {
17375        let handler = ControlHandler::new(Arc::new(Registry::default()));
17376        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17377        let response = handler
17378            .handle_control_frame(
17379                &ctx,
17380                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17381            )
17382            .await
17383            .unwrap();
17384
17385        assert_eq!(response.len(), 1);
17386        assert_eq!(response[0].header.ty, FrameType::Error);
17387        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17388        assert!(
17389            response[0].header.flags.is_daemon_origin(),
17390            "route.open refusal must carry daemon origin: {:?}",
17391            response[0].header.flags
17392        );
17393    }
17394
17395    /// The drain `module_reloading` refusal is daemon-synthesized for an
17396    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17397    /// frame the client receives.
17398    #[tokio::test(flavor = "current_thread")]
17399    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17400        let registry = Arc::new(Registry::default());
17401        let forwarding = Arc::new(ForwardingTable::default());
17402        let handler =
17403            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17404        let module_connection = ConnectionId::new(95);
17405        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17406        hello_via_sink(
17407            &handler,
17408            &module_ctx,
17409            &mut module_rx,
17410            hello_frame("aft", PROTOCOL_VERSION, 395),
17411        )
17412        .await;
17413        forwarding
17414            .begin_module_drain("aft", RouteCloseReason::Restart)
17415            .unwrap()
17416            .expect("the module endpoint drains");
17417
17418        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17419        let response = handler
17420            .handle_control_frame(
17421                &client_ctx,
17422                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17423            )
17424            .await
17425            .unwrap();
17426
17427        assert_eq!(response.len(), 1);
17428        assert_eq!(response[0].header.ty, FrameType::Error);
17429        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17430        assert!(
17431            response[0].header.flags.is_daemon_origin(),
17432            "drain module_reloading must carry daemon origin: {:?}",
17433            response[0].header.flags
17434        );
17435    }
17436
17437    /// A module that refuses a bind with a daemon code still cannot mint a
17438    /// daemon refusal: the relayed `module_reloading` body reaches the client
17439    /// with the daemon-origin bit clear.
17440    #[tokio::test(flavor = "current_thread")]
17441    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17442        let registry = Arc::new(Registry::default());
17443        let forwarding = Arc::new(ForwardingTable::default());
17444        let handler =
17445            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17446        let module_connection = ConnectionId::new(95);
17447        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17448        hello_via_sink(
17449            &handler,
17450            &module_ctx,
17451            &mut module_rx,
17452            hello_frame("aft", PROTOCOL_VERSION, 395),
17453        )
17454        .await;
17455
17456        let client_connection = ConnectionId::new(96);
17457        let (client_ctx, _client_rx) = route_ctx(client_connection);
17458        let (route_task, bind) = relay_route_open(
17459            &handler,
17460            client_connection,
17461            &client_ctx.egress,
17462            &mut module_rx,
17463            396,
17464            "aft",
17465            "spoofed-reloading",
17466        )
17467        .await;
17468        // The module sets the origin bit on its own rejection too: neither
17469        // the bit nor the daemon code may survive the relay as daemon-owned.
17470        let rejection = Frame::build(
17471            FrameType::Error,
17472            crate::router::daemon_error_flags(),
17473            0,
17474            0,
17475            bind.header.corr,
17476            serde_json::to_vec(&ErrorBody::new(
17477                "module_reloading",
17478                "module refused route.bind",
17479            ))
17480            .unwrap(),
17481        )
17482        .unwrap();
17483        handler
17484            .handle_control_frame(&module_ctx, rejection)
17485            .await
17486            .unwrap();
17487
17488        let response = route_task.await.unwrap();
17489        assert_eq!(response.len(), 1);
17490        assert_eq!(response[0].header.ty, FrameType::Error);
17491        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17492        assert!(
17493            !response[0].header.flags.is_daemon_origin(),
17494            "a module's own rejection must not carry daemon origin: {:?}",
17495            response[0].header.flags
17496        );
17497    }
17498
17499    #[tokio::test(flavor = "current_thread")]
17500    async fn route_open_module_rejection_uses_daemon_counter_key() {
17501        let registry = Arc::new(Registry::default());
17502        let forwarding = Arc::new(ForwardingTable::default());
17503        let handler =
17504            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17505        let module_connection = ConnectionId::new(95);
17506        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17507        hello_via_sink(
17508            &handler,
17509            &module_ctx,
17510            &mut module_rx,
17511            hello_frame("aft", PROTOCOL_VERSION, 395),
17512        )
17513        .await;
17514
17515        let client_connection = ConnectionId::new(96);
17516        let (client_ctx, _client_rx) = route_ctx(client_connection);
17517        let capture = EventCapture::default();
17518        // tracing-core decides once per callsite whether its events are enabled,
17519        // and caches the answer. If a parallel test with no subscriber reaches
17520        // this callsite first, the cached answer is "disabled" and this test's
17521        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17522        // ask every live subscriber instead, while only this test's default
17523        // receives the events.
17524        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17525        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17526        let _subscriber =
17527            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17528        let (route_task, bind) = relay_route_open(
17529            &handler,
17530            client_connection,
17531            &client_ctx.egress,
17532            &mut module_rx,
17533            396,
17534            "aft",
17535            "hostile-module-code",
17536        )
17537        .await;
17538        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17539        let rejection = Frame::build(
17540            FrameType::Error,
17541            control_flags(),
17542            0,
17543            0,
17544            bind.header.corr,
17545            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17546        )
17547        .unwrap();
17548        handler
17549            .handle_control_frame(&module_ctx, rejection)
17550            .await
17551            .unwrap();
17552
17553        let response = route_task.await.unwrap();
17554        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17555        let counters = handler.counters().snapshot();
17556        assert_eq!(
17557            counters["route_open_refused_by_code"],
17558            json!({ "module_rejected": 1 })
17559        );
17560        assert!(counters["route_open_refused_by_code"]
17561            .get(hostile_code)
17562            .is_none());
17563
17564        let event = capture
17565            .events()
17566            .into_iter()
17567            .find(|event| {
17568                event.target == "control"
17569                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17570            })
17571            .expect("route.open module-rejection refusal event");
17572        let logged = event.fields.get("module_code").expect("module_code field");
17573        assert!(!logged.bytes().any(|byte| byte < 0x20));
17574        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17575    }
17576
17577    #[tokio::test]
17578    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17579        let registry = Arc::new(Registry::default());
17580        let supervisor_handle = SupervisorHandle::new();
17581        let missing_program = std::env::temp_dir().join(format!(
17582            "subc-route-open-missing-program-{}",
17583            std::process::id()
17584        ));
17585        let supervisor =
17586            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17587                .with_handle(supervisor_handle.clone());
17588        let module = supervisor
17589            .supervise_configured(
17590                ModuleSpec {
17591                    script: None,
17592                    carry_containment: false,
17593                    module_id: "failed".to_string(),
17594                    program: missing_program,
17595                    args: Vec::new(),
17596                    env: Vec::new(),
17597                    reserved: false,
17598                    reserved_prefixes: Vec::new(),
17599                    protocol: ModuleProtocol::Subc,
17600                    overlap: Default::default(),
17601                },
17602                true,
17603            )
17604            .unwrap();
17605        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17606
17607        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17608        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17609        let response = handler
17610            .handle_control_frame(
17611                &ctx,
17612                route_open_frame(305, "failed", unique_project_root("failed")),
17613            )
17614            .await
17615            .unwrap();
17616
17617        assert_eq!(response[0].header.ty, FrameType::Error);
17618        let error = parse_error(&response[0]);
17619        assert_eq!(error["code"], "target_unavailable");
17620        assert!(error["message"]
17621            .as_str()
17622            .unwrap()
17623            .contains("state=failed, enabled=true, live=false"));
17624    }
17625
17626    #[tokio::test]
17627    async fn route_open_role_mismatch_remains_target_unavailable() {
17628        let registry = Arc::new(Registry::default());
17629        let handler = ControlHandler::new(Arc::clone(&registry));
17630        handler
17631            .handle_control(
17632                ConnectionId::new(41),
17633                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17634            )
17635            .unwrap();
17636
17637        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17638        let response = handler
17639            .handle_control_frame(
17640                &ctx,
17641                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17642            )
17643            .await
17644            .unwrap();
17645
17646        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17647        assert!(parse_error(&response[0])["message"]
17648            .as_str()
17649            .unwrap()
17650            .contains("does not provide the requested target"));
17651    }
17652
17653    #[tokio::test]
17654    async fn route_open_inactive_registration_remains_target_unavailable() {
17655        let registry = Arc::new(Registry::default());
17656        let handler = ControlHandler::new(Arc::clone(&registry));
17657        handler
17658            .handle_control(
17659                ConnectionId::new(43),
17660                hello_frame("inactive", PROTOCOL_VERSION, 308),
17661            )
17662            .unwrap();
17663        assert!(registry
17664            .set_module_state_for_test("inactive", ChannelState::Closed)
17665            .unwrap());
17666
17667        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17668        let response = handler
17669            .handle_control_frame(
17670                &ctx,
17671                route_open_frame(309, "inactive", unique_project_root("inactive")),
17672            )
17673            .await
17674            .unwrap();
17675
17676        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17677        assert!(parse_error(&response[0])["message"]
17678            .as_str()
17679            .unwrap()
17680            .contains("is not active"));
17681    }
17682
17683    #[tokio::test]
17684    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17685        let registry = Arc::new(Registry::default());
17686        let forwarding = Arc::new(ForwardingTable::default());
17687        let supervisor_handle = SupervisorHandle::new();
17688        let supervisor =
17689            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17690                .with_forwarding(Arc::clone(&forwarding))
17691                .with_handle(supervisor_handle.clone());
17692        let module = supervisor
17693            .supervise_configured(
17694                crate::ModuleSpec {
17695                    script: None,
17696                    carry_containment: false,
17697                    module_id: "late-health-response".to_string(),
17698                    program: PathBuf::from("disabled-module"),
17699                    args: Vec::new(),
17700                    env: Vec::new(),
17701                    reserved: false,
17702                    reserved_prefixes: Vec::new(),
17703                    protocol: ModuleProtocol::Subc,
17704                    overlap: Default::default(),
17705                },
17706                false,
17707            )
17708            .unwrap();
17709        let handler =
17710            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17711                .with_supervisor(supervisor_handle);
17712        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17713        handler
17714            .handle_control_frame(
17715                &module_ctx,
17716                hello_frame_with_control_ops(
17717                    "late-health-response",
17718                    PROTOCOL_VERSION,
17719                    7,
17720                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17721                ),
17722            )
17723            .await
17724            .unwrap();
17725        let probe_started_at = Instant::now() - Duration::from_millis(80);
17726        let pending = forwarding
17727            .begin_health_probe_rpc_for(
17728                "late-health-response",
17729                MODULE_CONTROL_OP_HEALTH_CHECK,
17730                probe_started_at,
17731                Instant::now() - Duration::from_millis(1),
17732            )
17733            .unwrap();
17734        assert!(forwarding
17735            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17736            .unwrap());
17737
17738        let responses = handler
17739            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17740            .await
17741            .unwrap();
17742
17743        assert!(responses.is_empty());
17744        let health = module.status().unwrap().health;
17745        assert_eq!(health.late_answer_count, 1);
17746        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17747    }
17748
17749    #[tokio::test]
17750    async fn health_probe_timeout_and_module_death_are_typed() {
17751        let registry = Arc::new(Registry::default());
17752        let forwarding = Arc::new(ForwardingTable::default());
17753        let handler =
17754            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17755                .with_health_probe_timeout(Duration::from_millis(50));
17756        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17757        hello_via_sink(
17758            &handler,
17759            &module_ctx,
17760            &mut module_rx,
17761            hello_frame_with_control_ops(
17762                "aft",
17763                PROTOCOL_VERSION,
17764                7,
17765                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17766            ),
17767        )
17768        .await;
17769
17770        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17771        let responses = handler
17772            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17773            .await
17774            .unwrap();
17775        assert_eq!(responses[0].header.ty, FrameType::Error);
17776        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17777        let _ = module_rx.try_recv();
17778
17779        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17780        let health_handler = handler.clone();
17781        let death_task = tokio::spawn(async move {
17782            health_handler
17783                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17784                .await
17785                .unwrap()
17786        });
17787        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17788            .await
17789            .unwrap()
17790            .unwrap();
17791        handler
17792            .cleanup_connection(module_ctx.connection_id)
17793            .unwrap();
17794        let responses = death_task.await.unwrap();
17795        assert_eq!(responses[0].header.ty, FrameType::Error);
17796        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17797    }
17798
17799    #[test]
17800    fn hello_requires_exact_protocol_version() {
17801        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17802            let registry = Arc::new(Registry::default());
17803            let handler = ControlHandler::new(Arc::clone(&registry));
17804            let responses = handler
17805                .handle_control(
17806                    ConnectionId::new(connection),
17807                    hello_frame("aft", offered, 9),
17808                )
17809                .unwrap();
17810
17811            assert_eq!(responses.len(), 1);
17812            assert_eq!(responses[0].header.ty, FrameType::Error);
17813            let error = parse_error(&responses[0]);
17814            assert_eq!(error["code"], "version_unsupported");
17815            assert!(registry.get_module("aft").unwrap().is_none());
17816            assert_eq!(registry.active_registration_count().unwrap(), 0);
17817        }
17818    }
17819
17820    #[test]
17821    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17822        let registry = Arc::new(Registry::default());
17823        let forwarding = Arc::new(ForwardingTable::default());
17824        let handler =
17825            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17826        let module_connection = ConnectionId::new(301);
17827        let registration = registry
17828            .register_with_control_ops(
17829                manifest("aft-push", PROTOCOL_VERSION),
17830                PROTOCOL_VERSION,
17831                module_connection,
17832                module_baseline_control_ops(),
17833            )
17834            .unwrap();
17835        let (module_tx, _module_rx) = mpsc::channel(8);
17836        let endpoint = forwarding
17837            .register_module_connection(
17838                module_connection,
17839                "aft-push".to_string(),
17840                PROTOCOL_VERSION,
17841                manifest_concurrency(&registration.manifest),
17842                FrameSink::new(module_tx),
17843            )
17844            .unwrap();
17845
17846        // A push op this version does not know is ignored (forward-compat), not errored.
17847        let unknown = Frame::build(
17848            FrameType::Push,
17849            control_flags(),
17850            0,
17851            0,
17852            5,
17853            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17854        )
17855        .unwrap();
17856        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17857        assert!(
17858            out.is_empty(),
17859            "unknown push op must be ignored, got {out:?}"
17860        );
17861
17862        // A malformed body for a KNOWN op is a real error worth surfacing.
17863        let malformed = Frame::build(
17864            FrameType::Push,
17865            control_flags(),
17866            0,
17867            0,
17868            6,
17869            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17870        )
17871        .unwrap();
17872        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17873        assert_eq!(out.len(), 1);
17874        assert_eq!(out[0].header.ty, FrameType::Error);
17875        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17876    }
17877
17878    #[test]
17879    fn hello_rejected_when_connection_already_owns_client_routes() {
17880        let registry = Arc::new(Registry::default());
17881        let forwarding = Arc::new(ForwardingTable::default());
17882        let handler =
17883            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17884        // Commits a client route on connection 202 (bound to a module on conn 101).
17885        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17886        let client_connection = ConnectionId::new(202);
17887
17888        // That same connection now tries to register as a module: rejected, so one
17889        // connection never holds both client-route and module-endpoint state.
17890        let responses = handler
17891            .handle_control(
17892                client_connection,
17893                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17894            )
17895            .unwrap();
17896        assert_eq!(responses[0].header.ty, FrameType::Error);
17897        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17898        assert!(registry.get_module("aft-second").unwrap().is_none());
17899    }
17900
17901    #[tokio::test]
17902    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17903        let registry = Arc::new(Registry::default());
17904        let forwarding = Arc::new(ForwardingTable::default());
17905        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
17906        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
17907        hello_via_sink(
17908            &handler,
17909            &module_ctx,
17910            &mut module_rx,
17911            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
17912        )
17913        .await;
17914        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
17915        let pending = forwarding
17916            .begin_route_bind_relay_for_test(
17917                client_ctx.connection_id,
17918                client_ctx.egress.clone(),
17919                2,
17920                "alpha",
17921            )
17922            .unwrap();
17923        forwarding
17924            .complete_pending_relay(
17925                module_ctx.connection_id,
17926                pending.corr,
17927                RouteBindRelayOutcome::Accepted,
17928            )
17929            .unwrap();
17930        client_rx.try_recv().unwrap();
17931        for module_id in ["beta", "alpha"] {
17932            let replies = handler
17933                .handle_control_frame(
17934                    &module_ctx,
17935                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
17936                )
17937                .await
17938                .unwrap();
17939            assert_eq!(replies.len(), 1, "second HELLO must be refused");
17940            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
17941        }
17942        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
17943        assert!(registry.get_module("beta").unwrap().is_none());
17944        assert!(matches!(
17945            forwarding
17946                .lookup_data_route(
17947                    client_ctx.connection_id,
17948                    pending.client_channel,
17949                    pending.client_epoch,
17950                )
17951                .unwrap(),
17952            DataRoute::Client(DataRouteState::Bound(_))
17953        ));
17954        assert!(handler
17955            .hello_launch_nonces
17956            .lock()
17957            .unwrap()
17958            .presented(module_ctx.connection_id, Some("alpha-nonce")));
17959        assert!(module_rx.try_recv().is_err());
17960    }
17961
17962    #[test]
17963    fn reserved_module_hello_requires_matching_launch_nonce() {
17964        let registry = Arc::new(Registry::default());
17965        let supervisor = SupervisorHandle::new();
17966        // The supervisor recorded the nonce it injected when it spawned the reserved
17967        // module; the HELLO verifier checks against the same shared handle.
17968        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
17969        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
17970
17971        // A HELLO with NO nonce is rejected.
17972        let no_nonce = handler
17973            .handle_control(
17974                ConnectionId::new(1),
17975                hello_frame("vault", PROTOCOL_VERSION, 1),
17976            )
17977            .unwrap();
17978        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
17979        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
17980        assert!(registry.get_module("vault").unwrap().is_none());
17981
17982        // A HELLO with the WRONG nonce is rejected.
17983        let wrong = handler
17984            .handle_control(
17985                ConnectionId::new(2),
17986                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
17987            )
17988            .unwrap();
17989        assert_eq!(wrong[0].header.ty, FrameType::Error);
17990        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
17991        assert!(registry.get_module("vault").unwrap().is_none());
17992
17993        // A HELLO with the CORRECT nonce registers.
17994        let ok = handler
17995            .handle_control(
17996                ConnectionId::new(3),
17997                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
17998            )
17999            .unwrap();
18000        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18001        assert!(registry.get_module("vault").unwrap().is_some());
18002    }
18003
18004    #[test]
18005    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18006        let registry = Arc::new(Registry::default());
18007        let supervisor = SupervisorHandle::new();
18008        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18009        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18010        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18011
18012        let squat = handler
18013            .handle_control(
18014                ConnectionId::new(1),
18015                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18016            )
18017            .unwrap();
18018        assert_eq!(squat[0].header.ty, FrameType::Error);
18019        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18020        assert!(parse_error(&squat[0])["message"]
18021            .as_str()
18022            .unwrap()
18023            .contains("fed:"));
18024
18025        let accepted_peer = handler
18026            .handle_control(
18027                ConnectionId::new(2),
18028                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18029            )
18030            .unwrap();
18031        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18032
18033        let accepted_short = handler
18034            .handle_control(
18035                ConnectionId::new(3),
18036                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18037            )
18038            .unwrap();
18039        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18040
18041        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18042            let response = handler
18043                .handle_control(
18044                    ConnectionId::new(conn),
18045                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18046                )
18047                .unwrap();
18048            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18049        }
18050    }
18051
18052    #[test]
18053    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18054        let registry = Arc::new(Registry::default());
18055        let supervisor = SupervisorHandle::new();
18056        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18057        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18058        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18059        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18060
18061        let owner_nonce = handler
18062            .handle_control(
18063                ConnectionId::new(1),
18064                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18065            )
18066            .unwrap();
18067        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18068        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18069        assert!(registry.get_module("fed:special").unwrap().is_none());
18070
18071        let exact_nonce = handler
18072            .handle_control(
18073                ConnectionId::new(2),
18074                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18075            )
18076            .unwrap();
18077        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18078        assert!(registry.get_module("fed:special").unwrap().is_some());
18079    }
18080
18081    #[test]
18082    fn non_reserved_module_ignores_launch_nonce() {
18083        let registry = Arc::new(Registry::default());
18084        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18085        // registration succeeds whether a spawned process echoes a nonce or not.
18086        let handler = ControlHandler::new(Arc::clone(&registry));
18087        let no_nonce = handler
18088            .handle_control(
18089                ConnectionId::new(1),
18090                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18091            )
18092            .unwrap();
18093        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18094        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18095
18096        let echoed_nonce = handler
18097            .handle_control(
18098                ConnectionId::new(2),
18099                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18100            )
18101            .unwrap();
18102        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18103        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18104    }
18105
18106    #[test]
18107    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18108        let handler = ControlHandler::default();
18109        let conn = ConnectionId::new(1);
18110        let malformed = Frame::build(
18111            FrameType::Hello,
18112            control_flags(),
18113            0,
18114            0,
18115            3,
18116            b"{not json".to_vec(),
18117        )
18118        .unwrap();
18119
18120        let error = handler.handle_control(conn, malformed).unwrap();
18121        assert_eq!(error[0].header.ty, FrameType::Error);
18122        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18123
18124        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18125        let pong = handler.handle_control(conn, ping).unwrap();
18126        assert_eq!(pong[0].header.ty, FrameType::Pong);
18127        assert_eq!(pong[0].header.corr, 4);
18128    }
18129
18130    #[test]
18131    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18132        let registry = Arc::new(Registry::default());
18133        let handler = ControlHandler::new(Arc::clone(&registry));
18134
18135        handler
18136            .handle_control(
18137                ConnectionId::new(1),
18138                hello_frame("aft", PROTOCOL_VERSION, 1),
18139            )
18140            .unwrap();
18141        let duplicate = handler
18142            .handle_control(
18143                ConnectionId::new(2),
18144                hello_frame("aft", PROTOCOL_VERSION, 2),
18145            )
18146            .unwrap();
18147
18148        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18149        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18150        let registration = registry.get_module("aft").unwrap().unwrap();
18151        assert_eq!(registration.connection_id, ConnectionId::new(1));
18152    }
18153
18154    #[test]
18155    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18156        let registry = Arc::new(Registry::default());
18157        let forwarding = Arc::new(ForwardingTable::default());
18158        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
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-dead");
18164        let responses = handler
18165            .handle_route_poll(
18166                &ctx,
18167                route_poll_frame(41, PollKind::Liveness, route_channel),
18168                route_channel,
18169                route_epoch,
18170                PollKind::Liveness,
18171            )
18172            .unwrap();
18173
18174        assert_eq!(responses.len(), 1);
18175        assert_eq!(responses[0].header.ty, FrameType::Response);
18176        assert_route_poll_liveness(&responses[0], false);
18177    }
18178
18179    #[test]
18180    fn liveness_poll_without_process_source_uses_bound_route() {
18181        let registry = Arc::new(Registry::default());
18182        let forwarding = Arc::new(ForwardingTable::default());
18183        let handler =
18184            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18185        let (ctx, route_channel, route_epoch) =
18186            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18187        let responses = handler
18188            .handle_route_poll(
18189                &ctx,
18190                route_poll_frame(42, PollKind::Liveness, route_channel),
18191                route_channel,
18192                route_epoch,
18193                PollKind::Liveness,
18194            )
18195            .unwrap();
18196
18197        assert_route_poll_liveness(&responses[0], true);
18198    }
18199
18200    #[test]
18201    fn liveness_poll_untracked_process_source_uses_bound_route() {
18202        let registry = Arc::new(Registry::default());
18203        let forwarding = Arc::new(ForwardingTable::default());
18204        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18205        let handler =
18206            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18207                .with_process_liveness(process_liveness);
18208        let (ctx, route_channel, route_epoch) =
18209            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18210        let responses = handler
18211            .handle_route_poll(
18212                &ctx,
18213                route_poll_frame(43, PollKind::Liveness, route_channel),
18214                route_channel,
18215                route_epoch,
18216                PollKind::Liveness,
18217            )
18218            .unwrap();
18219
18220        assert_route_poll_liveness(&responses[0], true);
18221    }
18222
18223    #[tokio::test]
18224    async fn unknown_op_returns_unknown_control_op() {
18225        let handler = ControlHandler::default();
18226        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18227        let request = Frame::build(
18228            FrameType::Request,
18229            control_flags(),
18230            0,
18231            0,
18232            55,
18233            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18234        )
18235        .unwrap();
18236
18237        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18238
18239        assert_eq!(response.len(), 1);
18240        assert_eq!(response[0].header.ty, FrameType::Error);
18241        assert_eq!(response[0].header.corr, 55);
18242        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18243    }
18244
18245    #[tokio::test]
18246    async fn supervisor_provenance_rejects_unknown_exact_module() {
18247        let handler = ControlHandler::default();
18248        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18249        let request = Frame::build(
18250            FrameType::Request,
18251            control_flags(),
18252            0,
18253            0,
18254            57,
18255            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18256        )
18257        .unwrap();
18258
18259        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18260
18261        assert_eq!(response.len(), 1);
18262        assert_eq!(response[0].header.ty, FrameType::Error);
18263        assert_eq!(response[0].header.corr, 57);
18264        let error = parse_error(&response[0]);
18265        assert_eq!(error["code"], "unknown_module");
18266        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18267    }
18268
18269    #[test]
18270    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18271        let expected = subc_control::RunningImageAgreement::Unavailable {
18272            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18273        };
18274        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18275        assert_eq!(handler.provenance_probe_override, Some(expected));
18276    }
18277
18278    #[test]
18279    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18280        let verdict = reload_verdict(
18281            std::path::Path::new("/bin/new"),
18282            Some(std::path::Path::new("/bin/old")),
18283            subc_control::RunningImageAgreement::Unavailable {
18284                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18285            },
18286        );
18287        assert!(matches!(
18288            verdict.path,
18289            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18290                if configured == std::path::Path::new("/bin/new")
18291                    && spawned_from == std::path::Path::new("/bin/old")
18292        ));
18293    }
18294
18295    #[test]
18296    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18297        use subc_control::{
18298            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18299        };
18300        let configured = crate::supervise::ModuleSpec {
18301            script: None,
18302            carry_containment: false,
18303            module_id: "legacy".into(),
18304            program: "/module".into(),
18305            args: Vec::new(),
18306            env: Vec::new(),
18307            reserved: false,
18308            reserved_prefixes: Vec::new(),
18309            protocol: subc_control::ModuleProtocol::Subc,
18310            overlap: Default::default(),
18311        };
18312        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18313        assert_eq!(
18314            launch_spec_agreement(&configured, false, Some(&digest)),
18315            Agreement::Unavailable {
18316                reason: Reason::NotRunning
18317            }
18318        );
18319        assert_eq!(
18320            launch_spec_agreement(&configured, true, None),
18321            Agreement::Unavailable {
18322                reason: Reason::SpawnedSpecUnavailable
18323            }
18324        );
18325        assert_eq!(
18326            launch_spec_agreement(&configured, true, Some(&digest)),
18327            Agreement::Match
18328        );
18329    }
18330
18331    #[cfg(windows)]
18332    #[test]
18333    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18334        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18335        let configured = dir.join("module.exe");
18336        std::fs::write(&configured, b"executable path fixture").unwrap();
18337        let spawned = std::fs::canonicalize(&configured).unwrap();
18338        assert_ne!(
18339            configured, spawned,
18340            "fixture must exercise different path spellings"
18341        );
18342        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18343        let lower_case = configured.to_string_lossy().to_lowercase();
18344        for spelling in [
18345            &configured,
18346            Path::new(&forward_slashes),
18347            Path::new(&lower_case),
18348        ] {
18349            let verdict = reload_verdict(
18350                spelling,
18351                Some(&spawned),
18352                subc_control::RunningImageAgreement::Unavailable {
18353                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18354                },
18355            );
18356            assert_eq!(
18357                verdict.path,
18358                ReloadPathAgreement::Match,
18359                "configured {spelling:?}, spawned {spawned:?}"
18360            );
18361        }
18362    }
18363
18364    #[cfg(windows)]
18365    #[test]
18366    fn windows_reload_path_keeps_different_existing_program_pending() {
18367        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18368        let old = dir.join("old.exe");
18369        let new = dir.join("new.exe");
18370        std::fs::write(&old, b"same executable content").unwrap();
18371        std::fs::copy(&old, &new).unwrap();
18372        let spawned = std::fs::canonicalize(&old).unwrap();
18373        let image = subc_control::RunningImageAgreement::Unavailable {
18374            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18375        };
18376        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18377        assert!(
18378            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18379            if configured == new && spawned_from == spawned)
18380        );
18381        let missing = dir.join("missing.exe");
18382        assert!(matches!(
18383            reload_verdict(&missing, Some(&spawned), image).path,
18384            ReloadPathAgreement::Mismatch { .. }
18385        ));
18386    }
18387
18388    #[test]
18389    fn reload_verdict_detects_replaced_image_at_same_path() {
18390        let image = subc_control::RunningImageAgreement::Mismatch {
18391            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18392                digest: "old".into(),
18393            },
18394            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18395                digest: "new".into(),
18396            },
18397        };
18398        let verdict = reload_verdict(
18399            std::path::Path::new("/bin/same"),
18400            Some(std::path::Path::new("/bin/same")),
18401            image.clone(),
18402        );
18403        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18404        assert_eq!(verdict.image, image);
18405    }
18406
18407    #[test]
18408    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18409        let image = subc_control::RunningImageAgreement::Unavailable {
18410            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18411        };
18412        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18413        assert_eq!(
18414            verdict.path,
18415            subc_control::ReloadPathAgreement::Unavailable {
18416                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18417            }
18418        );
18419        assert_eq!(verdict.image, image);
18420
18421        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18422            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18423        };
18424        let verdict = reload_verdict(
18425            std::path::Path::new("/bin/same"),
18426            Some(std::path::Path::new("/bin/same")),
18427            unconfirmed.clone(),
18428        );
18429        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18430        assert_eq!(verdict.image, unconfirmed);
18431    }
18432
18433    #[test]
18434    fn reload_verdict_preserves_each_image_unavailability_reason() {
18435        use subc_control::RunningImageUnavailableReason as Reason;
18436
18437        for reason in [
18438            Reason::NotRunning,
18439            Reason::UnsupportedPlatform,
18440            Reason::RunningExecutableUnreadable,
18441            Reason::SpawnedPathUnreadable,
18442            Reason::HashFailed,
18443            Reason::ProcessIdentityUnconfirmed,
18444            Reason::Unknown("future_probe_reason".to_string()),
18445        ] {
18446            let image = subc_control::RunningImageAgreement::Unavailable {
18447                reason: reason.clone(),
18448            };
18449            let verdict = reload_verdict(
18450                std::path::Path::new("/bin/same"),
18451                Some(std::path::Path::new("/bin/same")),
18452                image.clone(),
18453            );
18454            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18455            assert_eq!(verdict.image, image, "{reason:?}");
18456        }
18457    }
18458
18459    #[tokio::test]
18460    async fn malformed_control_bodies_return_invalid_control_body() {
18461        let handler = ControlHandler::default();
18462        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18463
18464        for (corr, body) in [
18465            (56, br#"{"route_channel":1}"#.as_slice()),
18466            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18467            (
18468                58,
18469                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18470            ),
18471        ] {
18472            let request = Frame::build(
18473                FrameType::Request,
18474                control_flags(),
18475                0,
18476                0,
18477                corr,
18478                body.to_vec(),
18479            )
18480            .unwrap();
18481            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18482
18483            assert_eq!(response.len(), 1);
18484            assert_eq!(response[0].header.ty, FrameType::Error);
18485            assert_eq!(response[0].header.corr, corr);
18486            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18487        }
18488    }
18489
18490    #[tokio::test]
18491    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18492        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18493        let registry = Arc::new(Registry::default());
18494        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18495        let router = Router::with_control_handler(Arc::clone(&control));
18496        let connection = router.begin_connection();
18497        let (ctx, mut rx) = route_ctx(connection.id());
18498
18499        router
18500            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18501            .await
18502            .unwrap();
18503        let response = rx.recv().await.unwrap();
18504        let ack = parse_ack(&response);
18505        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18506        let channel = 1;
18507
18508        let goodbye =
18509            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18510        router.route_for_connection(&ctx, goodbye).await.unwrap();
18511        assert!(rx.try_recv().is_err());
18512        assert!(registry.get_module("aft").unwrap().is_none());
18513
18514        router
18515            .route_for_connection(&ctx, channel_request(channel, 13))
18516            .await
18517            .unwrap();
18518        let error_frame = rx.recv().await.unwrap();
18519        assert_eq!(error_frame.header.ty, FrameType::Error);
18520        assert_eq!(error_frame.header.channel, channel);
18521        let captured = crate::router::test_log::captured_logs(&logs);
18522        assert_eq!(
18523            captured
18524                .lines()
18525                .filter(|line| {
18526                    line.contains("module_id=aft")
18527                        && line.contains("reason=explicit_goodbye")
18528                        && line.contains("module registration ended")
18529                })
18530                .count(),
18531            1,
18532            "unexpected GOODBYE registry log: {captured}"
18533        );
18534    }
18535
18536    #[tokio::test]
18537    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18538        let registry = Arc::new(Registry::default());
18539        let handler = ControlHandler::new(registry).with_capability_config(
18540            [("prov".to_string(), true), ("cons".to_string(), true)],
18541            BTreeMap::new(),
18542        );
18543        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18544        register_capability_manifest(
18545            &handler,
18546            &provider_ctx,
18547            &mut provider_rx,
18548            capability_manifest("prov", &["thing/v1"], &[]),
18549            1,
18550        )
18551        .await;
18552        let mut consumer = capability_manifest("cons", &[], &[]);
18553        consumer.capabilities.as_mut().unwrap().requires.push(
18554            subc_protocol::manifest::CapabilityRequirement {
18555                capability: "thing/v1".to_string(),
18556                need: subc_protocol::manifest::CapabilityNeed::Required,
18557            },
18558        );
18559        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18560        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18561        assert_eq!(
18562            handler.capability_evaluator.verdict("cons", "thing/v1"),
18563            Some(CapabilityVerdict::Provided)
18564        );
18565        let (mut client_rx, _) = open_route_for_capability_test(
18566            &handler,
18567            &provider_ctx,
18568            &mut provider_rx,
18569            703,
18570            3,
18571            "prov",
18572            None,
18573        )
18574        .await;
18575        let goodbye =
18576            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18577        handler
18578            .handle_control_frame(&provider_ctx, goodbye)
18579            .await
18580            .unwrap();
18581        assert_eq!(
18582            handler.capability_evaluator.verdict("cons", "thing/v1"),
18583            Some(CapabilityVerdict::NeverProvided)
18584        );
18585        let closed = client_rx
18586            .try_recv()
18587            .expect("GOODBYE pushes route.closed before route GOODBYE");
18588        assert!(
18589            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18590            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18591        );
18592        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18593        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18594    }
18595
18596    struct RouteClosedFixture {
18597        handler: ControlHandler,
18598        #[cfg(unix)]
18599        supervisor: Supervisor,
18600        module_ctx: RouteCtx,
18601        #[cfg(unix)]
18602        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18603        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18604        route: Arc<crate::forwarding::RouteBinding>,
18605    }
18606
18607    async fn route_closed_fixture() -> RouteClosedFixture {
18608        let registry = Arc::new(Registry::default());
18609        let handler = ControlHandler::new(Arc::clone(&registry));
18610        #[cfg(unix)]
18611        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18612            .with_forwarding(Arc::clone(&handler.forwarding));
18613        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18614        register_capability_manifest(
18615            &handler,
18616            &module_ctx,
18617            &mut module_rx,
18618            capability_manifest("prov", &[], &[]),
18619            1,
18620        )
18621        .await;
18622        let (client_rx, bind) = open_route_for_capability_test(
18623            &handler,
18624            &module_ctx,
18625            &mut module_rx,
18626            702,
18627            2,
18628            "prov",
18629            None,
18630        )
18631        .await;
18632        let ModuleControlRequest::RouteBind {
18633            route_channel: channel,
18634            epoch: route_epoch,
18635            ..
18636        } = bind
18637        else {
18638            panic!("expected route.bind");
18639        };
18640        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18641            handler
18642                .forwarding
18643                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18644                .unwrap()
18645        else {
18646            panic!("the acknowledged route must be bound");
18647        };
18648        RouteClosedFixture {
18649            handler,
18650            #[cfg(unix)]
18651            supervisor,
18652            module_ctx,
18653            #[cfg(unix)]
18654            module_rx,
18655            client_rx,
18656            route,
18657        }
18658    }
18659
18660    impl RouteClosedFixture {
18661        #[cfg(unix)]
18662        async fn cut(&mut self) {
18663            let notices = async {
18664                let mut draining = self.module_rx.recv().await.unwrap();
18665                assert!(matches!(
18666                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18667                        &draining.body
18668                    )
18669                    .unwrap(),
18670                    subc_protocol::session::ModuleControlCommand::Draining {
18671                        reason: RouteCloseReason::Disable,
18672                        ..
18673                    }
18674                ));
18675                draining.flushed.take().unwrap().send(()).unwrap();
18676                let mut closing = self.client_rx.recv().await.unwrap();
18677                assert!(matches!(
18678                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18679                    ClientControlPush::RouteClosing {
18680                        reason: RouteCloseReason::Restart,
18681                        ..
18682                    }
18683                ));
18684                closing.flushed.take().unwrap().send(()).unwrap();
18685            };
18686            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18687            result.unwrap();
18688        }
18689
18690        fn disconnect(&mut self) -> ClientControlPush {
18691            self.handler
18692                .cleanup_connection(self.module_ctx.connection_id)
18693                .unwrap();
18694            let closed = self.client_rx.try_recv().unwrap();
18695            assert_eq!(closed.header.ty, FrameType::Push);
18696            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18697            assert!(matches!(
18698                &push,
18699                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18700                    if channels == &[self.route.client_channel]
18701            ));
18702            assert_eq!(
18703                self.client_rx.try_recv().unwrap().header.ty,
18704                FrameType::Goodbye
18705            );
18706            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18707            push
18708        }
18709    }
18710
18711    #[cfg(unix)]
18712    #[tokio::test(start_paused = true)]
18713    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18714        let mut fixture = route_closed_fixture().await;
18715        fixture.cut().await;
18716        assert!(matches!(
18717            fixture.disconnect(),
18718            ClientControlPush::RouteClosed {
18719                reason: RouteCloseReason::Restart,
18720                drained: true,
18721                ..
18722            }
18723        ));
18724    }
18725
18726    #[cfg(unix)]
18727    #[tokio::test(start_paused = true)]
18728    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18729        let mut fixture = route_closed_fixture().await;
18730        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18731        let started = tokio::time::Instant::now();
18732        fixture.cut().await;
18733        assert!(started.elapsed() >= Duration::from_secs(2));
18734        assert_eq!(fixture.route.flow.in_flight(), 1);
18735        assert!(matches!(
18736            fixture.disconnect(),
18737            ClientControlPush::RouteClosed {
18738                reason: RouteCloseReason::Restart,
18739                drained: false,
18740                ..
18741            }
18742        ));
18743    }
18744
18745    #[tokio::test]
18746    async fn module_connection_crash_reports_crash_and_not_drained() {
18747        let mut fixture = route_closed_fixture().await;
18748        // The server calls cleanup_connection on module EOF. Without a planned
18749        // daemon shutdown, that disconnect must remain a crash with no prior
18750        // route.closing notice, even when the route has no in-flight calls.
18751        assert!(matches!(
18752            fixture.disconnect(),
18753            ClientControlPush::RouteClosed {
18754                reason: RouteCloseReason::Crash,
18755                drained: false,
18756                ..
18757            }
18758        ));
18759    }
18760
18761    #[tokio::test]
18762    async fn dropping_router_connection_releases_registration() {
18763        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18764        let registry = Arc::new(Registry::default());
18765        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18766        let router = Router::with_control_handler(Arc::clone(&control));
18767        let connection = router.begin_connection();
18768        let connection_id = connection.id();
18769        let (ctx, mut rx) = route_ctx(connection_id);
18770
18771        router
18772            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18773            .await
18774            .unwrap();
18775        let response = rx.recv().await.unwrap();
18776        let ack = parse_ack(&response);
18777        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18778        assert!(registry.get_module("aft").unwrap().is_some());
18779
18780        drop(connection);
18781
18782        assert!(registry.get_module("aft").unwrap().is_none());
18783        assert_eq!(registry.active_registration_count().unwrap(), 0);
18784
18785        control
18786            .cleanup_connection(ConnectionId::new(u64::MAX))
18787            .unwrap();
18788        let captured = crate::router::test_log::captured_logs(&logs);
18789        println!("captured registry lifecycle logs:\n{captured}");
18790        let events: Vec<_> = captured
18791            .lines()
18792            .filter(|line| {
18793                line.contains("module registered module_id=aft ")
18794                    || line.contains("module registration ended")
18795            })
18796            .collect();
18797        assert_eq!(
18798            events.len(),
18799            2,
18800            "unexpected registry lifecycle logs: {captured}"
18801        );
18802        assert!(events[0].contains("module registered module_id=aft "));
18803        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18804        assert!(events[1].contains(&format!(
18805            "module_id=aft connection_id={}",
18806            connection_id.get()
18807        )));
18808        assert!(events[1].contains("reason=connection_closed"));
18809        assert!(events[1].contains("module registration ended"));
18810        assert_eq!(
18811            captured
18812                .lines()
18813                .filter(|line| line.contains("module registered module_id=aft "))
18814                .count(),
18815            1,
18816            "legacy registration admission line must appear once: {captured}"
18817        );
18818    }
18819
18820    #[tokio::test]
18821    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18822        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18823        let registry = Arc::new(Registry::default());
18824        let control = ControlHandler::new(Arc::clone(&registry));
18825        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18826        hello_via_sink(
18827            &control,
18828            &ctx,
18829            &mut rx,
18830            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18831        )
18832        .await;
18833
18834        let captured = crate::router::test_log::captured_logs(&logs);
18835        let admissions: Vec<_> = captured
18836            .lines()
18837            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18838            .collect();
18839        assert_eq!(
18840            admissions.len(),
18841            1,
18842            "legacy admission line must remain exactly once: {captured}"
18843        );
18844        assert!(admissions[0].contains("routable_provider=true"));
18845        assert!(admissions[0].contains("connection_id=777"));
18846    }
18847
18848    fn capability_manifest(
18849        module_id: &str,
18850        provides: &[&str],
18851        must_never_reach: &[&str],
18852    ) -> ModuleManifest {
18853        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18854        manifest.capabilities = Some(CapabilityDeclarations {
18855            provides: provides
18856                .iter()
18857                .map(|capability| (*capability).to_string())
18858                .collect(),
18859            requires: Vec::new(),
18860            must_never_reach: must_never_reach
18861                .iter()
18862                .map(|capability| (*capability).to_string())
18863                .collect(),
18864        });
18865        manifest
18866    }
18867
18868    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18869        Frame::build(
18870            FrameType::Hello,
18871            control_flags(),
18872            0,
18873            0,
18874            corr,
18875            serde_json::to_vec(&ModuleHelloBody {
18876                protocol_ver: manifest.protocol_ver,
18877                manifest,
18878                control_ops: None,
18879                launch_nonce: None,
18880            })
18881            .expect("capability test HELLO serializes"),
18882        )
18883        .expect("capability test HELLO frame builds")
18884    }
18885
18886    fn catalog_update_with_capabilities_frame(
18887        corr: u64,
18888        capabilities: CapabilityDeclarations,
18889    ) -> Frame {
18890        Frame::build(
18891            FrameType::Request,
18892            control_flags(),
18893            0,
18894            0,
18895            corr,
18896            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18897                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18898                capabilities: Some(capabilities),
18899                ready: None,
18900            })
18901            .expect("capability catalog.update serializes"),
18902        )
18903        .expect("capability catalog.update frame builds")
18904    }
18905
18906    async fn register_capability_manifest(
18907        handler: &ControlHandler,
18908        ctx: &RouteCtx,
18909        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18910        manifest: ModuleManifest,
18911        corr: u64,
18912    ) {
18913        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
18914    }
18915
18916    async fn open_route_for_capability_test(
18917        handler: &ControlHandler,
18918        target_ctx: &RouteCtx,
18919        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18920        client_connection_id: u64,
18921        corr: u64,
18922        target_module_id: &str,
18923        consumer_identity: Option<ConsumerIdentity>,
18924    ) -> (
18925        mpsc::Receiver<crate::router::OutboundFrame>,
18926        ModuleControlRequest,
18927    ) {
18928        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
18929        let route_handler = handler.clone();
18930        let target_module_id = target_module_id.to_string();
18931        let route_task = tokio::spawn(async move {
18932            route_handler
18933                .handle_control_frame(
18934                    &client_ctx,
18935                    route_open_frame_with_admission_facts(
18936                        corr,
18937                        &target_module_id,
18938                        unique_project_root("admission-facts"),
18939                        consumer_identity,
18940                        None,
18941                    ),
18942                )
18943                .await
18944                .expect("capability test route.open succeeds")
18945        });
18946        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
18947            .await
18948            .expect("capability test route.open must reach route.bind")
18949            .expect("target control receiver stays open");
18950        let bind_request: ModuleControlRequest =
18951            serde_json::from_slice(&bind.body).expect("route.bind decodes");
18952        handler
18953            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
18954            .await
18955            .expect("capability test route.bind ACK succeeds");
18956        assert!(route_task.await.expect("route.open task joins").is_empty());
18957        let opened = client_rx
18958            .recv()
18959            .await
18960            .expect("successful route.open publishes a response");
18961        assert!(matches!(
18962            serde_json::from_slice::<ClientControlResponse>(&opened.body),
18963            Ok(ClientControlResponse::RouteOpen { .. })
18964        ));
18965        (client_rx, bind_request)
18966    }
18967
18968    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
18969        assert_eq!(frame.header.ty, FrameType::Push);
18970        assert_eq!(frame.header.channel, 0);
18971        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
18972            .expect("route.closed control push decodes");
18973        let ClientControlPush::RouteClosed { channels, .. } = &push else {
18974            panic!("expected route.closed");
18975        };
18976        assert_eq!(channels.len(), 1, "exactly one violating route closed");
18977        let closed_channel = channels[0];
18978        let channels = channels.clone();
18979        assert_eq!(
18980            push,
18981            ClientControlPush::RouteClosed {
18982                module_id: target_module_id.to_string(),
18983                channels,
18984                reason: RouteCloseReason::CapabilityDenied,
18985                drained: false,
18986                abandoned: 0,
18987                excluded_subscriptions: 0,
18988                terminal: Some(false),
18989            }
18990        );
18991        closed_channel
18992    }
18993
18994    #[tokio::test]
18995    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
18996        let registry = Arc::new(Registry::default());
18997        let forwarding = Arc::new(ForwardingTable::default());
18998        let supervisor = SupervisorHandle::new();
18999        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19000        let handler =
19001            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19002                .with_supervisor(supervisor);
19003        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19004        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19005        register_capability_manifest(
19006            &handler,
19007            &target_ctx,
19008            &mut target_rx,
19009            capability_manifest("target", &["credentials-provider/v1"], &[]),
19010            1,
19011        )
19012        .await;
19013        register_capability_manifest(
19014            &handler,
19015            &opener_ctx,
19016            &mut opener_rx,
19017            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19018            2,
19019        )
19020        .await;
19021
19022        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19023        let replies = handler
19024            .handle_control_frame(
19025                &client_ctx,
19026                route_open_frame_with_admission_facts(
19027                    3,
19028                    "target",
19029                    unique_project_root("admission-facts"),
19030                    Some(ConsumerIdentity {
19031                        module_id: "opener".to_string(),
19032                        launch_nonce: "opener-nonce".to_string(),
19033                    }),
19034                    None,
19035                ),
19036            )
19037            .await
19038            .expect("denied route.open returns a typed frame");
19039        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19040        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19041        assert!(
19042            target_rx.try_recv().is_err(),
19043            "forbidden route.open must not relay route.bind"
19044        );
19045    }
19046
19047    #[tokio::test]
19048    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19049        let registry = Arc::new(Registry::default());
19050        let forwarding = Arc::new(ForwardingTable::default());
19051        let supervisor = SupervisorHandle::new();
19052        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19053        let handler =
19054            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19055                .with_supervisor(supervisor);
19056        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19057        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19058        register_capability_manifest(
19059            &handler,
19060            &target_ctx,
19061            &mut target_rx,
19062            capability_manifest("target", &["credentials-provider/v1"], &[]),
19063            1,
19064        )
19065        .await;
19066        register_capability_manifest(
19067            &handler,
19068            &old_opener_ctx,
19069            &mut old_opener_rx,
19070            capability_manifest("opener", &[], &[]),
19071            2,
19072        )
19073        .await;
19074        let (mut client_rx, _) = open_route_for_capability_test(
19075            &handler,
19076            &target_ctx,
19077            &mut target_rx,
19078            712,
19079            3,
19080            "target",
19081            Some(ConsumerIdentity {
19082                module_id: "opener".to_string(),
19083                launch_nonce: "opener-nonce".to_string(),
19084            }),
19085        )
19086        .await;
19087        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19088
19089        handler
19090            .cleanup_connection(old_opener_ctx.connection_id)
19091            .expect("old opener registration cleans up");
19092        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19093        register_capability_manifest(
19094            &handler,
19095            &new_opener_ctx,
19096            &mut new_opener_rx,
19097            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19098            4,
19099        )
19100        .await;
19101
19102        let closed_channel = assert_capability_denied_push(
19103            client_rx
19104                .try_recv()
19105                .expect("HELLO deny addition must emit route.closed")
19106                .frame,
19107            "target",
19108        );
19109        let goodbye = client_rx
19110            .try_recv()
19111            .expect("HELLO deny addition must send the client a route GOODBYE")
19112            .frame;
19113        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19114        assert_eq!(goodbye.header.channel, closed_channel);
19115        assert_ne!(goodbye.header.channel, 0);
19116        assert_ne!(goodbye.header.epoch, 0);
19117        assert!(client_rx.try_recv().is_err());
19118        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19119        assert!(matches!(
19120            target_rx.try_recv(),
19121            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19122        ));
19123    }
19124
19125    #[tokio::test]
19126    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19127        let registry = Arc::new(Registry::default());
19128        let forwarding = Arc::new(ForwardingTable::default());
19129        let supervisor = SupervisorHandle::new();
19130        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19131        let handler =
19132            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19133                .with_supervisor(supervisor);
19134        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19135        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19136        register_capability_manifest(
19137            &handler,
19138            &target_ctx,
19139            &mut target_rx,
19140            capability_manifest("target", &[], &[]),
19141            1,
19142        )
19143        .await;
19144        register_capability_manifest(
19145            &handler,
19146            &opener_ctx,
19147            &mut opener_rx,
19148            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19149            2,
19150        )
19151        .await;
19152        let (mut client_rx, _) = open_route_for_capability_test(
19153            &handler,
19154            &target_ctx,
19155            &mut target_rx,
19156            722,
19157            3,
19158            "target",
19159            Some(ConsumerIdentity {
19160                module_id: "opener".to_string(),
19161                launch_nonce: "opener-nonce".to_string(),
19162            }),
19163        )
19164        .await;
19165        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19166
19167        let replies = handler
19168            .handle_control_frame(
19169                &target_ctx,
19170                catalog_update_with_capabilities_frame(
19171                    4,
19172                    CapabilityDeclarations {
19173                        provides: vec!["credentials-provider/v1".to_string()],
19174                        requires: Vec::new(),
19175                        must_never_reach: Vec::new(),
19176                    },
19177                ),
19178            )
19179            .await
19180            .expect("claim catalog.update succeeds");
19181        assert!(matches!(
19182            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19183            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19184        ));
19185        let closed_channel = assert_capability_denied_push(
19186            client_rx
19187                .try_recv()
19188                .expect("claim addition must emit route.closed")
19189                .frame,
19190            "target",
19191        );
19192        let goodbye = client_rx
19193            .try_recv()
19194            .expect("claim addition must send the client a route GOODBYE")
19195            .frame;
19196        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19197        assert_eq!(goodbye.header.channel, closed_channel);
19198        assert_ne!(goodbye.header.channel, 0);
19199        assert_ne!(goodbye.header.epoch, 0);
19200        assert!(client_rx.try_recv().is_err());
19201        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19202        assert!(matches!(
19203            target_rx.try_recv(),
19204            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19205        ));
19206    }
19207
19208    #[tokio::test]
19209    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19210        let registry = Arc::new(Registry::default());
19211        let forwarding = Arc::new(ForwardingTable::default());
19212        let supervisor = SupervisorHandle::new();
19213        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19214        let handler =
19215            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19216                .with_supervisor(supervisor);
19217        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19218        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19219        register_capability_manifest(
19220            &handler,
19221            &target_ctx,
19222            &mut target_rx,
19223            capability_manifest("target", &["credentials-provider/v1"], &[]),
19224            1,
19225        )
19226        .await;
19227        register_capability_manifest(
19228            &handler,
19229            &opener_ctx,
19230            &mut opener_rx,
19231            capability_manifest("opener", &[], &[]),
19232            2,
19233        )
19234        .await;
19235        let (mut client_rx, _) = open_route_for_capability_test(
19236            &handler,
19237            &target_ctx,
19238            &mut target_rx,
19239            732,
19240            3,
19241            "target",
19242            Some(ConsumerIdentity {
19243                module_id: "opener".to_string(),
19244                launch_nonce: "opener-nonce".to_string(),
19245            }),
19246        )
19247        .await;
19248        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19249
19250        handler
19251            .handle_control_frame(
19252                &target_ctx,
19253                catalog_update_with_capabilities_frame(
19254                    4,
19255                    CapabilityDeclarations {
19256                        provides: Vec::new(),
19257                        requires: Vec::new(),
19258                        must_never_reach: Vec::new(),
19259                    },
19260                ),
19261            )
19262            .await
19263            .expect("claim removal catalog.update succeeds");
19264        assert_eq!(
19265            forwarding.active_binding_count().unwrap(),
19266            1,
19267            "removing an attested target claim must leave the route census unchanged"
19268        );
19269        assert!(
19270            client_rx.try_recv().is_err(),
19271            "claim removal must not emit route.closed or a client route GOODBYE"
19272        );
19273        assert!(
19274            target_rx.try_recv().is_err(),
19275            "claim removal must not send the target a route GOODBYE"
19276        );
19277    }
19278
19279    /// A direct client may open a route to a denied capability provider; this
19280    /// policy applies only to attested supervised module origins, not to direct clients.
19281    #[tokio::test]
19282    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19283        let registry = Arc::new(Registry::default());
19284        let forwarding = Arc::new(ForwardingTable::default());
19285        let supervisor = SupervisorHandle::new();
19286        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19287        let handler =
19288            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19289                .with_supervisor(supervisor);
19290        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19291        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19292        register_capability_manifest(
19293            &handler,
19294            &target_ctx,
19295            &mut target_rx,
19296            capability_manifest("target", &["credentials-provider/v1"], &[]),
19297            1,
19298        )
19299        .await;
19300        register_capability_manifest(
19301            &handler,
19302            &opener_ctx,
19303            &mut opener_rx,
19304            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19305            2,
19306        )
19307        .await;
19308
19309        let (_client_rx, bind) = open_route_for_capability_test(
19310            &handler,
19311            &target_ctx,
19312            &mut target_rx,
19313            742,
19314            3,
19315            "target",
19316            None,
19317        )
19318        .await;
19319        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19320            panic!("direct scope-honesty route must bind");
19321        };
19322        assert_eq!(principal, Some(Principal::Direct));
19323        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19324    }
19325
19326    /// A module that denies a capability receives no self-route exemption when it
19327    /// also attestedly provides that capability.
19328    #[tokio::test]
19329    async fn must_never_reach_self_route_is_capability_forbidden() {
19330        let registry = Arc::new(Registry::default());
19331        let forwarding = Arc::new(ForwardingTable::default());
19332        let supervisor = SupervisorHandle::new();
19333        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19334        let handler =
19335            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19336                .with_supervisor(supervisor);
19337        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19338        register_capability_manifest(
19339            &handler,
19340            &self_ctx,
19341            &mut self_rx,
19342            capability_manifest(
19343                "self-provider",
19344                &["credentials-provider/v1"],
19345                &["credentials-provider/v1"],
19346            ),
19347            1,
19348        )
19349        .await;
19350
19351        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19352        let replies = handler
19353            .handle_control_frame(
19354                &client_ctx,
19355                route_open_frame_with_admission_facts(
19356                    2,
19357                    "self-provider",
19358                    unique_project_root("admission-facts"),
19359                    Some(ConsumerIdentity {
19360                        module_id: "self-provider".to_string(),
19361                        launch_nonce: "self-nonce".to_string(),
19362                    }),
19363                    None,
19364                ),
19365            )
19366            .await
19367            .expect("self-route refusal returns a typed frame");
19368        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19369        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19370        assert!(
19371            self_rx.try_recv().is_err(),
19372            "self denial must not relay route.bind"
19373        );
19374    }
19375
19376    #[test]
19377    fn unsupported_channel_zero_frame_returns_error() {
19378        let handler = ControlHandler::default();
19379        let request = Frame::build(
19380            FrameType::Request,
19381            control_flags(),
19382            0,
19383            0,
19384            21,
19385            b"opaque".to_vec(),
19386        )
19387        .unwrap();
19388
19389        let response = handler
19390            .handle_control(ConnectionId::new(1), request)
19391            .unwrap();
19392
19393        assert_eq!(response[0].header.ty, FrameType::Error);
19394        assert_eq!(
19395            parse_error(&response[0])["code"],
19396            "unsupported_control_frame"
19397        );
19398    }
19399
19400    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19401    /// a swap is not wired yet, so the candidate is registered here directly
19402    /// into the registry and forwarding candidate slots, the way the swap's
19403    /// HELLO admission will.
19404    mod swap {
19405        use super::*;
19406
19407        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19408        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19409
19410        struct Swap {
19411            registry: Arc<Registry>,
19412            forwarding: Arc<ForwardingTable>,
19413            handler: ControlHandler,
19414            incumbent_ctx: RouteCtx,
19415            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19416            candidate_ctx: RouteCtx,
19417            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19418        }
19419
19420        async fn swap_with_incumbent() -> Swap {
19421            let registry = Arc::new(Registry::default());
19422            let forwarding = Arc::new(ForwardingTable::default());
19423            let handler =
19424                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19425            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19426            hello_via_sink(
19427                &handler,
19428                &incumbent_ctx,
19429                &mut incumbent_rx,
19430                hello_frame("aft", PROTOCOL_VERSION, 7),
19431            )
19432            .await;
19433            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19434            Swap {
19435                registry,
19436                forwarding,
19437                handler,
19438                incumbent_ctx,
19439                incumbent_rx,
19440                candidate_ctx,
19441                candidate_rx,
19442            }
19443        }
19444
19445        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19446            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19447            candidate_manifest.ready = ready;
19448            let registration = swap
19449                .registry
19450                .register_candidate_with_control_ops(
19451                    candidate_manifest,
19452                    PROTOCOL_VERSION,
19453                    CANDIDATE,
19454                    module_baseline_control_ops(),
19455                )
19456                .unwrap();
19457            swap.forwarding
19458                .register_candidate_module_connection(
19459                    CANDIDATE,
19460                    "aft".to_string(),
19461                    PROTOCOL_VERSION,
19462                    manifest_concurrency(&registration.manifest),
19463                    swap.candidate_ctx.egress.clone(),
19464                )
19465                .unwrap();
19466        }
19467
19468        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19469            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19470            swap.registry.promote_candidate("aft").unwrap().unwrap();
19471            cutover.incumbent.unwrap()
19472        }
19473
19474        /// A swap candidate's HELLO reserves its candidate registry entry
19475        /// before installing its candidate forwarding endpoint. The swap
19476        /// supervisor promotes a ready candidate as soon as it reads it as
19477        /// registered, and promotion cuts forwarding over to the candidate
19478        /// endpoint, so the lookup the supervisor reads
19479        /// (`Registry::published_registration`) must not return the candidate
19480        /// until that endpoint exists. Otherwise the cutover finds no candidate
19481        /// endpoint and the swap fails as if the candidate had disconnected.
19482        #[tokio::test]
19483        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19484            let mut swap = swap_with_incumbent().await;
19485            let hold = Arc::new(std::sync::Barrier::new(2));
19486            let handler = swap
19487                .handler
19488                .clone()
19489                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19490            handler
19491                .supervisor
19492                .open_swap("aft", "candidate-nonce".to_string());
19493            let hello = {
19494                let handler = handler.clone();
19495                let candidate_ctx = swap.candidate_ctx.clone();
19496                std::thread::spawn(move || {
19497                    handler
19498                        .handle_hello(
19499                            candidate_ctx.connection_id,
19500                            Some(candidate_ctx.egress.clone()),
19501                            hello_frame_with_nonce(
19502                                "aft",
19503                                PROTOCOL_VERSION,
19504                                8,
19505                                Some("candidate-nonce"),
19506                            ),
19507                        )
19508                        .unwrap()
19509                })
19510            };
19511
19512            hold.wait();
19513            // Parked: the candidate slot is claimed but not published, and
19514            // forwarding has no candidate endpoint.
19515            assert!(swap
19516                .registry
19517                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19518                .unwrap()
19519                .is_some());
19520            assert!(swap
19521                .registry
19522                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19523                .unwrap()
19524                .is_none());
19525            assert!(swap
19526                .forwarding
19527                .module_endpoint_for_connection(CANDIDATE)
19528                .unwrap()
19529                .is_none());
19530
19531            hold.wait();
19532            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19533            assert_eq!(
19534                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19535                FrameType::HelloAck
19536            );
19537            let published = swap
19538                .registry
19539                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19540                .unwrap()
19541                .expect("candidate is published once its HELLO completes");
19542            assert_eq!(published.connection_id, CANDIDATE);
19543            assert!(swap
19544                .forwarding
19545                .module_endpoint_for_connection(CANDIDATE)
19546                .unwrap()
19547                .is_some());
19548        }
19549
19550        #[tokio::test]
19551        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19552            let mut swap = swap_with_incumbent().await;
19553            let hold = Arc::new(std::sync::Barrier::new(2));
19554            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19555            swap.handler
19556                .supervisor
19557                .open_swap("aft", "candidate-nonce".to_string());
19558            let hello = {
19559                let handler = swap.handler.clone();
19560                let candidate_ctx = swap.candidate_ctx.clone();
19561                std::thread::spawn(move || {
19562                    handler
19563                        .handle_hello(
19564                            CANDIDATE,
19565                            Some(candidate_ctx.egress),
19566                            hello_frame_with_nonce(
19567                                "aft",
19568                                PROTOCOL_VERSION,
19569                                8,
19570                                Some("candidate-nonce"),
19571                            ),
19572                        )
19573                        .unwrap()
19574                })
19575            };
19576            hold.wait();
19577            assert_eq!(
19578                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19579                FrameType::HelloAck
19580            );
19581            let reader_registry = Arc::clone(&swap.registry);
19582            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19583                reader_registry
19584                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19585                    .unwrap()
19586            });
19587            assert!(hello.join().unwrap().is_empty());
19588            assert_eq!(
19589                published
19590                    .expect("ACK makes candidate publication visible")
19591                    .connection_id,
19592                CANDIDATE
19593            );
19594            assert_eq!(
19595                swap.registry.generation().unwrap(),
19596                1,
19597                "candidate is not a second catalog entry"
19598            );
19599        }
19600
19601        #[tokio::test]
19602        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19603            let mut swap = swap_with_incumbent().await;
19604            let hold = Arc::new(std::sync::Barrier::new(2));
19605            let handler = swap
19606                .handler
19607                .clone()
19608                .with_hello_registry_to_forwarding_hold(hold.clone());
19609            handler
19610                .supervisor
19611                .open_swap("aft", "candidate-nonce".into());
19612            let hello = {
19613                let handler = handler.clone();
19614                let ctx = swap.candidate_ctx.clone();
19615                std::thread::spawn(move || {
19616                    handler
19617                        .handle_hello(
19618                            CANDIDATE,
19619                            Some(ctx.egress),
19620                            hello_frame_with_nonce(
19621                                "aft",
19622                                PROTOCOL_VERSION,
19623                                8,
19624                                Some("candidate-nonce"),
19625                            ),
19626                        )
19627                        .unwrap()
19628                })
19629            };
19630            hold.wait();
19631            assert_eq!(
19632                swap.registry
19633                    .deregister_connection(CANDIDATE)
19634                    .unwrap()
19635                    .len(),
19636                1
19637            );
19638            hold.wait();
19639            assert!(hello.join().unwrap().is_empty());
19640            assert_eq!(
19641                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19642                FrameType::HelloAck
19643            );
19644            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19645            assert_eq!(
19646                handler
19647                    .supervisor
19648                    .swap_hello_admission("aft", Some("candidate-nonce")),
19649                SwapHelloAdmission::Candidate,
19650                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19651            );
19652            handler.supervisor.close_swap("aft");
19653        }
19654
19655        fn keyed_total(counters: &Value, key: &str) -> u64 {
19656            counters[key]
19657                .as_object()
19658                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19659                .unwrap_or(0)
19660        }
19661
19662        #[tokio::test]
19663        async fn replacement_logs_old_end_and_new_admission_once() {
19664            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19665            let mut swap = swap_with_incumbent().await;
19666            swap.handler
19667                .supervisor
19668                .open_swap("aft", "candidate-nonce".to_string());
19669            hello_via_sink(
19670                &swap.handler,
19671                &swap.candidate_ctx,
19672                &mut swap.candidate_rx,
19673                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19674            )
19675            .await;
19676            cutover(&swap);
19677            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19678
19679            let captured = crate::router::test_log::captured_logs(&logs);
19680            println!("captured replacement registry logs:\n{captured}");
19681            let new_admissions: Vec<_> = captured
19682                .lines()
19683                .filter(|line| {
19684                    line.contains("connection_id=40")
19685                        && line.contains("swap candidate registered; not routable until cutover")
19686                })
19687                .collect();
19688            assert_eq!(
19689                new_admissions.len(),
19690                1,
19691                "unexpected admission logs: {captured}"
19692            );
19693            assert!(new_admissions[0].contains("module_id=aft"));
19694            assert!(new_admissions[0].contains("connection_id=40"));
19695            assert!(
19696                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19697            );
19698            assert!(new_admissions[0].contains("ready=true"));
19699
19700            let old_admissions: Vec<_> = captured
19701                .lines()
19702                .filter(|line| {
19703                    line.contains("module registered module_id=aft ")
19704                        && line.contains("connection_id=30")
19705                })
19706                .collect();
19707            assert_eq!(
19708                old_admissions.len(),
19709                1,
19710                "unexpected incumbent admission: {captured}"
19711            );
19712
19713            let old_ends: Vec<_> = captured
19714                .lines()
19715                .filter(|line| {
19716                    line.contains("connection_id=30") && line.contains("module registration ended")
19717                })
19718                .collect();
19719            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19720            assert!(old_ends[0].contains("module_id=aft"));
19721            assert!(old_ends[0].contains("connection_id=30"));
19722            assert!(old_ends[0].contains("reason=replaced"));
19723            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19724            assert_eq!(
19725                captured
19726                    .lines()
19727                    .filter(|line| line.contains("module registration promoted"))
19728                    .count(),
19729                1,
19730                "unexpected promotion logs: {captured}"
19731            );
19732        }
19733
19734        /// An ack from the incumbent for a bind it was sent before cutover,
19735        /// arriving before the incumbent is drained. The incumbent is the live
19736        /// connection carrying every other client's routes, so the ack must
19737        /// not end it: the waiting client is told to retry, the reservation is
19738        /// given back, and the incumbent is told to drop just that binding.
19739        #[tokio::test]
19740        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19741            let mut swap = swap_with_incumbent().await;
19742            let handler = swap.handler.clone();
19743
19744            // A co-tenant route, bound on the incumbent before the swap.
19745            let cotenant = ConnectionId::new(31);
19746            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19747            let (cotenant_task, cotenant_bind) = relay_route_open(
19748                &handler,
19749                cotenant,
19750                &cotenant_ctx.egress,
19751                &mut swap.incumbent_rx,
19752                100,
19753                "aft",
19754                "swap-cotenant",
19755            )
19756            .await;
19757            handler
19758                .handle_control_frame(
19759                    &swap.incumbent_ctx,
19760                    route_bind_ack(cotenant_bind.header.corr),
19761                )
19762                .await
19763                .unwrap();
19764            assert!(cotenant_task.await.unwrap().is_empty());
19765            let (cotenant_channel, cotenant_epoch) =
19766                published_route(&cotenant_rx.recv().await.unwrap());
19767
19768            // A second route.open, relayed to the incumbent and not yet acked.
19769            let caller = ConnectionId::new(32);
19770            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19771            let (caller_task, caller_bind) = relay_route_open(
19772                &handler,
19773                caller,
19774                &caller_ctx.egress,
19775                &mut swap.incumbent_rx,
19776                101,
19777                "aft",
19778                "swap-caller",
19779            )
19780            .await;
19781            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19782
19783            register_candidate(&swap, None);
19784            cutover(&swap);
19785
19786            // The incumbent acks after promotion and before any drain.
19787            let ack = handler
19788                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19789                .await;
19790            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19791            if module_loop_error.is_some() {
19792                // What the connection loop does with an untranslated router
19793                // error: end the connection, releasing every route on it.
19794                handler.cleanup_connection(INCUMBENT).unwrap();
19795            }
19796
19797            // 1. The incumbent's other routes survive.
19798            assert!(
19799                cotenant_rx.try_recv().is_err(),
19800                "the co-tenant route on the incumbent was torn down by one late ack: \
19801                 {module_loop_error:?}"
19802            );
19803            assert!(matches!(
19804                swap.forwarding
19805                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19806                    .unwrap(),
19807                DataRoute::Client(DataRouteState::Bound(_))
19808            ));
19809            assert_eq!(module_loop_error, None);
19810            assert!(swap
19811                .registry
19812                .get_module_by_connection(INCUMBENT)
19813                .unwrap()
19814                .is_some());
19815
19816            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19817            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19818                .await
19819                .expect("the incumbent is told to drop the abandoned binding")
19820                .unwrap()
19821                .frame;
19822            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19823            assert_eq!(goodbye.header.channel, abandoned_channel);
19824            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19825            assert!(swap.incumbent_rx.try_recv().is_err());
19826
19827            // 3. The waiting client gets a retryable refusal and no route.
19828            let response = caller_task.await.unwrap();
19829            assert_eq!(response.len(), 1);
19830            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19831            assert!(caller_rx.try_recv().is_err());
19832
19833            // 4. The reservation pair is given back, and the pending bind
19834            //    settled exactly once: one accepted open (the co-tenant) and one
19835            //    refused open (the caller), nothing counted twice.
19836            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19837            let counters = handler.counters().snapshot();
19838            assert_eq!(
19839                keyed_total(&counters, "route_open_accepted_by_principal"),
19840                1
19841            );
19842            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19843            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19844        }
19845
19846        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19847        /// id would resolve to the promoted candidate and every new route.open
19848        /// would be refused as reloading, leaving neither process routable.
19849        #[tokio::test]
19850        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19851            let mut swap = swap_with_incumbent().await;
19852            register_candidate(&swap, None);
19853            let incumbent = cutover(&swap);
19854            swap.forwarding
19855                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19856                .unwrap()
19857                .expect("the incumbent is still registered");
19858
19859            let client = ConnectionId::new(33);
19860            let (client_ctx, mut client_rx) = route_ctx(client);
19861            let route_handler = swap.handler.clone();
19862            let open_ctx = RouteCtx {
19863                connection_id: client,
19864                egress: client_ctx.egress.clone(),
19865            };
19866            let mut route_task = tokio::spawn(async move {
19867                route_handler
19868                    .handle_control_frame(
19869                        &open_ctx,
19870                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19871                    )
19872                    .await
19873                    .unwrap()
19874            });
19875            let bind = tokio::select! {
19876                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19877                response = &mut route_task => {
19878                    let response = response.unwrap();
19879                    panic!(
19880                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19881                        parse_error(&response[0])["code"]
19882                    );
19883                }
19884            };
19885            swap.handler
19886                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19887                .await
19888                .unwrap();
19889            assert!(route_task.await.unwrap().is_empty());
19890            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19891            match swap
19892                .forwarding
19893                .lookup_data_route(client, channel, epoch)
19894                .unwrap()
19895            {
19896                DataRoute::Client(DataRouteState::Bound(route)) => {
19897                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19898                }
19899                other => panic!("expected a bound route on the candidate, got {other:?}"),
19900            }
19901            assert!(swap.incumbent_rx.try_recv().is_err());
19902        }
19903
19904        /// A candidate declares itself ready with `catalog.update` on its own
19905        /// connection. If the connection-keyed registry lookups searched only the
19906        /// active slot, this would answer `not_registered` and the candidate
19907        /// would never become ready.
19908        #[tokio::test]
19909        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
19910            let swap = swap_with_incumbent().await;
19911            register_candidate(&swap, Some(false));
19912            let update = Frame::build(
19913                FrameType::Request,
19914                control_flags(),
19915                0,
19916                0,
19917                55,
19918                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
19919                    provides: manifest("aft", PROTOCOL_VERSION).provides,
19920                    capabilities: None,
19921                    ready: Some(true),
19922                })
19923                .unwrap(),
19924            )
19925            .unwrap();
19926
19927            let replies = swap
19928                .handler
19929                .handle_control_frame(&swap.candidate_ctx, update)
19930                .await
19931                .unwrap();
19932
19933            assert_eq!(replies.len(), 1);
19934            assert_eq!(
19935                replies[0].header.ty,
19936                FrameType::Response,
19937                "candidate catalog.update was refused: {:?}",
19938                serde_json::from_slice::<Value>(&replies[0].body).ok()
19939            );
19940            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
19941            assert_eq!(
19942                swap.registry
19943                    .get_module("aft")
19944                    .unwrap()
19945                    .unwrap()
19946                    .connection_id,
19947                INCUMBENT
19948            );
19949        }
19950    }
19951
19952    /// The HELLO gate while the supervisor has a swap open: only the nonce it
19953    /// minted for the candidate admits a second process, into the candidate
19954    /// slot, and that check runs ahead of the reserved-module gate.
19955    mod swap_admission {
19956        use super::*;
19957
19958        const INCUMBENT_NONCE: &str = "incumbent-nonce";
19959        const CANDIDATE_NONCE: &str = "candidate-nonce";
19960
19961        fn handler_with_incumbent(
19962            module_id: &str,
19963            reserved: bool,
19964        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
19965            let registry = Arc::new(Registry::default());
19966            let supervisor = SupervisorHandle::new();
19967            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
19968            if reserved {
19969                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
19970            }
19971            let handler =
19972                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
19973            let incumbent = handler
19974                .handle_control(
19975                    ConnectionId::new(1),
19976                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
19977                )
19978                .unwrap();
19979            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
19980            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
19981            (registry, supervisor, handler)
19982        }
19983
19984        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
19985        /// admits every nonce, so while a swap is open the swap gate is the only
19986        /// thing between a key-holder and the candidate slot. A nonce the
19987        /// supervisor did not mint, or none at all, is refused, and neither the
19988        /// incumbent's registration nor the candidate slot moves.
19989        #[test]
19990        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
19991            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
19992
19993            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
19994                let replies = handler
19995                    .handle_control(
19996                        ConnectionId::new(connection),
19997                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
19998                    )
19999                    .unwrap();
20000                assert_eq!(replies[0].header.ty, FrameType::Error);
20001                assert_eq!(
20002                    parse_error(&replies[0])["code"],
20003                    "swap_token_invalid",
20004                    "nonce {nonce:?}"
20005                );
20006            }
20007            assert!(registry.get_candidate("aft").unwrap().is_none());
20008            assert_eq!(
20009                registry.get_module("aft").unwrap().unwrap().connection_id,
20010                ConnectionId::new(1)
20011            );
20012
20013            // Control: the minted token is admitted, into the candidate slot,
20014            // and only once.
20015            let admitted = handler
20016                .handle_control(
20017                    ConnectionId::new(4),
20018                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20019                )
20020                .unwrap();
20021            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20022            assert_eq!(
20023                registry
20024                    .get_candidate("aft")
20025                    .unwrap()
20026                    .unwrap()
20027                    .connection_id,
20028                ConnectionId::new(4)
20029            );
20030            assert_eq!(
20031                registry.get_module("aft").unwrap().unwrap().connection_id,
20032                ConnectionId::new(1),
20033                "the candidate must not take the active slot"
20034            );
20035            let replayed = handler
20036                .handle_control(
20037                    ConnectionId::new(5),
20038                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20039                )
20040                .unwrap();
20041            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20042
20043            // The case only this gate covers: the incumbent has died mid-swap,
20044            // so its duplicate refusal is gone too, and without the gate a
20045            // key-holder would take the id's ACTIVE slot.
20046            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20047            let squatter = handler
20048                .handle_control(
20049                    ConnectionId::new(6),
20050                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20051                )
20052                .unwrap();
20053            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20054            assert!(
20055                registry.get_module("aft").unwrap().is_none(),
20056                "a squatter took the active slot of an id being swapped"
20057            );
20058        }
20059
20060        /// Design mutation arm (iii). A reserved module's candidate presents a
20061        /// nonce the reserved gate has never seen (that gate holds the
20062        /// incumbent's), so the swap gate must run first or the candidate is
20063        /// refused `reserved_module` and a reserved module can never be swapped.
20064        #[test]
20065        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20066            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20067
20068            let replies = handler
20069                .handle_control(
20070                    ConnectionId::new(2),
20071                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20072                )
20073                .unwrap();
20074
20075            assert_eq!(
20076                replies[0].header.ty,
20077                FrameType::HelloAck,
20078                "reserved candidate refused: {:?}",
20079                serde_json::from_slice::<Value>(&replies[0].body).ok()
20080            );
20081            assert_eq!(
20082                registry
20083                    .get_candidate("vault")
20084                    .unwrap()
20085                    .unwrap()
20086                    .connection_id,
20087                ConnectionId::new(2)
20088            );
20089        }
20090
20091        /// With no swap open the gate is inert: the incumbent's reserved gate
20092        /// and duplicate refusal behave exactly as before.
20093        #[test]
20094        fn without_an_open_swap_the_ordinary_gates_decide() {
20095            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20096            supervisor.close_swap("vault");
20097
20098            let candidate = handler
20099                .handle_control(
20100                    ConnectionId::new(2),
20101                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20102                )
20103                .unwrap();
20104            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20105            let duplicate = handler
20106                .handle_control(
20107                    ConnectionId::new(3),
20108                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20109                )
20110                .unwrap();
20111            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20112            assert!(registry.get_candidate("vault").unwrap().is_none());
20113        }
20114    }
20115
20116    /// `scope.sync` and `scope.describe` through the real control handler: who
20117    /// may sync is decided by the registration and launch nonce of the module
20118    /// connection, never by the request body.
20119    mod scopes {
20120        mod close_reasons {
20121            include!("route_close_reason_tests.rs");
20122        }
20123        mod idle_tests {
20124            use super::*;
20125            include!("scope_idle_tests.rs");
20126        }
20127        mod route_open_timings {
20128            use super::*;
20129            include!("route_open_timing_tests.rs");
20130        }
20131        mod route_open_refusal_log {
20132            use super::*;
20133            include!("route_open_refusal_log_tests.rs");
20134        }
20135        mod activity {
20136            include!("activity_scope_tests.rs");
20137        }
20138        mod delta {
20139            include!("scope_handler_delta_tests.rs");
20140        }
20141        mod watch {
20142            include!("scope_watch_tests.rs");
20143        }
20144        mod call_modes {
20145            include!("scope_call_mode_tests.rs");
20146        }
20147        mod router_audit {
20148            use super::*;
20149            include!("control/router_audit_scope_tests.rs");
20150        }
20151        mod federated {
20152            include!("scope_federated_tests.rs");
20153        }
20154        mod authorize {
20155            include!("route_authorize_tests.rs");
20156        }
20157        #[tokio::test]
20158        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20159            let rig = rig().await;
20160            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20161                "s".into(),
20162                1,
20163                "tool".into(),
20164            ))
20165            .unwrap();
20166            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20167            let (direct, _rx) = wide_ctx(999);
20168            for (ctx, expected) in [
20169                (&rig.owner, FrameType::Response),
20170                (&direct, FrameType::Error),
20171            ] {
20172                let frame =
20173                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20174                        .unwrap();
20175                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20176                assert_eq!(replies[0].header.ty, expected);
20177                if expected == FrameType::Response {
20178                    let reply: subc_control::ScopeServedByReply =
20179                        serde_json::from_slice(&replies[0].body).unwrap();
20180                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20181                } else {
20182                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20183                }
20184            }
20185            let reply = call(
20186                &rig.handler,
20187                &rig.owner,
20188                &ModuleControlRequestFromModule::ScopeDescribe {
20189                    owner: Principal::Reserved {
20190                        module_id: OWNER.into(),
20191                    },
20192                    scope_ref: "s".into(),
20193                },
20194            )
20195            .await;
20196            assert!(matches!(
20197                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20198                ModuleControlResponseToModule::ScopeDescribe { .. }
20199            ));
20200        }
20201
20202        use subc_protocol::scope::{
20203            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20204            ScopeStatus,
20205        };
20206
20207        use super::*;
20208
20209        const OWNER: &str = "prefrontal-core";
20210
20211        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20212            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20213        }
20214
20215        async fn call(
20216            handler: &ControlHandler,
20217            ctx: &RouteCtx,
20218            request: &ModuleControlRequestFromModule,
20219        ) -> Frame {
20220            let body = serde_json::to_vec(request).unwrap();
20221            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20222            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20223            assert_eq!(replies.len(), 1, "{replies:?}");
20224            replies.pop().unwrap()
20225        }
20226
20227        async fn sync(
20228            handler: &ControlHandler,
20229            ctx: &RouteCtx,
20230            generation: u64,
20231            scopes: Vec<ScopeRecord>,
20232        ) -> Result<ModuleControlResponseToModule, String> {
20233            let reply = call(
20234                handler,
20235                ctx,
20236                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20237            )
20238            .await;
20239            match reply.header.ty {
20240                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20241                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20242            }
20243        }
20244
20245        async fn describe(
20246            handler: &ControlHandler,
20247            ctx: &RouteCtx,
20248            owner: &str,
20249            scope_ref: &str,
20250        ) -> ModuleControlResponseToModule {
20251            let reply = call(
20252                handler,
20253                ctx,
20254                &ModuleControlRequestFromModule::ScopeDescribe {
20255                    owner: Principal::Reserved {
20256                        module_id: owner.to_string(),
20257                    },
20258                    scope_ref: scope_ref.to_string(),
20259                },
20260            )
20261            .await;
20262            assert_eq!(
20263                reply.header.ty,
20264                FrameType::Response,
20265                "{:?}",
20266                parse_error(&reply)
20267            );
20268            serde_json::from_slice(&reply.body).unwrap()
20269        }
20270
20271        #[tokio::test]
20272        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20273            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20274            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20275            let mut rig = rig().await;
20276            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20277                .await;
20278            let _bound = rig
20279                .bound(
20280                    Some(AFT),
20281                    PLEXUS,
20282                    Some(
20283                        rig.selector("s", Some(1))
20284                            .with_bind_proof(Some(PROOF.into())),
20285                    ),
20286                )
20287                .await;
20288            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20289            let output = serde_json::to_string(&reply).unwrap();
20290            assert!(output.contains("\"status\":\"live\""));
20291            assert!(!output.contains(PROOF));
20292            assert!(!output.contains(HASH));
20293        }
20294
20295        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20296        async fn module(
20297            handler: &ControlHandler,
20298            connection: u64,
20299            module_id: &str,
20300            nonce: Option<&str>,
20301        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20302            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20303            hello_via_sink(
20304                handler,
20305                &ctx,
20306                &mut rx,
20307                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20308            )
20309            .await;
20310            (ctx, rx)
20311        }
20312
20313        /// `direct` and every other client connection has no registration, so
20314        /// it can neither sync nor own a scope.
20315        #[tokio::test]
20316        async fn a_client_connection_cannot_sync_or_describe() {
20317            let handler = ControlHandler::new(Arc::new(Registry::default()));
20318            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20319            for request in [
20320                ModuleControlRequestFromModule::ScopeSync {
20321                    generation: 1,
20322                    scopes: vec![head("s", 1)],
20323                },
20324                ModuleControlRequestFromModule::ScopeDescribe {
20325                    owner: Principal::Direct,
20326                    scope_ref: "s".to_string(),
20327                },
20328            ] {
20329                let reply = call(&handler, &ctx, &request).await;
20330                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20331            }
20332            assert!(
20333                !handler
20334                    .scopes
20335                    .read()
20336                    .unwrap()
20337                    .describe(
20338                        &Principal::Reserved {
20339                            module_id: OWNER.to_string()
20340                        },
20341                        "s"
20342                    )
20343                    .owner_synced
20344            );
20345        }
20346
20347        /// A module the supervisor did not spawn registers without a launch
20348        /// nonce, so it is never an owner's current launch.
20349        #[tokio::test]
20350        async fn a_module_without_a_supervised_launch_cannot_sync() {
20351            let handler = ControlHandler::new(Arc::new(Registry::default()));
20352            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20353            assert_eq!(
20354                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20355                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20356            );
20357        }
20358
20359        #[tokio::test]
20360        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20361            let supervisor = SupervisorHandle::new();
20362            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20363            let handler = ControlHandler::new(Arc::new(Registry::default()))
20364                .with_supervisor(supervisor.clone());
20365            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20366            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20367                .await
20368                .expect("the current launch syncs");
20369
20370            // A swap candidate registers with the swap token and is refused
20371            // while the incumbent keeps syncing.
20372            supervisor.open_swap(OWNER, "n2".to_string());
20373            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20374            assert_eq!(
20375                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20376                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20377            );
20378            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20379                .await
20380                .expect("the serving owner syncs during the swap");
20381
20382            // The swap fails and is rolled back. The candidate never held sync
20383            // authority, and still cannot sync.
20384            supervisor.close_swap(OWNER);
20385            assert_eq!(
20386                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20387                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20388            );
20389            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20390                .await
20391                .expect("the serving owner syncs after the rollback");
20392            handler.cleanup_connection(candidate.connection_id).unwrap();
20393
20394            // A swap that cuts over. Promotion records the candidate's nonce as
20395            // the module's spawn nonce, which is what `set_spawn_nonce` does
20396            // here; the promoted connection then takes authority at any
20397            // generation and the superseded incumbent is refused.
20398            supervisor.open_swap(OWNER, "n3".to_string());
20399            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20400            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20401            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20402                .await
20403                .expect("the promoted launch takes authority");
20404            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20405                panic!("unexpected reply {reply:?}");
20406            };
20407            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20408            assert_eq!(
20409                sync(&handler, &incumbent, 4, Vec::new()).await,
20410                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20411            );
20412        }
20413
20414        /// Authority dies with its connection: the cleanup path releases it,
20415        /// so the owner's next connection takes it at any generation.
20416        #[tokio::test]
20417        async fn closing_the_authority_connection_frees_sync_authority() {
20418            let supervisor = SupervisorHandle::new();
20419            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20420            let handler = ControlHandler::new(Arc::new(Registry::default()))
20421                .with_supervisor(supervisor.clone());
20422            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20423            sync(&handler, &first, 10, vec![head("s", 1)])
20424                .await
20425                .unwrap();
20426            handler.cleanup_connection(first.connection_id).unwrap();
20427
20428            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20429            sync(&handler, &second, 1, vec![head("s", 1)])
20430                .await
20431                .expect("the next connection takes the released authority");
20432        }
20433
20434        #[tokio::test]
20435        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20436            let supervisor = SupervisorHandle::new();
20437            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20438            let handler =
20439                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20440            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20441            sync(&handler, &first, 10, vec![head("s", 1)])
20442                .await
20443                .unwrap();
20444            handler
20445                .handle_control_frame(
20446                    &first,
20447                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20448                )
20449                .await
20450                .unwrap();
20451            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20452            sync(&handler, &second, 1, vec![head("s", 1)])
20453                .await
20454                .expect("GOODBYE releases authority even if the old socket remains open");
20455        }
20456
20457        #[tokio::test]
20458        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20459            let registry = Arc::new(Registry::default());
20460            let supervisor_handle = SupervisorHandle::new();
20461            let supervisor =
20462                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20463                    .with_handle(supervisor_handle.clone())
20464                    .with_daemon_incarnation("incarnation-7".to_string());
20465            // Configured with enabled: false, so the supervisor lists the
20466            // module without spawning a process for it.
20467            supervisor
20468                .supervise_configured(
20469                    ModuleSpec {
20470                        script: None,
20471                        carry_containment: false,
20472                        module_id: OWNER.to_string(),
20473                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20474                        args: Vec::new(),
20475                        env: Vec::new(),
20476                        reserved: false,
20477                        reserved_prefixes: Vec::new(),
20478                        protocol: ModuleProtocol::Subc,
20479                        overlap: Default::default(),
20480                    },
20481                    false,
20482                )
20483                .unwrap();
20484            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20485            let handler =
20486                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20487            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20488
20489            // Configured but not yet synced: a reader waits for the owner.
20490            let ModuleControlResponseToModule::ScopeDescribe {
20491                status,
20492                daemon_incarnation,
20493                owner_synced,
20494                owner_configured,
20495                scope,
20496                ..
20497            } = describe(&handler, &reader, OWNER, "s").await
20498            else {
20499                panic!("not a describe reply");
20500            };
20501            assert_eq!(status, ScopeStatus::NotLive);
20502            assert_eq!(daemon_incarnation, "incarnation-7");
20503            assert!(!owner_synced);
20504            assert!(owner_configured);
20505            assert!(scope.is_none());
20506
20507            // Not a supervised module: the owner will never sync, and a reader
20508            // refuses rather than waits.
20509            let ModuleControlResponseToModule::ScopeDescribe {
20510                status,
20511                owner_configured,
20512                ..
20513            } = describe(&handler, &reader, "ghost", "s").await
20514            else {
20515                panic!("not a describe reply");
20516            };
20517            assert_eq!(status, ScopeStatus::NotLive);
20518            assert!(!owner_configured);
20519
20520            // Live, with the stamp fields and the computed owner_authorized.
20521            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20522            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20523            let ModuleControlResponseToModule::ScopeDescribe {
20524                status,
20525                scope_epoch,
20526                owner_synced,
20527                scope,
20528                ..
20529            } = describe(&handler, &reader, OWNER, "s").await
20530            else {
20531                panic!("not a describe reply");
20532            };
20533            assert_eq!(status, ScopeStatus::Live);
20534            assert_eq!(scope_epoch, Some(4));
20535            assert!(owner_synced);
20536            let stamp = scope.expect("a live scope carries its stamp");
20537            assert!(
20538                stamp.owner_authorized,
20539                "prefrontal-core is the default authority"
20540            );
20541            assert_eq!(stamp.kind, ScopeKind::Head);
20542        }
20543
20544        #[tokio::test]
20545        async fn scope_authority_owners_decides_owner_authorized() {
20546            let supervisor = SupervisorHandle::new();
20547            supervisor.set_spawn_nonce("broca", "b1".to_string());
20548            let handler = ControlHandler::new(Arc::new(Registry::default()))
20549                .with_supervisor(supervisor)
20550                .with_scope_authority_owners(vec!["broca".to_string()]);
20551            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20552            let mut gated = head("s", 1);
20553            gated.attributes.agent_id = Some("agent".to_string());
20554            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20555            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20556                describe(&handler, &broca, "broca", "s").await
20557            else {
20558                panic!("not a describe reply");
20559            };
20560            assert!(scope.unwrap().owner_authorized);
20561        }
20562
20563        /// With route admission, the stamp, the commit re-check and drains in
20564        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20565        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20566        #[tokio::test]
20567        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20568            let handler = ControlHandler::new(Arc::new(Registry::default()));
20569            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20570            let ack = hello_via_sink(
20571                &handler,
20572                &ctx,
20573                &mut rx,
20574                hello_frame("m", PROTOCOL_VERSION, 1),
20575            )
20576            .await;
20577            let ack = parse_ack(&ack);
20578            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20579                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20580            }
20581            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20582
20583            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20584            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20585            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20586            let reply = handler
20587                .handle_control_frame(&client, frame)
20588                .await
20589                .unwrap()
20590                .pop()
20591                .unwrap();
20592            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20593                serde_json::from_slice(&reply.body).unwrap()
20594            else {
20595                panic!("not a server.describe reply");
20596            };
20597            assert!(
20598                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20599                "{capabilities:?}"
20600            );
20601        }
20602
20603        // ---- route admission, stamps, commit re-check and drains ----------
20604
20605        const PLEXUS: &str = "plexus";
20606        const OTHER: &str = "other";
20607        const AFT: &str = "aft";
20608        const BROCA: &str = "broca";
20609        const MAGIC: &str = "magic-context";
20610
20611        fn nonce(module_id: &str) -> String {
20612            format!("nonce-{module_id}")
20613        }
20614
20615        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20616            let (tx, rx) = mpsc::channel(64);
20617            (
20618                RouteCtx {
20619                    connection_id: ConnectionId::new(connection),
20620                    egress: FrameSink::new(tx),
20621                },
20622                rx,
20623            )
20624        }
20625
20626        /// A daemon with a configured owner (prefrontal-core) registered on its
20627        /// own module connection, two routable targets (plexus, other), and
20628        /// launch nonces minted for the modules that open routes as carriers.
20629        struct Rig {
20630            handler: ControlHandler,
20631            forwarding: Arc<ForwardingTable>,
20632            owner: RouteCtx,
20633            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20634            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20635            generation: u64,
20636            next_connection: u64,
20637            _supervisor: Supervisor,
20638        }
20639
20640        async fn rig() -> Rig {
20641            rig_with_flow_support(true).await
20642        }
20643
20644        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20645            rig_with_scope_capabilities(flow_support, false).await
20646        }
20647
20648        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20649            let mut provides = Vec::new();
20650            if flow_support {
20651                provides.push("flow-scopes/v1");
20652            }
20653            if run_support {
20654                provides.push("agent-run-scopes/v1");
20655            }
20656            rig_with_target_capabilities(&provides).await
20657        }
20658
20659        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20660            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20661            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20662            // Decoder versions alone cannot admit scoped calls: only a capability
20663            // declaration promises the required run or flow behaviour.
20664            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20665            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20666            Frame::build(
20667                FrameType::Hello,
20668                control_flags(),
20669                0,
20670                0,
20671                connection,
20672                serde_json::to_vec(&body).unwrap(),
20673            )
20674            .unwrap()
20675        }
20676
20677        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20678            let registry = Arc::new(Registry::default());
20679            let forwarding = Arc::new(ForwardingTable::default());
20680            let supervisor_handle = SupervisorHandle::new();
20681            let supervisor =
20682                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20683                    .with_handle(supervisor_handle.clone());
20684            supervisor
20685                .supervise_configured(
20686                    ModuleSpec {
20687                        script: None,
20688                        carry_containment: false,
20689                        module_id: OWNER.to_string(),
20690                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20691                        args: Vec::new(),
20692                        env: Vec::new(),
20693                        reserved: false,
20694                        reserved_prefixes: Vec::new(),
20695                        protocol: ModuleProtocol::Subc,
20696                        overlap: Default::default(),
20697                    },
20698                    false,
20699                )
20700                .unwrap();
20701            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20702                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20703            }
20704            let handler =
20705                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20706                    .with_supervisor(supervisor_handle);
20707            let (owner, mut owner_rx) = wide_ctx(1);
20708            hello_via_sink(
20709                &handler,
20710                &owner,
20711                &mut owner_rx,
20712                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20713            )
20714            .await;
20715            let mut modules = BTreeMap::new();
20716            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20717                let (ctx, mut rx) = wide_ctx(connection);
20718                let hello = hello_with_capabilities(module_id, connection, provides);
20719                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20720                modules.insert(module_id.to_string(), (ctx, rx));
20721            }
20722            Rig {
20723                handler,
20724                forwarding,
20725                owner,
20726                _owner_rx: owner_rx,
20727                modules,
20728                generation: 0,
20729                next_connection: 100,
20730                _supervisor: supervisor,
20731            }
20732        }
20733
20734        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20735            ScopeCarrier::new(Principal::Reserved {
20736                module_id: module_id.to_string(),
20737            })
20738            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20739        }
20740
20741        /// The scope most tests open under: aft carries to any module, broca
20742        /// only to plexus and other, and the owner delegates as agent-1.
20743        fn session(scope_epoch: u64) -> ScopeRecord {
20744            let mut record = head("s", scope_epoch);
20745            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20746            record.attributes.agent_id = Some("agent-1".to_string());
20747            record.attributes.delegates = true;
20748            record
20749        }
20750
20751        impl Rig {
20752            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20753                self.generation += 1;
20754                sync(&self.handler, &self.owner, self.generation, scopes)
20755                    .await
20756                    .expect("the owner's sync is accepted");
20757            }
20758
20759            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20760                ScopeSelector::new(
20761                    Principal::Reserved {
20762                        module_id: OWNER.to_string(),
20763                    },
20764                    scope_ref.to_string(),
20765                    scope_epoch,
20766                )
20767            }
20768
20769            fn open_frame(
20770                &mut self,
20771                opener: Option<&str>,
20772                target: &str,
20773                scope: Option<ScopeSelector>,
20774            ) -> (
20775                RouteCtx,
20776                mpsc::Receiver<crate::router::OutboundFrame>,
20777                Frame,
20778            ) {
20779                self.next_connection += 1;
20780                let (ctx, rx) = wide_ctx(self.next_connection);
20781                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20782                    busy_refusals: None,
20783                    target: RouteTarget::ToolProvider {
20784                        module_id: target.to_string(),
20785                    },
20786                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20787                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20788                        module_id: module_id.to_string(),
20789                        launch_nonce: nonce(module_id),
20790                    }),
20791                    consumer_capabilities: None,
20792                    role_versions: None,
20793                    admission_facts: None,
20794                    scope,
20795                })
20796                .unwrap();
20797                let frame = Frame::build(
20798                    FrameType::Request,
20799                    control_flags(),
20800                    0,
20801                    0,
20802                    self.next_connection,
20803                    body,
20804                )
20805                .unwrap();
20806                (ctx, rx, frame)
20807            }
20808
20809            /// Open and expect a refusal before anything is relayed.
20810            async fn refused(
20811                &mut self,
20812                opener: Option<&str>,
20813                target: &str,
20814                scope: Option<ScopeSelector>,
20815            ) -> String {
20816                self.refusal_body(opener, target, scope).await["code"]
20817                    .as_str()
20818                    .unwrap()
20819                    .to_string()
20820            }
20821
20822            async fn refusal_body(
20823                &mut self,
20824                opener: Option<&str>,
20825                target: &str,
20826                scope: Option<ScopeSelector>,
20827            ) -> Value {
20828                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20829                let replies = tokio::time::timeout(
20830                    Duration::from_secs(2),
20831                    self.handler.handle_control_frame(&ctx, frame),
20832                )
20833                .await
20834                .expect("the open must be refused before waiting for a bind ack")
20835                .unwrap();
20836                assert_eq!(replies.len(), 1, "{replies:?}");
20837                assert_eq!(replies[0].header.ty, FrameType::Error);
20838                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20839                assert!(
20840                    module_rx.try_recv().is_err(),
20841                    "a refused open relays nothing"
20842                );
20843                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20844                parse_error(&replies[0])
20845            }
20846
20847            /// Start an open and return its task and the bind the target got.
20848            async fn relayed(
20849                &mut self,
20850                opener: Option<&str>,
20851                target: &str,
20852                scope: Option<ScopeSelector>,
20853            ) -> Relayed {
20854                self.relayed_with_legacy_root(opener, target, scope, None)
20855                    .await
20856            }
20857
20858            async fn relayed_with_legacy_root(
20859                &mut self,
20860                opener: Option<&str>,
20861                target: &str,
20862                scope: Option<ScopeSelector>,
20863                legacy_root: Option<&std::path::Path>,
20864            ) -> Relayed {
20865                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20866                if let Some(root) = legacy_root {
20867                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20868                    body["identity"]["project_root"] = serde_json::json!(root);
20869                    frame.body = serde_json::to_vec(&body).unwrap();
20870                }
20871                let handler = self.handler.clone();
20872                let task_ctx = ctx.clone();
20873                let task = tokio::spawn(async move {
20874                    handler
20875                        .handle_control_frame(&task_ctx, frame)
20876                        .await
20877                        .unwrap()
20878                });
20879                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20880                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20881                    .await
20882                    .expect("the target receives the relayed route.bind")
20883                    .unwrap()
20884                    .frame;
20885                Relayed {
20886                    target: target.to_string(),
20887                    client: ctx,
20888                    client_rx: rx,
20889                    task,
20890                    bind,
20891                }
20892            }
20893
20894            async fn ack(&self, relayed: &Relayed) {
20895                let (module, _) = &self.modules[&relayed.target];
20896                self.handler
20897                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20898                    .await
20899                    .unwrap();
20900            }
20901
20902            /// Open, ack and return the bound route.
20903            async fn bound(
20904                &mut self,
20905                opener: Option<&str>,
20906                target: &str,
20907                scope: Option<ScopeSelector>,
20908            ) -> Bound {
20909                let relayed = self.relayed(opener, target, scope).await;
20910                self.commit_relayed(relayed).await
20911            }
20912
20913            async fn bound_with_legacy_root(
20914                &mut self,
20915                opener: Option<&str>,
20916                target: &str,
20917                scope: Option<ScopeSelector>,
20918                root: &std::path::Path,
20919            ) -> Bound {
20920                let relayed = self
20921                    .relayed_with_legacy_root(opener, target, scope, Some(root))
20922                    .await;
20923                self.commit_relayed(relayed).await
20924            }
20925
20926            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
20927                self.ack(&relayed).await;
20928                let Relayed {
20929                    target,
20930                    client,
20931                    mut client_rx,
20932                    task,
20933                    bind,
20934                } = relayed;
20935                assert!(
20936                    task.await.unwrap().is_empty(),
20937                    "the open is answered by commit"
20938                );
20939                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
20940                Bound {
20941                    target,
20942                    client,
20943                    client_rx,
20944                    channel,
20945                    epoch,
20946                    bind,
20947                }
20948            }
20949
20950            fn live(&self, route: &Bound) -> bool {
20951                matches!(
20952                    self.forwarding
20953                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
20954                        .unwrap(),
20955                    DataRoute::Client(DataRouteState::Bound(_))
20956                )
20957            }
20958        }
20959
20960        struct Relayed {
20961            target: String,
20962            client: RouteCtx,
20963            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20964            task: tokio::task::JoinHandle<Vec<Frame>>,
20965            bind: Frame,
20966        }
20967
20968        struct Bound {
20969            target: String,
20970            client: RouteCtx,
20971            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20972            channel: u16,
20973            epoch: u32,
20974            bind: Frame,
20975        }
20976
20977        impl Bound {
20978            /// The reason of the `route.closed` this client was sent, after
20979            /// checking it also got a GOODBYE on exactly this route.
20980            fn closed_reason(&mut self) -> RouteCloseReason {
20981                let mut reason = None;
20982                let mut goodbye = false;
20983                while let Ok(outbound) = self.client_rx.try_recv() {
20984                    let frame = outbound.frame;
20985                    match frame.header.ty {
20986                        FrameType::Goodbye => {
20987                            assert_eq!(
20988                                (frame.header.channel, frame.header.epoch),
20989                                (self.channel, self.epoch)
20990                            );
20991                            goodbye = true;
20992                        }
20993                        FrameType::Push => {
20994                            let ClientControlPush::RouteClosed {
20995                                reason: r,
20996                                module_id,
20997                                ..
20998                            } = serde_json::from_slice(&frame.body).unwrap()
20999                            else {
21000                                panic!("unexpected push");
21001                            };
21002                            assert_eq!(module_id, self.target);
21003                            reason = Some(r);
21004                        }
21005                        other => panic!("unexpected frame {other:?}"),
21006                    }
21007                }
21008                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21009                reason.expect("the client is told why the route closed")
21010            }
21011
21012            fn untouched(&mut self) -> bool {
21013                self.client_rx.try_recv().is_err()
21014            }
21015
21016            fn stamp(&self) -> Option<ScopeStamp> {
21017                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21018                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21019                    other => panic!("expected a route.bind, got {other:?}"),
21020                }
21021            }
21022        }
21023
21024        #[tokio::test]
21025        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21026        ) {
21027            let mut rig = rig().await;
21028            let mut record = session(1);
21029            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21030            record.child_owners = vec![Principal::Reserved {
21031                module_id: MAGIC.to_string(),
21032            }];
21033            rig.sync(vec![record]).await;
21034            let scope = || Some(rig_selector("s", Some(1)));
21035
21036            // Admitted: the owner, a bare carrier to any module, a targeted
21037            // carrier to its listed module.
21038            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21039            rig.bound(Some(AFT), OTHER, scope()).await;
21040            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21041
21042            // Refused scope_not_carrier: a targeted carrier to an unlisted
21043            // module, a module that is not listed at all (a child owner is not
21044            // a carrier), and a direct key-holder.
21045            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21046                assert_eq!(
21047                    rig.refused(opener, target, scope()).await,
21048                    error_codes::SCOPE_NOT_CARRIER,
21049                    "{opener:?} -> {target}"
21050                );
21051            }
21052        }
21053
21054        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21055            ScopeSelector::new(
21056                Principal::Reserved {
21057                    module_id: OWNER.to_string(),
21058                },
21059                scope_ref.to_string(),
21060                scope_epoch,
21061            )
21062        }
21063
21064        #[tokio::test]
21065        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21066            let mut rig = rig().await;
21067            rig.sync(vec![session(1)]).await;
21068            for opener in [OWNER, AFT] {
21069                assert_eq!(
21070                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21071                        .await,
21072                    error_codes::SCOPE_EPOCH_REQUIRED,
21073                    "{opener}"
21074                );
21075            }
21076        }
21077
21078        #[tokio::test]
21079        async fn admission_separates_not_synced_not_live_and_ended() {
21080            let mut rig = rig().await;
21081            // Before the configured owner's first sync: retryable.
21082            let code = rig
21083                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21084                .await;
21085            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21086            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21087
21088            // An owner that is not configured will never sync: terminal.
21089            let ghost = ScopeSelector::new(
21090                Principal::Reserved {
21091                    module_id: "ghost".to_string(),
21092                },
21093                "s".to_string(),
21094                Some(1),
21095            );
21096            assert_eq!(
21097                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21098                error_codes::SCOPE_NOT_LIVE
21099            );
21100
21101            rig.sync(vec![session(2)]).await;
21102            assert_eq!(
21103                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21104                    .await,
21105                error_codes::SCOPE_NOT_LIVE
21106            );
21107            for epoch in [1, 3] {
21108                assert_eq!(
21109                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21110                        .await,
21111                    error_codes::SCOPE_ENDED,
21112                    "epoch {epoch}"
21113                );
21114            }
21115            // Control: the live epoch is admitted.
21116            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21117                .await;
21118        }
21119
21120        #[tokio::test]
21121        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21122            let mut rig = rig().await;
21123            rig.sync(vec![session(1)]).await;
21124            let route = rig
21125                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21126                .await;
21127            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21128            assert_eq!(stamp.scope_ref, "s");
21129            assert_eq!(stamp.scope_epoch, 1);
21130            assert_eq!(stamp.kind, ScopeKind::Head);
21131            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21132            assert!(stamp.attributes.delegates);
21133            assert!(stamp.owner_authorized);
21134            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21135            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21136
21137            // broca owns a scope of its own on its own module connection; it is
21138            // not in scope_authority_owners, so its stamp is not authorized.
21139            let (broca, mut broca_rx) = wide_ctx(50);
21140            hello_via_sink(
21141                &rig.handler,
21142                &broca,
21143                &mut broca_rx,
21144                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21145            )
21146            .await;
21147            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21148                .await
21149                .unwrap();
21150            let own = ScopeSelector::new(
21151                Principal::Reserved {
21152                    module_id: BROCA.to_string(),
21153                },
21154                "b".to_string(),
21155                Some(1),
21156            );
21157            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21158            assert!(!route.stamp().unwrap().owner_authorized);
21159        }
21160
21161        #[tokio::test]
21162        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21163            let mut rig = rig().await;
21164            let mut record = head("s", 1);
21165            record.carriers = vec![carrier(AFT, None)];
21166            let flow_id = "Flow:run-7/step_2!~";
21167            record.attributes.flow_id = Some(flow_id.to_string());
21168            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21169                .await
21170                .unwrap();
21171            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21172                panic!("not a sync reply");
21173            };
21174            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21175            let route = rig
21176                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21177                .await;
21178            assert!(rig.live(&route), "the stamped bind committed");
21179            let stamp = route.stamp().expect("a flow scope carries a stamp");
21180            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21181            assert_eq!(stamp.attributes.agent_id, None);
21182            assert!(!stamp.attributes.delegates);
21183            assert!(stamp.owner_authorized);
21184            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21185            assert_eq!(unscoped.stamp(), None);
21186        }
21187
21188        #[tokio::test]
21189        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21190            let mut rig = rig_with_flow_support(false).await;
21191            let mut record = session(1);
21192            record.attributes.flow_id = Some("flow:7".to_string());
21193            rig.sync(vec![record]).await;
21194            for opener in [OWNER, AFT] {
21195                let body = rig
21196                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21197                    .await;
21198                assert_eq!(body["code"], "target_flow_unsupported");
21199                let message = body["message"].as_str().unwrap();
21200                for required in [PLEXUS, "flow-scopes/v1"] {
21201                    assert!(message.contains(required), "{message}");
21202                }
21203            }
21204        }
21205
21206        #[tokio::test]
21207        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21208            let mut rig = rig_with_flow_support(true).await;
21209            let mut record = session(1);
21210            record.attributes.flow_id = Some("flow:7".to_string());
21211            rig.sync(vec![record]).await;
21212            for opener in [OWNER, AFT] {
21213                let route = rig
21214                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21215                    .await;
21216                assert!(rig.live(&route));
21217                assert_eq!(
21218                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21219                    Some("flow:7")
21220                );
21221            }
21222        }
21223
21224        #[tokio::test]
21225        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21226            use std::future::Future;
21227
21228            let mut rig = rig_with_flow_support(true).await;
21229            let mut record = session(1);
21230            record.attributes.flow_id = Some("flow:7".to_string());
21231            rig.sync(vec![record]).await;
21232            let (client, mut client_rx, frame) =
21233                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21234            // Hold the route-open response permit so admission sees the first
21235            // target but relay reservation cannot capture an endpoint yet.
21236            for _ in 0..64 {
21237                client.egress.try_send(route_bind_ack(1)).unwrap();
21238            }
21239            let handler = rig.handler.clone();
21240            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21241            std::future::poll_fn(|cx| {
21242                assert!(open.as_mut().poll(cx).is_pending());
21243                std::task::Poll::Ready(())
21244            })
21245            .await;
21246            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21247
21248            let old_connection = rig.modules[PLEXUS].0.connection_id;
21249            rig.handler.cleanup_connection(old_connection).unwrap();
21250            let (replacement, mut replacement_rx) = wide_ctx(200);
21251            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21252            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21253            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21254            let hello = Frame::build(
21255                FrameType::Hello,
21256                control_flags(),
21257                0,
21258                0,
21259                200,
21260                serde_json::to_vec(&body).unwrap(),
21261            )
21262            .unwrap();
21263            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21264
21265            client_rx.try_recv().unwrap();
21266            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21267                .await
21268                .expect("the replacement is refused without waiting for a bind ack")
21269                .unwrap();
21270            assert_eq!(replies.len(), 1);
21271            let body = parse_error(&replies[0]);
21272            assert_eq!(body["code"], "target_flow_unsupported");
21273            for required in [PLEXUS, "flow-scopes/v1"] {
21274                assert!(body["message"].as_str().unwrap().contains(required));
21275            }
21276            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21277            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21278            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21279            assert!(rig
21280                .handler
21281                .registry
21282                .get_module_by_connection(replacement.connection_id)
21283                .unwrap()
21284                .is_some());
21285        }
21286
21287        #[tokio::test]
21288        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21289            use std::future::Future;
21290            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21291            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21292            const NEXT_HASH: &str =
21293                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21294            let mut rig = rig().await;
21295            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21296            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21297            rig.sync(vec![record.clone()]).await;
21298            let (client, mut rx, frame) = rig.open_frame(
21299                None,
21300                PLEXUS,
21301                Some(
21302                    rig.selector("s", Some(1))
21303                        .with_bind_proof(Some(PROOF.into())),
21304                ),
21305            );
21306            // Hold egress reservation while the scope owner changes its bind-proof
21307            // hash, so a proof valid at admission must be checked again at relay.
21308            for _ in 0..64 {
21309                client.egress.try_send(route_bind_ack(1)).unwrap();
21310            }
21311            let handler = rig.handler.clone();
21312            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21313            std::future::poll_fn(|cx| {
21314                assert!(open.as_mut().poll(cx).is_pending());
21315                std::task::Poll::Ready(())
21316            })
21317            .await;
21318            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21319            rig.sync(vec![record]).await;
21320            rx.try_recv().unwrap();
21321            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21322                .await
21323                .unwrap()
21324                .unwrap();
21325            assert_eq!(
21326                parse_error(&replies[0])["code"],
21327                error_codes::SCOPE_BIND_PROOF_MISMATCH
21328            );
21329            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21330            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21331            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21332        }
21333
21334        #[tokio::test]
21335        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21336            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21337            let mut rig = rig().await;
21338            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21339                .await;
21340            for opener in [OWNER, AFT] {
21341                for proof in [None, Some("malformed+proof=")] {
21342                    let route = rig
21343                        .bound(
21344                            Some(opener),
21345                            PLEXUS,
21346                            Some(
21347                                rig.selector("s", Some(1))
21348                                    .with_bind_proof(proof.map(str::to_string)),
21349                            ),
21350                        )
21351                        .await;
21352                    assert!(rig.live(&route));
21353                }
21354            }
21355        }
21356
21357        #[tokio::test]
21358        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21359            use std::future::Future;
21360            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21361            const NEXT_HASH: &str =
21362                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21363            let mut rig = rig().await;
21364            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21365                .await;
21366            let (client, mut rx, frame) =
21367                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21368            for _ in 0..64 {
21369                client.egress.try_send(route_bind_ack(1)).unwrap();
21370            }
21371            let handler = rig.handler.clone();
21372            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21373            std::future::poll_fn(|cx| {
21374                assert!(open.as_mut().poll(cx).is_pending());
21375                std::task::Poll::Ready(())
21376            })
21377            .await;
21378            rig.sync(vec![
21379                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21380            ])
21381            .await;
21382            rx.try_recv().unwrap();
21383            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21384            let bind = std::future::poll_fn(|cx| {
21385                assert!(open.as_mut().poll(cx).is_pending());
21386                module_rx.poll_recv(cx)
21387            })
21388            .await
21389            .unwrap()
21390            .frame;
21391            handler
21392                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21393                .await
21394                .unwrap();
21395            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21396                .await
21397                .unwrap()
21398                .unwrap();
21399            assert_eq!(replies.len(), 1);
21400            // Proof rechecking allowed the relay. Independent tag settlement
21401            // still asks the opener to retry after any same-epoch content change.
21402            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21403            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21404            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21405            let route = rig
21406                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21407                .await;
21408            assert!(rig.live(&route));
21409        }
21410
21411        #[tokio::test]
21412        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21413        {
21414            let mut rig = rig_with_flow_support(false).await;
21415            rig.sync(vec![session(1)]).await;
21416            let route = rig
21417                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21418                .await;
21419            assert!(rig.live(&route));
21420            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21421            let mut record = session(1);
21422            record.attributes.flow_id = Some("flow:7".to_string());
21423            rig.sync(vec![record]).await;
21424            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21425            assert!(rig.live(&unscoped));
21426            assert_eq!(unscoped.stamp(), None);
21427        }
21428
21429        #[tokio::test]
21430        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21431            let mut rig = rig().await;
21432            let mut record = session(1);
21433            record.attributes.flow_id = Some("flow:7".to_string());
21434            rig.sync(vec![record.clone()]).await;
21435            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21436            let mut owner_route = rig
21437                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21438                .await;
21439            let mut carrier_route = rig
21440                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21441                .await;
21442            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21443            rig.sync(vec![record.clone()]).await;
21444            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21445            assert!(rig.live(&owner_route) && owner_route.untouched());
21446            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21447
21448            record.attributes.flow_id = Some("flow:8".to_string());
21449            rig.sync(vec![record]).await;
21450            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21451            let before = before.unwrap();
21452            assert_eq!(after.scope_epoch, before.scope_epoch);
21453            assert!(after.version > before.version);
21454            for route in [&mut owner_route, &mut carrier_route] {
21455                assert!(!rig.live(route));
21456                assert_eq!(
21457                    route.closed_reason(),
21458                    RouteCloseReason::ScopeDelegationChanged
21459                );
21460            }
21461            assert!(rig.live(&unscoped) && unscoped.untouched());
21462            // Each provider also receives a GOODBYE for its drained route;
21463            // consume it before expecting the next route.bind on that sink.
21464            for target in [PLEXUS, OTHER] {
21465                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21466                let goodbye = module_rx
21467                    .try_recv()
21468                    .expect("the provider sees the drain")
21469                    .frame;
21470                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21471                assert!(module_rx.try_recv().is_err());
21472            }
21473            let rebound = rig
21474                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21475                .await;
21476            assert_eq!(
21477                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21478                Some("flow:8")
21479            );
21480        }
21481
21482        /// The owner's sync lands between admission and the module's ack. The
21483        /// open is refused by name, the module's other routes stay up, and the
21484        /// reserved pair is released. Changed content is retryable; an ended
21485        /// scope is not.
21486        #[tokio::test]
21487        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21488            let mut rig = rig().await;
21489            rig.sync(vec![session(1)]).await;
21490            let mut cotenant = rig
21491                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21492                .await;
21493
21494            let mut changed = session(1);
21495            changed.child_owners.push(Principal::Reserved {
21496                module_id: MAGIC.to_string(),
21497            });
21498            let mut ended = None;
21499            for (code, next) in [
21500                (error_codes::SCOPE_CHANGED, vec![changed]),
21501                (error_codes::SCOPE_ENDED, Vec::new()),
21502            ] {
21503                let relayed = rig
21504                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21505                    .await;
21506                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21507                ended = Some(next.is_empty());
21508                rig.sync(next).await;
21509                rig.ack(&relayed).await;
21510                let replies = relayed.task.await.unwrap();
21511                assert_eq!(replies.len(), 1, "{replies:?}");
21512                assert_eq!(parse_error(&replies[0])["code"], code);
21513                assert_eq!(
21514                    subc_protocol::error_codes::is_retryable_route_open(code),
21515                    code == error_codes::SCOPE_CHANGED
21516                );
21517                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21518                // The module is told to drop just the binding it created.
21519                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21520                // Collected, because ending the scope also closes the co-tenant
21521                // route, whose GOODBYE comes first.
21522                let mut goodbyes = Vec::new();
21523                while let Ok(outbound) = plexus_rx.try_recv() {
21524                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21525                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21526                }
21527                assert!(
21528                    goodbyes.contains(&(bind_channel, bind_epoch)),
21529                    "{goodbyes:?}"
21530                );
21531                assert!(rig
21532                    .handler
21533                    .registry
21534                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21535                    .unwrap()
21536                    .is_some());
21537            }
21538            assert_eq!(ended, Some(true));
21539            // The co-tenant stayed up through the change, and closed only when
21540            // the scope ended, by the drain rule rather than by the commit.
21541            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21542        }
21543
21544        /// Each row of the drain table on one set of routes: the owner's, a
21545        /// bare carrier's, and a targeted carrier's to each of its targets.
21546        #[tokio::test]
21547        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21548            struct Case {
21549                name: &'static str,
21550                change: fn(&mut ScopeRecord),
21551                /// Closed routes by index: owner->plexus, aft->plexus,
21552                /// broca->plexus, broca->other.
21553                closed: [Option<RouteCloseReason>; 4],
21554            }
21555            use RouteCloseReason::*;
21556            let cases = [
21557                Case {
21558                    name: "a carrier entry removed",
21559                    change: |r| {
21560                        r.carriers.retain(|c| {
21561                            c.principal
21562                                != Principal::Reserved {
21563                                    module_id: AFT.to_string(),
21564                                }
21565                        })
21566                    },
21567                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21568                },
21569                Case {
21570                    name: "a target removed from a carrier",
21571                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21572                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21573                },
21574                Case {
21575                    name: "a bare carrier narrowed to targets",
21576                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21577                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21578                },
21579                Case {
21580                    name: "delegates turned off",
21581                    change: |r| r.attributes.delegates = false,
21582                    closed: [Some(ScopeDelegationChanged); 4],
21583                },
21584                Case {
21585                    name: "agent_id changed",
21586                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21587                    closed: [Some(ScopeDelegationChanged); 4],
21588                },
21589                Case {
21590                    name: "a carrier added, child owners changed, the record re-sent",
21591                    change: |r| {
21592                        r.carriers.push(carrier(MAGIC, None));
21593                        r.child_owners.push(Principal::Reserved {
21594                            module_id: MAGIC.to_string(),
21595                        });
21596                    },
21597                    closed: [None; 4],
21598                },
21599                Case {
21600                    name: "a target added",
21601                    change: |r| {
21602                        r.carriers[1]
21603                            .targets
21604                            .as_mut()
21605                            .unwrap()
21606                            .push("third".to_string())
21607                    },
21608                    closed: [None; 4],
21609                },
21610                Case {
21611                    name: "delegates turned on",
21612                    change: |r| r.attributes.delegates = true,
21613                    closed: [None; 4],
21614                },
21615            ];
21616            for case in cases {
21617                let mut rig = rig().await;
21618                rig.sync(vec![session(1)]).await;
21619                let scope = || Some(rig_selector("s", Some(1)));
21620                let mut routes = [
21621                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21622                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21623                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21624                    rig.bound(Some(BROCA), OTHER, scope()).await,
21625                ];
21626                let mut record = session(1);
21627                (case.change)(&mut record);
21628                rig.sync(vec![record]).await;
21629                for (index, expected) in case.closed.iter().enumerate() {
21630                    let route = &mut routes[index];
21631                    match expected {
21632                        Some(reason) => {
21633                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21634                            assert_eq!(
21635                                route.closed_reason(),
21636                                *reason,
21637                                "{}: route {index}",
21638                                case.name
21639                            );
21640                        }
21641                        None => {
21642                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21643                            assert!(
21644                                route.untouched(),
21645                                "{}: route {index} was told something",
21646                                case.name
21647                            );
21648                        }
21649                    }
21650                }
21651            }
21652        }
21653
21654        #[tokio::test]
21655        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21656            // Removed, and replaced by a higher epoch.
21657            for next in [Vec::new(), vec![session(2)]] {
21658                let mut rig = rig().await;
21659                rig.sync(vec![session(1)]).await;
21660                let mut route = rig
21661                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21662                    .await;
21663                rig.sync(next).await;
21664                assert!(!rig.live(&route));
21665                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21666            }
21667
21668            // A child whose parent ends: its routes close as parent-ended, the
21669            // child stays live, and routes under the parent close as ended.
21670            let mut rig = rig().await;
21671            let mut child = session(1);
21672            child.scope_ref = "child".to_string();
21673            child.kind = ScopeKind::Worker;
21674            child.parent = Some(ScopeParent::new(
21675                Principal::Reserved {
21676                    module_id: OWNER.to_string(),
21677                },
21678                "s".to_string(),
21679                1,
21680            ));
21681            rig.sync(vec![session(1), child.clone()]).await;
21682            let mut child_route = rig
21683                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21684                .await;
21685            assert_eq!(
21686                child_route.stamp().unwrap().parent_state,
21687                Some(ParentState::Linked)
21688            );
21689            rig.sync(vec![child]).await;
21690            assert!(!rig.live(&child_route));
21691            assert_eq!(
21692                child_route.closed_reason(),
21693                RouteCloseReason::ScopeParentEnded
21694            );
21695        }
21696
21697        #[tokio::test]
21698        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21699        ) {
21700            let mut rig = rig().await;
21701            rig.sync(vec![session(1)]).await;
21702            let mut route = rig
21703                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21704                .await;
21705            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21706            rig.sync(vec![session(1)]).await;
21707            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21708            assert!(rig.live(&route) && route.untouched());
21709
21710            // A call in flight on the route when another carrier is added. A
21711            // forwarded REQUEST holds one credit on the route's flow until the
21712            // module answers; the router takes it exactly like this.
21713            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21714                .forwarding
21715                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21716                .unwrap()
21717            else {
21718                panic!("the route is bound");
21719            };
21720            binding.flow.acquire_tagged(9, false).await.unwrap();
21721            let mut widened = session(1);
21722            widened.carriers.push(carrier(MAGIC, None));
21723            rig.sync(vec![widened]).await;
21724            assert!(rig.live(&route) && route.untouched());
21725            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21726            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21727            // The call's credit is still held on an open flow, so its answer
21728            // will be delivered: closing the route would have closed the flow.
21729            assert_eq!(binding.flow.in_flight(), 1);
21730            binding
21731                .flow
21732                .acquire_tagged(10, false)
21733                .await
21734                .expect("the flow is still open");
21735        }
21736
21737        /// A swap's superseded endpoint keeps its routes until drained; ending
21738        /// the scope closes them there too.
21739        #[tokio::test]
21740        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21741            let mut rig = rig().await;
21742            rig.sync(vec![session(1)]).await;
21743            let mut on_incumbent = rig
21744                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21745                .await;
21746
21747            // Swap plexus: register a candidate and cut over, leaving the
21748            // incumbent superseded with the route still on it.
21749            let (candidate, _candidate_rx) = wide_ctx(9);
21750            let registration = rig
21751                .handler
21752                .registry
21753                .register_candidate_with_control_ops(
21754                    manifest(PLEXUS, PROTOCOL_VERSION),
21755                    PROTOCOL_VERSION,
21756                    candidate.connection_id,
21757                    module_baseline_control_ops(),
21758                )
21759                .unwrap();
21760            rig.forwarding
21761                .register_candidate_module_connection(
21762                    candidate.connection_id,
21763                    PLEXUS.to_string(),
21764                    PROTOCOL_VERSION,
21765                    manifest_concurrency(&registration.manifest),
21766                    candidate.egress.clone(),
21767                )
21768                .unwrap();
21769            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21770            rig.handler
21771                .registry
21772                .promote_candidate(PLEXUS)
21773                .unwrap()
21774                .unwrap();
21775            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21776
21777            rig.sync(Vec::new()).await;
21778            assert!(!rig.live(&on_incumbent));
21779            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21780            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21781            let goodbye = incumbent_rx
21782                .try_recv()
21783                .expect("the superseded endpoint is told")
21784                .frame;
21785            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21786        }
21787    }
21788}
21789
21790#[cfg(test)]
21791mod concurrency_default_exposure_tests {
21792    use super::*;
21793
21794    fn hello_body(role_json: &str) -> Vec<u8> {
21795        format!(
21796            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":[]}}}}}}}}"#
21797        )
21798        .into_bytes()
21799    }
21800
21801    fn manifest_from(body: &[u8]) -> ModuleManifest {
21802        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21803        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21804            .expect("manifest parses")
21805    }
21806
21807    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21808
21809    #[test]
21810    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21811        let body = hello_body(&format!(
21812            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21813        ));
21814        let manifest = manifest_from(&body);
21815        // Precondition: serde really resolved it to the default, so the typed
21816        // manifest alone cannot answer the question this probe exists for.
21817        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21818        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21819    }
21820
21821    #[test]
21822    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21823        let body = hello_body(&format!(
21824            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21825        ));
21826        let manifest = manifest_from(&body);
21827        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21828        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21829    }
21830
21831    #[test]
21832    fn non_management_roles_are_never_reported() {
21833        let body = hello_body(
21834            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21835        );
21836        let manifest = manifest_from(&body);
21837        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21838    }
21839}