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};
172#[cfg(all(test, unix, feature = "test-support"))]
173#[path = "control/caller_attestation_tests.rs"]
174mod caller_attestation_tests;
175mod scope_expiry;
176mod scope_watch;
177mod usage;
178
179mod agent_commands;
180pub(crate) mod catalog;
181mod rescan_checked;
182use rescan_checked::{RescanMode, RescanPlan};
183
184const MODULE_TO_SUBC_CONTROL_OPS: &[&str] = &[
185    "claim.mint",
186    "claim.present",
187    MODULE_TO_SUBC_OP_CATALOG_UPDATE,
188    MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
189    "supervisor.live_roots",
190    "supervisor.agent_commands",
191    SCOPE_SYNC_OP,
192    SCOPE_APPLY_OP,
193    SCOPE_DESCRIBE_OP,
194    ops::SCOPE_WATCH,
195    subc_protocol::scope::ROUTE_AUTHORIZE_OP,
196    "operator.confirm",
197];
198
199/// Module-originated ops the daemon answers but does not advertise in
200/// `HELLO_ACK`. Empty today; an op is served from here while the feature it
201/// belongs to is incomplete, so no module is told it works before it does.
202const MODULE_TO_SUBC_UNADVERTISED_OPS: &[&str] = &[];
203
204const MODULE_BASELINE_CONTROL_OPS: &[&str] = &["route.bind", "route.status"];
205
206/// How long subc waits for a module to ack a relayed route.bind before returning
207/// `module_timeout`. The ack waits on the module's own configure, which for AFT
208/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
209/// and DB-open work — on a cold page cache or a large repo that legitimately
210/// exceeds a couple of seconds. The default is generous because rejecting a VALID
211/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
212/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
213pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
214
215/// How many CONSECUTIVE full-budget relay timeouts against one target module
216/// open that module's bind-relay breaker.
217///
218/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
219/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
220/// so three consecutive full-budget timeouts take ~36s to observe: every client
221/// whose open contributed to opening the breaker had already given up on its
222/// own. That is what makes opening the breaker unable to turn a call that would
223/// have succeeded into a refusal — it can only make an already-failing module
224/// fail faster.
225///
226/// Two would be reachable inside one default deadline. One would convict a
227/// module on a single cold-cache bind, which is exactly the valid-but-slow case
228/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
229pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
230
231/// How long a module's bind-relay breaker stays open before exactly one
232/// `route.open` is let through as a probe.
233///
234/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
235/// re-pays a full-budget stall almost continuously, and the breaker stops being
236/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
237/// deadline: a client that starts retrying after the module recovers has to get
238/// a probe opportunity inside its own deadline, or the breaker converts a
239/// recovered module into a failed call — the failure it exists to prevent,
240/// pointed the other way.
241///
242/// 20s sits between those with room on both sides, and it caps what a wedged
243/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
244/// rather than one per `route.open` per connection. The stall that motivated
245/// this, with its measurements, is written up in
246/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
247/// waited the whole budget out.
248pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
249
250const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
251const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
252
253fn reload_verdict(
254    configured: &Path,
255    spawned_from: Option<&Path>,
256    image: subc_control::RunningImageAgreement,
257) -> PendingReloadVerdict {
258    let path = match spawned_from {
259        Some(spawned_from) if reload_paths_match(configured, spawned_from) => {
260            ReloadPathAgreement::Match
261        }
262        Some(spawned_from) => ReloadPathAgreement::Mismatch {
263            configured: configured.to_path_buf(),
264            spawned_from: spawned_from.to_path_buf(),
265        },
266        None => ReloadPathAgreement::Unavailable {
267            reason: if matches!(
268                image,
269                subc_control::RunningImageAgreement::Unavailable {
270                    reason: subc_control::RunningImageUnavailableReason::NotRunning
271                }
272            ) {
273                ReloadPathUnavailableReason::NotRunning
274            } else {
275                ReloadPathUnavailableReason::SpawnedPathUnavailable
276            },
277        },
278    };
279    PendingReloadVerdict::new(path, image)
280}
281
282fn launch_spec_agreement(
283    configured: &crate::supervise::ModuleSpec,
284    running: bool,
285    spawned: Option<&crate::supervise::LaunchSpecDigest>,
286) -> subc_control::LaunchSpecAgreement {
287    use subc_control::{LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason};
288    if !running {
289        return Agreement::Unavailable {
290            reason: Reason::NotRunning,
291        };
292    }
293    match spawned {
294        None => Agreement::Unavailable {
295            reason: Reason::SpawnedSpecUnavailable,
296        },
297        Some(digest) if *digest == crate::supervise::LaunchSpecDigest::from_spec(configured) => {
298            Agreement::Match
299        }
300        Some(_) => Agreement::Mismatch,
301    }
302}
303
304fn reload_paths_match(configured: &Path, spawned_from: &Path) -> bool {
305    if configured == spawned_from {
306        return true;
307    }
308    #[cfg(windows)]
309    {
310        // Windows spawn records the resolved verbatim path (\\?\...), while
311        // configuration keeps its original spelling. Resolve both with the OS
312        // instead of stripping prefixes or folding case, which could conflate
313        // distinct names in case-sensitive directories. Different resolved
314        // paths still differ even if their files have identical content.
315        match (
316            std::fs::canonicalize(configured),
317            std::fs::canonicalize(spawned_from),
318        ) {
319            (Ok(configured), Ok(spawned_from)) => configured == spawned_from,
320            _ => false,
321        }
322    }
323    #[cfg(not(windows))]
324    {
325        false
326    }
327}
328
329#[derive(Clone)]
330struct DaemonProvenanceFacts {
331    build: DaemonBuildProvenance,
332    pid: Option<u32>,
333    started_at_ms: Option<u64>,
334    start_clock: Option<crate::clock::StartClock>,
335    executable_path: Option<PathBuf>,
336    executable_identity: Option<SpawnedFileIdentity>,
337    process_start_time: Option<u64>,
338    probe: ExecutableIdentityProbe,
339}
340
341impl Default for DaemonProvenanceFacts {
342    fn default() -> Self {
343        Self {
344            build: DaemonBuildProvenance {
345                build_git_sha: None,
346                build_lock_digest: None,
347            },
348            pid: None,
349            started_at_ms: None,
350            start_clock: None,
351            executable_path: None,
352            executable_identity: None,
353            process_start_time: None,
354            probe: ExecutableIdentityProbe::default(),
355        }
356    }
357}
358
359#[derive(Debug, Clone)]
360struct SupervisorRescanContext {
361    supervisor: Supervisor,
362    config_path: PathBuf,
363    configured_port: Option<u16>,
364    storage_config: Option<crate::daemon_config::StorageConfig>,
365    admission_facts_carrier_module_id: Option<String>,
366    admission_facts_targets: Option<Vec<String>>,
367    scope_authority_owners: Vec<String>,
368    federated_scope_owner: String,
369    privileged_operator_prompt: PrivilegedOperatorPrompt,
370    /// Counts executed rescans that set out to change the supervised modules'
371    /// staged or applied configuration, counted before the first change so a
372    /// rescan that fails partway still counts. With the daemon incarnation it
373    /// names the state a `supervisor.rescan_checked` preview was computed
374    /// against.
375    generation: Arc<std::sync::atomic::AtomicU64>,
376    rescan_lock: Arc<tokio::sync::Mutex<()>>,
377    module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
378}
379
380/// Refusal labels passed to `observe_route_open_refusal` that mean the target
381/// module is not serving right now, and so open or extend an outage in the
382/// route outage tracker. Every one of them is only reachable after the target
383/// was found in the registry, which is what keeps an arbitrary client-chosen
384/// id from ever creating tracker state.
385///
386/// Deliberately absent: `not_registered` and `removed` (the id may be
387/// anything a client sent, and a removed module is gone on purpose),
388/// `protocol_none` (such a module never serves routes, so nothing is out),
389/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
390/// capability and admission-facts refusals (they refuse the caller, not a
391/// module outage), and `relay_reservation_failed` (its code ranges over
392/// capacity limits as well as a vanished connection). Capacity, breaker,
393/// relay-timeout and module-rejection refusals do not pass through that
394/// function at all; the breaker logs its own transitions.
395///
396/// The two not-serving refusals that bypass that function record themselves
397/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
398/// `required_capability_unprovided` is not tracked: the module itself is up,
399/// and the outage belongs to the missing provider.
400const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
401    "reloading",
402    "supervisor_not_live",
403    "registration_not_active",
404    "no_forwarding_connection",
405    "relay_send_failed",
406];
407
408/// Observe test request cancellation relative to the connection's cleanup.
409#[cfg(test)]
410struct ActivityRequestPause {
411    connection: ConnectionId,
412    started: tokio::sync::Notify,
413    cancelled: tokio::sync::Notify,
414    cleanup_started: std::sync::atomic::AtomicBool,
415    cancelled_after_cleanup: std::sync::atomic::AtomicBool,
416}
417
418#[cfg(test)]
419struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
420
421#[cfg(test)]
422impl Drop for ActivityRequestCancellation {
423    fn drop(&mut self) {
424        self.0.cancelled_after_cleanup.store(
425            self.0
426                .cleanup_started
427                .load(std::sync::atomic::Ordering::Acquire),
428            std::sync::atomic::Ordering::Release,
429        );
430        self.0.cancelled.notify_one();
431    }
432}
433
434/// A test hold: signal arrival, then wait for release on the holding thread.
435#[cfg(test)]
436type TestPause = (
437    tokio::sync::oneshot::Sender<()>,
438    std::sync::mpsc::Receiver<()>,
439);
440
441/// A test hook run once at a fixed point in a handler.
442#[cfg(test)]
443type TestHook = Box<dyn FnOnce() + Send>;
444
445/// A test hold for async code: signal arrival, then await release.
446#[cfg(test)]
447type AsyncTestPause = (
448    tokio::sync::oneshot::Sender<()>,
449    tokio::sync::oneshot::Receiver<()>,
450);
451
452/// Real channel-0 control handler for subc itself.
453#[derive(Clone)]
454pub struct ControlHandler {
455    #[cfg(test)]
456    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
457    /// Holds connection cleanup at a numbered point: 0 is just after the agent
458    /// declaration queue closes, 1 just after the registration channel is
459    /// forgotten.
460    #[cfg(test)]
461    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
462    /// Runs once in `route.open`'s launch-nonce attestation, right after the
463    /// nonce is resolved, to interleave a nonce withdrawal there.
464    #[cfg(test)]
465    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
466    /// Holds a registration channel's HELLO after its reader resolved the
467    /// channel and before the blocking HELLO handler starts.
468    #[cfg(test)]
469    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
470    /// Holds an agent command declaration at a numbered point in its handler.
471    #[cfg(test)]
472    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
473    claims: Arc<claims::Claims>,
474    registry: Arc<Registry>,
475    control_usage: Arc<Mutex<usage::ControlUsage>>,
476    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
477    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
478    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
479    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
480    config_review_admission_is_default: bool,
481    activity: Option<crate::activity::ActivityLedger>,
482    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
483    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
484    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
485    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
486    forwarding: Arc<ForwardingTable>,
487    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
488    supervisor: SupervisorHandle,
489    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
490    agent_declarations: agent_commands::Queues,
491    list_admission: Arc<tokio::sync::Semaphore>,
492    subc_capabilities: Arc<[String]>,
493    /// Daemon-wide route.bind relay budget. Used as the fallback when the
494    /// target module has no per-module override in
495    /// `route_bind_relay_timeouts`.
496    route_bind_relay_timeout: Duration,
497    /// Per-module route.bind relay budget overrides, keyed by module id. When
498    /// `handle_route_open` resolves the deadline for a target module, a
499    /// per-module entry wins over the daemon-wide value above.
500    route_bind_relay_timeouts: BTreeMap<String, Duration>,
501    /// Per-target-module bind-relay breaker state. Shared with the forwarding
502    /// table, which is where a new module connection resets it.
503    route_bind_breakers: RouteBindBreakers,
504    /// Live relay admissions keyed by target module. Shared through the
505    /// forwarding table so cloned or separately built handlers enforce one cap.
506    route_bind_concurrency: RouteBindConcurrency,
507    /// Start and end of each module's not-serving period as seen by
508    /// `route.open`, so an outage gets one line at each edge instead of only
509    /// the per-refusal INFO lines. Taken from the forwarding table, so every
510    /// handler built over one table shares it.
511    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
512    route_refusal_log: route_open_refusal_log::RefusalLog,
513    /// Consecutive relay timeouts that open a module's breaker.
514    route_bind_breaker_threshold: u32,
515    /// How long a breaker stays open before one probe is admitted.
516    route_bind_breaker_cooldown: Duration,
517    health_probe_timeout: Duration,
518    /// Central storage policy. When set, each registering module receives its
519    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
520    storage_config: Option<crate::daemon_config::StorageConfig>,
521    /// The machine id established at boot, served on every HELLO_ACK and on
522    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
523    /// changes the file, never this value. `None` serves no id.
524    machine_id: Option<crate::machine_id::MachineId>,
525    admission_facts_carrier_module_id: Option<String>,
526    admission_facts_targets: Option<Vec<String>>,
527    /// Scope records with their sync authorities and tombstones; see
528    /// `crate::scopes`. Shared by clones of this handler, so every connection
529    /// reads and writes one table.
530    scopes: Arc<RwLock<ScopeTable>>,
531    /// Wakes the expiry loop when an accepted scope change may have added a
532    /// deadline, so the loop can wait without ticking while no live scope has
533    /// one. A permit is stored when nothing waits, so no wake is lost.
534    scope_deadline_added: Arc<tokio::sync::Notify>,
535    /// The configured `scope_authority_owners`, kept so a rescan can report a
536    /// changed value as needing a daemon restart; rescan never applies it.
537    scope_authority_owners: Vec<String>,
538    federated_scope_owner: String,
539    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
540    privileged_operator_prompt: PrivilegedOperatorPrompt,
541    /// The local and peer address of each accepted TCP client connection, read
542    /// from the daemon's own socket, so a privileged request can name its caller.
543    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
544    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
545    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
546    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
547    config_desktop_stamps:
548        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
549    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
550    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
551    pub(crate) operator_apps:
552        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
553    /// One launch entry per app, behind a leaf lock: no other lock is taken
554    /// while it is held. Entries are memory-only, so a daemon or
555    /// installed-service restart drops them and a relaunched daemon never
556    /// mistakes an older process for its own launch.
557    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
558    /// Serializes `app.open` launches: the liveness check in the decision and
559    /// the later publish must not interleave across concurrent calls, or two
560    /// calls could both launch and the second publish would orphan the first
561    /// process. Refusals and `already_running` answers share the same lock;
562    /// `app.open` is rare, so the cost is negligible.
563    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
564    // Portable wire samples exercise dispatch without starting an OS process.
565    #[cfg(test)]
566    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
567    #[cfg(test)]
568    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
569    #[cfg(test)]
570    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
571    #[cfg(test)]
572    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
573    #[cfg(test)]
574    recovery_exit_test_completed: Option<fn(u64)>,
575    #[cfg(test)]
576    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
577    #[cfg(test)]
578    recovery_exit_test_quiet_retry: bool,
579    #[cfg(test)]
580    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
581    #[cfg(test)]
582    config_delivery_test_wakes:
583        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
584    #[cfg(all(test, unix))]
585    config_delivery_test_idle:
586        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
587    /// Test-only Windows signature and flash hooks. Production builds carry
588    /// neither: with the publisher unset, the production table never reaches
589    /// verification, and the default attention hook only logs.
590    #[allow(dead_code)]
591    #[cfg(windows)]
592    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
593    #[allow(dead_code)]
594    #[cfg(windows)]
595    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
596    /// Test-only tracking fault hook: makes opening the tracking handle on
597    /// the launched pid fail, so a test can prove an untrackable launch is
598    /// stopped rather than left running.
599    #[allow(dead_code)]
600    #[cfg(windows)]
601    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
602    /// Test-only count of Windows spawn attempts, so a test can prove a
603    /// refused launch started no process. Unit tests only.
604    #[cfg(all(test, windows))]
605    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
606    #[cfg(test)]
607    caller_lookup: Option<TestCallerLookup>,
608    /// The launch nonce each module connection presented at HELLO, which is how
609    /// a `scope.sync` is matched to the owner's current launch.
610    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
611    rescan: Option<SupervisorRescanContext>,
612    connected_clients: ConnectedClients,
613    counters: DaemonCounters,
614    /// Why this daemon serves no local endpoint, when binding one failed. `None`
615    /// when the endpoint is served, and also on a handler that was never told.
616    local_endpoint_unavailable: Option<String>,
617    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
618    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
619    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
620    /// their usual severity (see [`log_requirement_events`]). A handler built
621    /// without one has a flag that is never set.
622    daemon_shutdown: DaemonShutdownFlag,
623    daemon_provenance: DaemonProvenanceFacts,
624    #[cfg(test)]
625    control_dispatch_delay: Option<Duration>,
626    #[cfg(test)]
627    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
628    /// Holds `route.open` after the route.bind is queued to the module and
629    /// before it is marked enqueued, so a test can make the module's reply (or
630    /// a client teardown) land exactly inside that window.
631    #[cfg(test)]
632    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
633    /// Holds a HELLO after its registry entry is reserved and before its
634    /// forwarding endpoint is installed, so a test can read the catalog and
635    /// open routes while the module is registered but not yet routable. A
636    /// blocking barrier because the HELLO handler is synchronous; the test
637    /// runs the HELLO on its own thread.
638    #[cfg(test)]
639    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
640    #[cfg(test)]
641    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
642    #[cfg(test)]
643    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
644    #[cfg(test)]
645    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
646    #[cfg(test)]
647    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
648}
649
650impl fmt::Debug for ControlHandler {
651    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652        f.debug_struct("ControlHandler")
653            .field("registry", &self.registry)
654            .field("forwarding", &self.forwarding)
655            .field("process_liveness", &self.process_liveness.is_some())
656            .field("supervisor", &self.supervisor)
657            .field("subc_capabilities", &self.subc_capabilities)
658            .finish()
659    }
660}
661
662struct RouteOpenRequest {
663    target: RouteTarget,
664    identity: BindIdentity,
665    consumer_identity: Option<ConsumerIdentity>,
666    consumer_capabilities: Option<Vec<String>>,
667    role_versions: Option<BTreeMap<String, String>>,
668    busy_refusals: Option<bool>,
669    admission_facts: Option<serde_json::Value>,
670    scope: Option<ScopeSelector>,
671    accepts_close_reasons: Option<Vec<String>>,
672}
673
674#[derive(Clone, Copy)]
675enum RouteOpenPhase {
676    Admission,
677    ProjectRoot,
678    EgressReservation,
679    BindSend,
680    BindAckWait,
681}
682
683/// Store elapsed time for each route-open phase, including attempts that end
684/// in an early refusal or backend error. Admission also includes rechecks and
685/// commit bookkeeping performed between the other timed phases.
686struct RouteOpenTimings {
687    module_id: String,
688    principal: String,
689    admission: Duration,
690    project_root: Duration,
691    egress_reservation: Duration,
692    bind_send: Duration,
693    bind_ack_wait: Duration,
694    phase: Option<RouteOpenPhase>,
695    phase_started_at: Instant,
696}
697
698impl RouteOpenTimings {
699    fn new() -> Self {
700        Self {
701            module_id: String::new(),
702            // Refusals before attestation must not claim a verified principal.
703            principal: "unresolved".to_string(),
704            admission: Duration::ZERO,
705            project_root: Duration::ZERO,
706            egress_reservation: Duration::ZERO,
707            bind_send: Duration::ZERO,
708            bind_ack_wait: Duration::ZERO,
709            phase: Some(RouteOpenPhase::Admission),
710            phase_started_at: Instant::now(),
711        }
712    }
713
714    fn finish(&mut self) {
715        let elapsed = self.phase_started_at.elapsed();
716        match self.phase.take() {
717            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
718            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
719            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
720            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
721            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
722            None => {}
723        }
724    }
725
726    fn enter(&mut self, phase: RouteOpenPhase) {
727        self.finish();
728        self.phase = Some(phase);
729        self.phase_started_at = Instant::now();
730    }
731}
732
733struct RouteBindReservationGuard {
734    forwarding: Arc<ForwardingTable>,
735    endpoint: ModuleEndpointId,
736    relay_corr: u64,
737    armed: bool,
738}
739
740struct ModuleControlRpcGuard {
741    forwarding: Arc<ForwardingTable>,
742    endpoint: ModuleEndpointId,
743    corr: u64,
744    armed: bool,
745}
746
747impl ModuleControlRpcGuard {
748    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
749        Self {
750            forwarding,
751            endpoint,
752            corr,
753            armed: true,
754        }
755    }
756
757    fn disarm(&mut self) {
758        self.armed = false;
759    }
760}
761
762impl Drop for ModuleControlRpcGuard {
763    fn drop(&mut self) {
764        if self.armed {
765            let _ = self
766                .forwarding
767                .cancel_module_control_rpc(self.endpoint, self.corr);
768        }
769    }
770}
771
772impl RouteBindReservationGuard {
773    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
774        Self {
775            forwarding,
776            endpoint,
777            relay_corr,
778            armed: true,
779        }
780    }
781
782    fn release_and_disarm(&mut self) {
783        if !self.armed {
784            return;
785        }
786        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
787            self.endpoint,
788            self.relay_corr,
789            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
790        ) {
791            send_goodbye_target_best_effort(
792                &self.forwarding.counters(),
793                &target,
794                "canceled route.bind",
795            );
796        }
797        self.armed = false;
798    }
799
800    fn disarm(&mut self) {
801        self.armed = false;
802    }
803}
804
805impl Drop for RouteBindReservationGuard {
806    fn drop(&mut self) {
807        self.release_and_disarm();
808    }
809}
810
811/// Per-target-module circuit breaker around the `route.bind` relay.
812///
813/// The connection reader is serial per connection, so a module whose `on_bind`
814/// sits on the ack blocks every LATER frame on the connections that call it,
815/// including calls to unrelated modules. This does not make any module's bind
816/// fast; it stops the daemon paying the full budget again and again for a
817/// condition it has already observed.
818///
819/// State is keyed by TARGET MODULE and shared by every connection: a wedged
820/// module wedges everyone, so what one connection learned should protect the
821/// rest.
822///
823/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
824/// relay to that module has actually timed out, and is removed again when a
825/// relay is accepted or the module reconnects, so it cannot grow with traffic
826/// or with modules that behave.
827///
828/// # Why a `std` mutex here is not the head-of-line defect again
829///
830/// Acquisition never awaits. The critical section is a hash lookup plus a few
831/// integer updates, with no I/O and no `.await` inside it, so a reader task
832/// cannot be descheduled behind it the way it can behind
833/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
834/// primitive, held for the same kind of work, as the refusal counter this very
835/// path already increments.
836///
837/// It is also NOT on the data-plane splice path: only `route.open` and module
838/// registration touch it, so bound-route frames gain no state check and no
839/// contention.
840#[derive(Debug, Clone, Default)]
841pub(crate) struct RouteBindBreakers {
842    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
843}
844
845#[derive(Debug, Clone, Default)]
846pub(crate) struct RouteBindConcurrency {
847    modules: Arc<Mutex<HashMap<String, usize>>>,
848}
849
850struct RouteBindConcurrencyGuard {
851    concurrency: RouteBindConcurrency,
852    module_id: String,
853}
854
855impl RouteBindConcurrency {
856    /// Admit without waiting. Waiting here would move the bind stall from the
857    /// module reply to a semaphore and restore reader head-of-line blocking.
858    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
859        let mut modules = self
860            .modules
861            .lock()
862            .expect("route.bind concurrency mutex poisoned");
863        let in_flight = modules.entry(module_id.to_string()).or_default();
864        if *in_flight >= limit {
865            return Err(*in_flight);
866        }
867        *in_flight += 1;
868        Ok(RouteBindConcurrencyGuard {
869            concurrency: self.clone(),
870            module_id: module_id.to_string(),
871        })
872    }
873}
874
875impl Drop for RouteBindConcurrencyGuard {
876    fn drop(&mut self) {
877        let mut modules = self
878            .concurrency
879            .modules
880            .lock()
881            .expect("route.bind concurrency mutex poisoned");
882        let remove = {
883            let in_flight = modules
884                .get_mut(&self.module_id)
885                .expect("admitted route.bind has a concurrency entry");
886            *in_flight -= 1;
887            *in_flight == 0
888        };
889        if remove {
890            modules.remove(&self.module_id);
891        }
892    }
893}
894
895#[derive(Debug, Default)]
896struct ModuleBreakerState {
897    /// Relay timeouts observed with no accepted relay in between.
898    consecutive_timeouts: u32,
899    /// `Some` while the breaker is open: the instant the cooldown expires and
900    /// the next arrival may probe. `None` means closed.
901    cooldown_until: Option<Instant>,
902    /// A half-open probe has been admitted and has not settled yet. This is
903    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
904    /// that read the cooldown, so concurrent opens arriving at the moment the
905    /// cooldown expires cannot all decide that they are the probe.
906    probe_in_flight: Option<Arc<()>>,
907}
908
909/// What the breaker decided for one `route.open`, before any relay work.
910enum RouteBindAdmission<'a> {
911    Admitted {
912        guard: RouteBindBreakerGuard<'a>,
913        /// This open is the single half-open probe, so the transition is worth
914        /// one log line.
915        probe: bool,
916    },
917    Refused {
918        consecutive_timeouts: u32,
919        /// What is left of the cooldown. Zero when the refusal is because the
920        /// one probe is already in flight rather than because the cooldown has
921        /// not elapsed.
922        retry_in: Duration,
923        probe_in_flight: bool,
924    },
925}
926
927/// An outstanding admission, which must be told how its relay settled.
928///
929/// `Drop` settles it as inconclusive, so an early return between admission and
930/// the relay -- or the whole handler being cancelled when the client
931/// disconnects -- releases a half-open probe slot instead of leaving the
932/// breaker wedged half-open with no further probes.
933struct RouteBindBreakerGuard<'a> {
934    breakers: RouteBindBreakers,
935    module_id: &'a str,
936    probe_token: Option<Arc<()>>,
937    settled: bool,
938}
939
940impl RouteBindBreakerGuard<'_> {
941    /// The module answered within the budget and took the bind. THE ONLY
942    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
943    /// breaker, which is a transition worth logging.
944    fn record_accepted(&mut self) -> bool {
945        self.settled = true;
946        self.breakers.record_accepted(self.module_id)
947    }
948
949    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
950    /// COUNTS TOWARD OPENING.
951    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
952        self.settled = true;
953        self.breakers.record_timeout(
954            self.module_id,
955            self.probe_token.as_ref(),
956            threshold,
957            cooldown,
958        )
959    }
960
961    /// Everything else: the module REJECTED the bind, its connection went away
962    /// mid-relay, or the waiter was cancelled.
963    ///
964    /// None of these is evidence that a module is slow, and each already has
965    /// its own refusal with its own code. A module that rejects a bind in
966    /// microseconds is healthy and must never be convicted for it; a module
967    /// that died has said nothing about the module that replaces it. So these
968    /// neither increment nor reset the count -- they only release a probe slot.
969    fn record_inconclusive(&mut self) {
970        self.settled = true;
971        self.breakers
972            .record_inconclusive(self.module_id, self.probe_token.as_ref());
973    }
974}
975
976impl Drop for RouteBindBreakerGuard<'_> {
977    fn drop(&mut self) {
978        if !self.settled {
979            self.breakers
980                .record_inconclusive(self.module_id, self.probe_token.as_ref());
981        }
982    }
983}
984
985/// The breaker moved to open, reported so the caller can log it outside the
986/// lock. Opening is rare and load-bearing; the refusals that follow are
987/// frequent and are counted rather than logged.
988struct BreakerOpened {
989    consecutive_timeouts: u32,
990    /// True when a failed probe re-opened an already-open breaker, which reads
991    /// very differently in a log from a first opening.
992    reopened_after_probe: bool,
993}
994
995impl RouteBindBreakers {
996    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
997        self.modules
998            .lock()
999            .expect("route.bind breaker mutex poisoned")
1000    }
1001
1002    /// Decide whether this `route.open` may attempt its relay. Takes the map
1003    /// lock and nothing else, and never awaits.
1004    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
1005        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
1006            probe: probe_token.is_some(),
1007            guard: RouteBindBreakerGuard {
1008                breakers: self.clone(),
1009                module_id,
1010                probe_token,
1011                settled: false,
1012            },
1013        };
1014
1015        let mut modules = self.lock();
1016        let Some(state) = modules.get_mut(module_id) else {
1017            return admitted(None);
1018        };
1019        let Some(cooldown_until) = state.cooldown_until else {
1020            return admitted(None);
1021        };
1022        if state.probe_in_flight.is_some() {
1023            return RouteBindAdmission::Refused {
1024                consecutive_timeouts: state.consecutive_timeouts,
1025                retry_in: Duration::ZERO,
1026                probe_in_flight: true,
1027            };
1028        }
1029        let now = Instant::now();
1030        if now < cooldown_until {
1031            return RouteBindAdmission::Refused {
1032                consecutive_timeouts: state.consecutive_timeouts,
1033                retry_in: cooldown_until - now,
1034                probe_in_flight: false,
1035            };
1036        }
1037        let token = Arc::new(());
1038        state.probe_in_flight = Some(Arc::clone(&token));
1039        admitted(Some(token))
1040    }
1041
1042    fn record_accepted(&self, module_id: &str) -> bool {
1043        self.lock()
1044            .remove(module_id)
1045            .is_some_and(|state| state.cooldown_until.is_some())
1046    }
1047
1048    fn record_timeout(
1049        &self,
1050        module_id: &str,
1051        probe_token: Option<&Arc<()>>,
1052        threshold: u32,
1053        cooldown: Duration,
1054    ) -> Option<BreakerOpened> {
1055        let mut modules = self.lock();
1056        let state = modules.entry(module_id.to_string()).or_default();
1057        let was_open = state.cooldown_until.is_some();
1058        let was_probe = Self::owns_probe(state, probe_token);
1059        if was_probe {
1060            state.probe_in_flight = None;
1061        }
1062        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
1063        if state.consecutive_timeouts < threshold {
1064            return None;
1065        }
1066        state.cooldown_until = Some(Instant::now() + cooldown);
1067        Some(BreakerOpened {
1068            consecutive_timeouts: state.consecutive_timeouts,
1069            reopened_after_probe: was_open && was_probe,
1070        })
1071    }
1072
1073    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
1074        // A relay can finish after the breaker was reset or after it opened
1075        // again and started a new probe. Only the guard whose token matches the
1076        // active probe may release it, so a late relay never frees a newer probe.
1077        state
1078            .probe_in_flight
1079            .as_ref()
1080            .zip(token)
1081            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
1082    }
1083
1084    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
1085        if let Some(state) = self.lock().get_mut(module_id) {
1086            if Self::owns_probe(state, probe_token) {
1087                state.probe_in_flight = None;
1088            }
1089        }
1090    }
1091
1092    /// Discard what was learned about a module, because the process it was
1093    /// learned about is gone. Returns the discarded count when it was non-zero.
1094    ///
1095    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
1096    /// `module_id` is a configuration identity that outlives any particular
1097    /// child; what the breaker observed was the process behind the module
1098    /// connection of the moment. When a new connection registers under that id
1099    /// the verdict's subject no longer exists, so the verdict is stale by
1100    /// construction rather than merely likely to be wrong. Keeping it would
1101    /// apply a dead process's record to a live one, which is the same defect
1102    /// class this breaker exists to stop the daemon committing.
1103    ///
1104    /// A half-open probe in flight is discarded with the rest: it was a
1105    /// question about the old process.
1106    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
1107        self.lock()
1108            .remove(module_id)
1109            .map(|state| state.consecutive_timeouts)
1110            .filter(|discarded| *discarded > 0)
1111    }
1112
1113    /// Open breakers, for the `server.describe` counters object. `None` when
1114    /// none is open, so the key stays absent rather than present-and-empty.
1115    ///
1116    /// This is the operator's answer to "is this module refusing instantly or
1117    /// is it fine?", which look identical from a client that retries and then
1118    /// succeeds.
1119    fn open_snapshot(&self) -> Option<serde_json::Value> {
1120        let now = Instant::now();
1121        let modules = self.lock();
1122        let open = modules
1123            .iter()
1124            .filter_map(|(module_id, state)| {
1125                let cooldown_until = state.cooldown_until?;
1126                Some((
1127                    module_id.clone(),
1128                    serde_json::json!({
1129                        "consecutive_timeouts": state.consecutive_timeouts,
1130                        "cooldown_remaining_ms":
1131                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
1132                        "probe_in_flight": state.probe_in_flight.is_some(),
1133                    }),
1134                ))
1135            })
1136            .collect::<serde_json::Map<String, serde_json::Value>>();
1137        (!open.is_empty()).then_some(serde_json::Value::Object(open))
1138    }
1139}
1140
1141impl ControlHandler {
1142    pub(crate) fn install_registration_service(
1143        &self,
1144        router: std::sync::Weak<crate::Router>,
1145        auth: crate::server::ServerAuth,
1146    ) {
1147        self.supervisor.install_registration_service(router, auth);
1148    }
1149    pub fn new(registry: Arc<Registry>) -> Self {
1150        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
1151    }
1152
1153    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
1154        let counters = forwarding.counters();
1155        // Taken from the forwarding table rather than created here, so that the
1156        // breaker a `route.open` consults is the same one a module's
1157        // registration resets, however many handlers are built over one table.
1158        let route_bind_breakers = forwarding.route_bind_breakers();
1159        let route_bind_concurrency = forwarding.route_bind_concurrency();
1160        let route_outages = forwarding.route_outages();
1161        Self {
1162            registry,
1163            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
1164            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
1165            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1166            #[cfg(test)]
1167            activity_request_pause: Arc::new(Mutex::new(None)),
1168            #[cfg(test)]
1169            cleanup_pause: Arc::new(Mutex::new(None)),
1170            #[cfg(test)]
1171            after_nonce_attestation: Arc::new(Mutex::new(None)),
1172            #[cfg(test)]
1173            hello_ingress_pause: Arc::new(Mutex::new(None)),
1174            #[cfg(test)]
1175            agent_commands_pause: Arc::new(Mutex::new(None)),
1176            claims: Arc::new(claims::Claims::default()),
1177            config_runtime: None,
1178            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
1179            config_review_admission_is_default: true,
1180            activity: None,
1181            activity_streams: Arc::new(Mutex::new(HashMap::new())),
1182            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
1183            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
1184            scope_streams: Arc::new(Mutex::new(HashMap::new())),
1185            forwarding,
1186            process_liveness: None,
1187            supervisor: SupervisorHandle::new(),
1188            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
1189                env!("CARGO_PKG_VERSION").to_owned(),
1190            )),
1191            agent_declarations: agent_commands::Queues::default(),
1192            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
1193            subc_capabilities: Arc::from([
1194                CAP_MANIFEST_REGISTRATION.to_string(),
1195                CAP_CHANNEL_LIFECYCLE.to_string(),
1196                CAP_PING_PONG.to_string(),
1197                CAP_SESSION_ATTACH.to_string(),
1198                CAP_ADMISSION_FACTS_RELAY.to_string(),
1199                CAP_SCOPES_V1.to_string(),
1200                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
1201                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
1202                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1203                PEER_BUILD_CAPABILITY.to_string(),
1204                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1205                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1206                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1207                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1208                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1209                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1210                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1211                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1212                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1213                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1214                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1215                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1216            ]),
1217            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1218            route_bind_relay_timeouts: BTreeMap::new(),
1219            route_bind_breakers,
1220            route_bind_concurrency,
1221            route_outages,
1222            route_refusal_log: Default::default(),
1223            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1224            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1225            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1226            storage_config: None,
1227            machine_id: None,
1228            admission_facts_carrier_module_id: None,
1229            admission_facts_targets: None,
1230            scopes: Arc::new(RwLock::new(ScopeTable::new(
1231                crate::daemon_config::default_scope_authority_owners(),
1232            ))),
1233            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1234            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1235            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1236            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1237            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1238            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1239            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1240            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1241            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1242            local_connections: Arc::new(Mutex::new(HashSet::new())),
1243            operator_app_policy: Default::default(),
1244            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1245            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1246            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1247            #[cfg(test)]
1248            app_open_test_platform: None,
1249            #[cfg(test)]
1250            app_open_test_launch: None,
1251            #[cfg(test)]
1252            config_review_test_reply: None,
1253            #[cfg(test)]
1254            recovery_exit_test_after_step: None,
1255            #[cfg(test)]
1256            recovery_exit_test_completed: None,
1257            #[cfg(test)]
1258            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1259            #[cfg(test)]
1260            recovery_exit_test_quiet_retry: false,
1261            #[cfg(test)]
1262            recovery_exit_test_retry_pause: None,
1263            #[cfg(test)]
1264            config_delivery_test_wakes: None,
1265            #[cfg(all(test, unix))]
1266            config_delivery_test_idle: None,
1267            #[cfg(windows)]
1268            windows_verify: None,
1269            #[cfg(windows)]
1270            windows_flash: None,
1271            #[cfg(windows)]
1272            windows_track: None,
1273            #[cfg(all(test, windows))]
1274            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1275            #[cfg(test)]
1276            caller_lookup: None,
1277            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1278            rescan: None,
1279            connected_clients: ConnectedClients::new(),
1280            local_endpoint_unavailable: None,
1281            counters,
1282            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1283            daemon_shutdown: DaemonShutdownFlag::default(),
1284            daemon_provenance: DaemonProvenanceFacts::default(),
1285            #[cfg(test)]
1286            control_dispatch_delay: None,
1287            #[cfg(test)]
1288            provenance_probe_override: None,
1289            #[cfg(test)]
1290            route_bind_relay_sent_hold: None,
1291            #[cfg(test)]
1292            hello_registry_to_forwarding_hold: None,
1293            #[cfg(test)]
1294            hello_ack_to_publication_hold: None,
1295            #[cfg(test)]
1296            hello_before_publication_hold: None,
1297            #[cfg(test)]
1298            hello_after_launch_check_hold: None,
1299            #[cfg(test)]
1300            hello_inside_publication_hold: None,
1301        }
1302    }
1303
1304    /// Set the central storage policy: registering modules then receive their
1305    /// resolved storage descriptor in HELLO_ACK.
1306    pub fn with_storage_config(
1307        mut self,
1308        storage_config: Option<crate::daemon_config::StorageConfig>,
1309    ) -> Self {
1310        self.storage_config = storage_config;
1311        self
1312    }
1313
1314    /// Open the ledger on its own writer thread; an unavailable sink does not
1315    /// prevent the daemon from serving routing or supervisor requests.
1316    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1317        self.activity = Some(crate::activity::ActivityLedger::open(
1318            run_dir.join("activity.jsonl"),
1319            incarnation,
1320        ));
1321        self.supervisor.set_activity(self.activity.clone());
1322        self
1323    }
1324
1325    /// Set the machine id served to every registering module (HELLO_ACK) and on
1326    /// `server.describe`.
1327    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1328        self.machine_id = machine_id;
1329        self
1330    }
1331
1332    /// Configure the exact reserved module and target ids permitted to relay
1333    /// opaque admission facts. Config-file loading validates this authority;
1334    /// this builder keeps the same policy available to embedded test daemons.
1335    pub fn with_admission_facts_config(
1336        mut self,
1337        carrier_module_id: Option<String>,
1338        targets: Option<Vec<String>>,
1339    ) -> Self {
1340        self.admission_facts_carrier_module_id = carrier_module_id;
1341        self.admission_facts_targets = targets;
1342        self
1343    }
1344
1345    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1346    /// Replaces the scope table with an empty one under the new list, so call it
1347    /// while building the handler, before any module can sync.
1348    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1349        self.scopes = Arc::new(RwLock::new(
1350            ScopeTable::new(owners.iter().cloned())
1351                .with_federated_owner(self.federated_scope_owner.clone()),
1352        ));
1353        self.scope_authority_owners = owners;
1354        self
1355    }
1356
1357    /// Set the exclusive federated owner while building the handler, before syncs.
1358    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1359        self.scopes = Arc::new(RwLock::new(
1360            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1361                .with_federated_owner(owner.clone()),
1362        ));
1363        self.federated_scope_owner = owner;
1364        self
1365    }
1366
1367    /// Set the startup policy before installing the rescan context or serving requests.
1368    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1369        self.privileged_operator_prompt = mode;
1370        self
1371    }
1372
1373    /// Override the route.bind relay timeout. Used by tests that assert the
1374    /// timeout path so they don't block on the production-safe default.
1375    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1376        self.route_bind_relay_timeout = timeout;
1377        self
1378    }
1379
1380    /// Install per-module route.bind relay budget overrides. A module id
1381    /// listed here wins over the daemon-wide default set via
1382    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1383    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1384    /// the same `Duration` the bind path will use.
1385    pub fn with_route_bind_relay_timeouts(
1386        mut self,
1387        timeouts: impl IntoIterator<Item = (String, Duration)>,
1388    ) -> Self {
1389        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1390        self
1391    }
1392
1393    /// Resolve the route.bind relay budget for a specific target module id.
1394    /// Per-module overrides win; the daemon-wide value (set via
1395    /// `with_route_bind_relay_timeout` or the built-in default) is the
1396    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1397    /// the same resolution `handle_route_open` will use.
1398    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1399        self.route_bind_relay_timeouts
1400            .get(module_id)
1401            .copied()
1402            .unwrap_or(self.route_bind_relay_timeout)
1403    }
1404
1405    /// Override the per-module bind-relay breaker policy.
1406    ///
1407    /// Used by tests, which cannot spend three production budgets opening a
1408    /// breaker or twenty seconds waiting for its cooldown. The production
1409    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1410    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1411    /// reasoning for the numbers.
1412    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1413        self.route_bind_breaker_threshold = threshold.max(1);
1414        self.route_bind_breaker_cooldown = cooldown;
1415        self
1416    }
1417
1418    #[cfg(test)]
1419    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1420        self.health_probe_timeout = timeout;
1421        self
1422    }
1423
1424    #[cfg(test)]
1425    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1426        self.control_dispatch_delay = Some(delay);
1427        self
1428    }
1429
1430    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1431    /// announce it is parked, once to be released. Build the barrier for two
1432    /// parties, the test being the other one.
1433    #[cfg(test)]
1434    pub(crate) fn with_route_bind_relay_sent_hold(
1435        mut self,
1436        hold: Arc<tokio::sync::Barrier>,
1437    ) -> Self {
1438        self.route_bind_relay_sent_hold = Some(hold);
1439        self
1440    }
1441
1442    /// A HELLO waits on `hold` twice between reserving its registry entry and
1443    /// installing its forwarding endpoint: once to announce it is parked, once
1444    /// to be released. Build the barrier for two parties, the test being the
1445    /// other one, and run the HELLO on a thread of its own.
1446    #[cfg(test)]
1447    pub(crate) fn with_hello_registry_to_forwarding_hold(
1448        mut self,
1449        hold: Arc<std::sync::Barrier>,
1450    ) -> Self {
1451        self.hello_registry_to_forwarding_hold = Some(hold);
1452        self
1453    }
1454
1455    #[cfg(test)]
1456    fn hold_between_registry_and_forwarding(&self) {
1457        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1458            hold.wait();
1459            hold.wait();
1460        }
1461    }
1462
1463    /// Park after the ACK is queued and forwarding is installed, until a test
1464    /// has read the ACK and issued a registry lookup from another connection.
1465    #[cfg(test)]
1466    fn hold_between_ack_and_publication(&self) {
1467        if let Some(hold) = &self.hello_ack_to_publication_hold {
1468            hold.wait();
1469            hold.wait();
1470        }
1471    }
1472
1473    #[cfg(all(test, unix))]
1474    pub(crate) fn with_hello_before_publication_hold(
1475        mut self,
1476        hold: Arc<std::sync::Barrier>,
1477    ) -> Self {
1478        self.hello_before_publication_hold = Some(hold);
1479        self
1480    }
1481
1482    #[cfg(all(test, unix))]
1483    pub(crate) fn with_hello_after_launch_check_hold(
1484        mut self,
1485        hold: Arc<std::sync::Barrier>,
1486    ) -> Self {
1487        self.hello_after_launch_check_hold = Some(hold);
1488        self
1489    }
1490
1491    #[cfg(all(test, unix))]
1492    pub(crate) fn with_hello_inside_publication_hold(
1493        mut self,
1494        hold: Arc<std::sync::Barrier>,
1495    ) -> Self {
1496        self.hello_inside_publication_hold = Some(hold);
1497        self
1498    }
1499
1500    pub fn with_process_liveness(
1501        mut self,
1502        process_liveness: Arc<dyn ModuleProcessLiveness>,
1503    ) -> Self {
1504        self.process_liveness = Some(process_liveness);
1505        self
1506    }
1507
1508    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1509        self.supervisor = supervisor;
1510        if let Some(owner) = &self.config_runtime {
1511            self.supervisor.install_binding_retirement(owner);
1512        }
1513        self.supervisor.set_activity(self.activity.clone());
1514        self
1515    }
1516
1517    pub fn with_daemon_provenance(
1518        mut self,
1519        pid: u32,
1520        started_at_ms: u64,
1521        executable_path: Option<PathBuf>,
1522        build_git_sha: Option<String>,
1523        build_lock_digest: Option<String>,
1524    ) -> Self {
1525        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1526        let process_start_time = process_start_time(pid);
1527        self.daemon_provenance = DaemonProvenanceFacts {
1528            build: DaemonBuildProvenance {
1529                build_git_sha,
1530                build_lock_digest,
1531            },
1532            pid: Some(pid),
1533            started_at_ms: Some(started_at_ms),
1534            start_clock: None,
1535            executable_path,
1536            executable_identity,
1537            process_start_time,
1538            probe: ExecutableIdentityProbe::default(),
1539        };
1540        self
1541    }
1542
1543    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1544        self.daemon_provenance.start_clock = Some(clock);
1545        self
1546    }
1547
1548    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1549    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1550        self.scopes
1551            .write()
1552            .unwrap_or_else(|poisoned| poisoned.into_inner())
1553            .set_wall_clock(Arc::new(clock));
1554        self
1555    }
1556
1557    #[cfg(test)]
1558    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1559        self.provenance_probe_override = Some(result);
1560        self
1561    }
1562
1563    /// Install the configured module set and its reserved capability bindings.
1564    /// Bindings are configuration-scoped and may point at a provider that has not
1565    /// been installed yet, so this does not require the bound module to exist.
1566    pub fn with_capability_config(
1567        self,
1568        modules: impl IntoIterator<Item = (String, bool)>,
1569        reserved_capabilities: BTreeMap<String, String>,
1570    ) -> Self {
1571        self.capability_evaluator
1572            .configure(modules, reserved_capabilities);
1573        self
1574    }
1575
1576    /// Share the supervisor's daemon-shutdown flag with this handler, so
1577    /// requirement changes after the daemon has begun its announced shutdown
1578    /// are not reported as faults.
1579    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1580        self.daemon_shutdown = flag;
1581        self
1582    }
1583
1584    pub fn with_supervisor_rescan(
1585        mut self,
1586        supervisor: Supervisor,
1587        config_path: impl Into<PathBuf>,
1588        configured_port: Option<u16>,
1589    ) -> Self {
1590        self.rescan = Some(SupervisorRescanContext {
1591            supervisor,
1592            config_path: config_path.into(),
1593            configured_port,
1594            storage_config: self.storage_config.clone(),
1595            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1596            admission_facts_targets: self.admission_facts_targets.clone(),
1597            scope_authority_owners: self.scope_authority_owners.clone(),
1598            federated_scope_owner: self.federated_scope_owner.clone(),
1599            privileged_operator_prompt: self.privileged_operator_prompt,
1600            generation: Arc::default(),
1601            rescan_lock: Arc::default(),
1602            module_entries: Arc::default(),
1603        });
1604        self
1605    }
1606
1607    pub(crate) fn with_supervisor_rescan_entries(
1608        self,
1609        modules: &[crate::daemon_config::ConfiguredModule],
1610    ) -> Self {
1611        if let Some(context) = &self.rescan {
1612            let mut entries = context
1613                .module_entries
1614                .lock()
1615                .unwrap_or_else(|e| e.into_inner());
1616            entries.seed(modules);
1617        }
1618        self
1619    }
1620
1621    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1622        self.connected_clients = connected_clients;
1623        self
1624    }
1625
1626    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1627    /// an operator can see a bind failure without reading the daemon log.
1628    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1629        self.local_endpoint_unavailable = reason;
1630        self
1631    }
1632
1633    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1634        Arc::clone(&self.forwarding)
1635    }
1636
1637    pub(crate) fn counters(&self) -> DaemonCounters {
1638        self.counters.clone()
1639    }
1640
1641    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1642    /// requirement event without depending on an operator polling a status command.
1643    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1644        let handler = Arc::downgrade(&self);
1645        let evaluator = self.capability_evaluator.clone();
1646        tokio::spawn(async move {
1647            loop {
1648                evaluator.wait_for_change_or_deadline().await;
1649                let Some(handler) = handler.upgrade() else {
1650                    break;
1651                };
1652                handler.refresh_capability_requirements();
1653            }
1654        });
1655    }
1656
1657    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1658    /// deadline passed during sleep is enforced on the first tick after wake.
1659    /// While no live scope carries a deadline the loop waits for an accepted
1660    /// scope change instead of ticking, so a daemon without deadlines never
1661    /// wakes for expiry.
1662    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1663        let context = scope_expiry::ScopeExpiryContext::new(&self);
1664        let deadline_added = self.scope_deadline_added.clone();
1665        tokio::spawn(async move {
1666            loop {
1667                if !context.has_deadlines() {
1668                    deadline_added.notified().await;
1669                    continue;
1670                }
1671                tokio::time::sleep(Duration::from_secs(1)).await;
1672                if let Err(error) = context.sweep() {
1673                    warn!(%error, "scope expiry sweep failed");
1674                }
1675            }
1676        });
1677    }
1678
1679    #[cfg(test)]
1680    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1681        scope_expiry::ScopeExpiryContext::new(self).sweep()
1682    }
1683
1684    fn publish_scope_changes(
1685        &self,
1686        changes: &[crate::scopes::ScopeTagChange],
1687        expired: &[crate::scopes::ScopeExpired],
1688    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1689        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1690    }
1691
1692    fn runtime_capability_snapshot(
1693        &self,
1694    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1695        let runtime = self
1696            .supervisor
1697            .list()
1698            .into_iter()
1699            .map(|module| {
1700                let status = module.status().map_err(|err| {
1701                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1702                })?;
1703                Ok(RuntimeModule {
1704                    module_id: status.module_id,
1705                    state: status.state,
1706                    enabled: status.enabled,
1707                })
1708            })
1709            .collect::<Result<Vec<_>, RouterError>>()?;
1710        // Include every registration, published or not. The capability
1711        // evaluator counts a module as providing its capabilities as soon as it
1712        // has registered, even before `catalog.list` shows it, so a HELLO in
1713        // progress does not change other modules' required-capability
1714        // verdicts. See `Registry::list_registered_modules`.
1715        let registrations = self.registry.list_registered_modules().map_err(|err| {
1716            RouterError::backend(
1717                0,
1718                0,
1719                format!("failed to list capability registrations: {err}"),
1720            )
1721        })?;
1722        let registrations = registrations
1723            .into_iter()
1724            .map(|registration| RegisteredModule {
1725                module_id: registration.manifest.module_id,
1726                module_version: registration.manifest.module_version,
1727                capabilities: registration.manifest.capabilities,
1728            })
1729            .collect();
1730        Ok((runtime, registrations))
1731    }
1732
1733    /// The capability side effects of a module becoming the active registration
1734    /// for its id: cache its manifest (logging how it differs from the cached
1735    /// one), run the deny census when its declarations call for one, and recompute the
1736    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1737    /// candidate's does not, and the supervisor does it at promotion instead,
1738    /// through [`crate::supervise::SwapPromotionObserver`].
1739    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1740        let cached_registration = RegisteredModule {
1741            module_id: registration.manifest.module_id.clone(),
1742            module_version: registration.manifest.module_version.clone(),
1743            capabilities: registration.manifest.capabilities.clone(),
1744        };
1745        let change = self.capability_evaluator.record_hello(&cached_registration);
1746        log_manifest_change(&cached_registration.module_id, &change);
1747        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1748            self.enforce_capability_denies();
1749        }
1750        self.refresh_capability_requirements();
1751    }
1752
1753    /// Point the shared supervisor handle at this handler for swap promotions.
1754    /// Called wherever a handler is put behind the `Arc` the router serves, so
1755    /// it can be held weakly.
1756    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1757        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1758            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1759        self.supervisor.set_swap_promotion_observer(observer);
1760    }
1761
1762    pub fn refresh_capability_requirements(&self) {
1763        match self.runtime_capability_snapshot() {
1764            Ok((runtime, registrations)) => {
1765                let events = self
1766                    .capability_evaluator
1767                    .evaluate_now(&runtime, &registrations);
1768                if !events.is_empty() {
1769                    self.catalog_readiness_revision
1770                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1771                }
1772                log_requirement_events(events, &self.daemon_shutdown);
1773            }
1774            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1775        }
1776    }
1777
1778    /// Reconcile only live, attested route bindings after a capability deny edge
1779    /// or target claim was added. This is deliberately a control-plane census:
1780    /// the opaque forwarding hot path must not grow a per-frame capability check.
1781    fn enforce_capability_denies(&self) {
1782        let registrations = match self.registry.list_registered_modules() {
1783            Ok(snapshot) => snapshot,
1784            Err(err) => {
1785                warn!(error = %err, "failed to read registrations for capability deny census");
1786                return;
1787            }
1788        };
1789        let manifests = registrations
1790            .into_iter()
1791            .map(|registration| {
1792                (
1793                    registration.manifest.module_id.clone(),
1794                    registration.manifest,
1795                )
1796            })
1797            .collect::<BTreeMap<_, _>>();
1798        let census = match self.forwarding.route_census(None) {
1799            Ok(census) => census,
1800            Err(err) => {
1801                warn!(error = %err, "failed to read route census for capability deny enforcement");
1802                return;
1803            }
1804        };
1805
1806        for (target_module_id, routes) in census {
1807            let Some(target_manifest) = manifests.get(&target_module_id) else {
1808                continue;
1809            };
1810            let mut closed_routes = Vec::new();
1811            let mut goodbyes = Vec::new();
1812            for route in routes {
1813                let Principal::Reserved {
1814                    module_id: opening_module_id,
1815                } = &route.principal
1816                else {
1817                    continue;
1818                };
1819                let Some(opening_manifest) = manifests.get(opening_module_id) else {
1820                    continue;
1821                };
1822                let Some(capability) = denied_capability(
1823                    opening_manifest.capabilities.as_ref(),
1824                    target_manifest.capabilities.as_ref(),
1825                ) else {
1826                    continue;
1827                };
1828
1829                match self.forwarding.release_client_route(
1830                    route.goodbye_target.connection_id,
1831                    route.goodbye_target.channel,
1832                    route.goodbye_target.epoch,
1833                ) {
1834                    Ok(RouteRelease::Removed(module_goodbye)) => {
1835                        warn!(
1836                            opening_module_id,
1837                            target_module_id,
1838                            capability,
1839                            "force-closing route because an attested capability deny edge now matches"
1840                        );
1841                        goodbyes.push(module_goodbye);
1842                        goodbyes.push(route.goodbye_target.clone());
1843                        closed_routes.push(route);
1844                    }
1845                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
1846                    Err(err) => warn!(
1847                        opening_module_id,
1848                        target_module_id,
1849                        capability,
1850                        error = %err,
1851                        "failed to force-close capability-denied route"
1852                    ),
1853                }
1854            }
1855
1856            if closed_routes.is_empty() {
1857                continue;
1858            }
1859            send_route_control_pushes(
1860                &self.forwarding,
1861                closed_routes,
1862                ClientControlPush::RouteClosed {
1863                    module_id: target_module_id,
1864                    channels: Vec::new(),
1865                    reason: RouteCloseReason::CapabilityDenied,
1866                    drained: false,
1867                    abandoned: 0,
1868                    excluded_subscriptions: 0,
1869                    terminal: Some(false),
1870                },
1871            );
1872            // route.closed records the reason; the route GOODBYE ends the
1873            // client's handle and settles any calls still pending on it.
1874            self.emit_route_goodbyes(goodbyes);
1875        }
1876    }
1877
1878    /// Why a registered module is not accepting new route binds, or `None` when
1879    /// it is. This is the module's effective readiness: its declared readiness
1880    /// first, then every `need: required` capability it declares evaluating to
1881    /// `provided`. `route.open` and `catalog.list` both read it here so the
1882    /// catalog never reports a module routable that `route.open` would refuse.
1883    fn not_ready_reason(
1884        &self,
1885        registration: &crate::registry::ModuleRegistration,
1886    ) -> Option<NotReadyReason> {
1887        if !registration.ready {
1888            return Some(NotReadyReason {
1889                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1890                capability: None,
1891            });
1892        }
1893        self.first_unprovided_required_capability(registration)
1894            .map(|capability| NotReadyReason {
1895                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1896                capability: Some(capability),
1897            })
1898    }
1899
1900    /// The lexicographically first capability this registration declares
1901    /// `need: required` whose evaluator verdict is not `provided`.
1902    ///
1903    /// The verdicts are the capability evaluator's own; nothing here decides
1904    /// what "provided" means. The evaluator counts a capability provided as
1905    /// soon as a module claiming it has REGISTERED, not once that module is
1906    /// ready. That distinction is what keeps two modules that require each
1907    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1908    /// is ready", each would wait for the other to become ready first and
1909    /// neither ever would. Do not tighten it to readiness.
1910    ///
1911    /// A required capability with no verdict at all means this registration's
1912    /// HELLO or catalog.update landed after the last recompute; recompute once
1913    /// rather than let a missing verdict read as either answer. If it is still
1914    /// missing (the recompute itself failed) the capability counts as
1915    /// unprovided: the refusal is retryable, and routing a module whose
1916    /// required provider is unknown is the outcome this check exists to stop.
1917    fn first_unprovided_required_capability(
1918        &self,
1919        registration: &crate::registry::ModuleRegistration,
1920    ) -> Option<String> {
1921        self.first_unprovided_required_capability_for(
1922            &registration.manifest.module_id,
1923            registration.manifest.capabilities.as_ref(),
1924        )
1925    }
1926
1927    fn first_unprovided_required_capability_for(
1928        &self,
1929        module_id: &str,
1930        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1931    ) -> Option<String> {
1932        let required = capabilities
1933            .into_iter()
1934            .flat_map(|declarations| declarations.requires.iter())
1935            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1936            .map(|requirement| requirement.capability.as_str())
1937            .collect::<BTreeSet<_>>();
1938        if required.is_empty() {
1939            return None;
1940        }
1941        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1942        if required
1943            .iter()
1944            .any(|capability| verdict(capability).is_none())
1945        {
1946            self.refresh_capability_requirements();
1947        }
1948        required
1949            .into_iter()
1950            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1951            .map(str::to_string)
1952    }
1953
1954    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1955        self.capability_evaluator
1956            .statuses()
1957            .into_iter()
1958            .map(RequirementStatus::into_wire)
1959            .collect()
1960    }
1961
1962    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1963    /// registration-release watch. The signal is what the supervisor waits on
1964    /// before spawning a replacement, so it must only fire once forwarding
1965    /// teardown is also done (see [`Self::cleanup_connection`] /
1966    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1967    /// registry-only path below because publication already owns the spawn lock.
1968    fn deregister_connection(
1969        &self,
1970        connection_id: ConnectionId,
1971        reason: RegistrationEndReason,
1972    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1973        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1974            spawn.end_primary_registration();
1975        }
1976        self.registry
1977            .deregister_connection_with_reason(connection_id, reason)
1978    }
1979
1980    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1981    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1982    // or claim-bound consumers to revoke. Remove only its unpublished registry
1983    // entry without re-entering primary-registration teardown.
1984    fn rollback_unpublished_hello(
1985        &self,
1986        connection: ConnectionId,
1987    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1988        self.registry.deregister_connection_with_reason(
1989            connection,
1990            RegistrationEndReason::RegistrationFailed,
1991        )
1992    }
1993
1994    fn request_refusal_close(
1995        &self,
1996        connection: ConnectionId,
1997        sink: Option<&crate::FrameSink>,
1998        reason: CloseReason,
1999    ) {
2000        if let Some(sink) = sink {
2001            sink.terminate_ingress();
2002        }
2003        if self.claims.close_notifications_enabled() {
2004            self.forwarding.request_connection_close(connection, reason);
2005        }
2006    }
2007
2008    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
2009        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
2010            return None;
2011        }
2012        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
2013            parse_client_control_request(&frame.body)
2014        else {
2015            return None;
2016        };
2017        Some(target_module_id(&target).to_string())
2018    }
2019
2020    pub(crate) fn route_open_capacity_refusal(
2021        &self,
2022        ctx: &RouteCtx,
2023        frame: &Frame,
2024        target_module_id: &str,
2025        in_flight: usize,
2026        limit: usize,
2027    ) -> Result<Frame, RouterError> {
2028        // Sent before the request reaches `handle_route_open`, so the caller
2029        // fields come from the raw frame here.
2030        let caller = self.route_open_caller_from_frame(ctx, frame);
2031        self.route_open_admission_refusal_frame(
2032            ctx,
2033            &caller,
2034            frame,
2035            target_module_id,
2036            "open_admission_full",
2037            (in_flight, limit),
2038            format!(
2039                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
2040            ),
2041        )
2042    }
2043
2044    fn route_open_target_capacity_refusal(
2045        &self,
2046        ctx: &RouteCtx,
2047        caller: &RouteOpenCaller,
2048        frame: &Frame,
2049        target_module_id: &str,
2050        in_flight: usize,
2051    ) -> Result<Frame, RouterError> {
2052        self.route_open_admission_refusal_frame(
2053            ctx,
2054            caller,
2055            frame,
2056            target_module_id,
2057            "target_binds_full",
2058            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
2059            format!(
2060                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
2061            ),
2062        )
2063    }
2064
2065    /// Admission pressure clears as existing binds settle, so its refusal must
2066    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
2067    /// `module_reloading`, `module_warming`, `target_unavailable`, or
2068    /// `module_timeout`. `target_unavailable` is honest for an attempt that
2069    /// cannot currently reach its target; `module_timeout` would falsely claim
2070    /// that a wait expired. A new, cleaner code would be terminal to deployed
2071    /// clients, so it requires a client-tolerance rollout before daemon emission.
2072    #[allow(clippy::too_many_arguments)]
2073    fn route_open_admission_refusal_frame(
2074        &self,
2075        ctx: &RouteCtx,
2076        caller: &RouteOpenCaller,
2077        frame: &Frame,
2078        target_module_id: &str,
2079        reason: &'static str,
2080        (in_flight, limit): (usize, usize),
2081        message: impl Into<String>,
2082    ) -> Result<Frame, RouterError> {
2083        let code = error_codes::TARGET_UNAVAILABLE;
2084        self.counters.increment_route_open_refused(code);
2085        info!(
2086            target: "control",
2087            code,
2088            reason,
2089            module_id = ?target_module_id,
2090            connection_id = ctx.connection_id.get(),
2091            principal = %caller.principal,
2092            scope = %caller.scope,
2093            harness = %caller.harness,
2094            in_flight,
2095            limit,
2096            "route.open refused"
2097        );
2098        control_error_frame(frame, code, message.into())
2099    }
2100
2101    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
2102    ///
2103    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
2104    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
2105    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
2106    #[cfg(test)]
2107    pub fn handle_control(
2108        &self,
2109        connection_id: ConnectionId,
2110        frame: Frame,
2111    ) -> Result<Vec<Frame>, RouterError> {
2112        match frame.header.ty {
2113            FrameType::Ping => Ok(vec![pong(&frame)?]),
2114            FrameType::Hello => self.handle_hello(connection_id, None, frame),
2115            FrameType::Goodbye => self.handle_goodbye(connection_id),
2116            ty => Ok(vec![control_error_frame(
2117                &frame,
2118                "unsupported_control_frame",
2119                format!("unsupported channel-0 frame {ty:?}"),
2120            )?]),
2121        }
2122    }
2123
2124    pub async fn handle_control_frame(
2125        &self,
2126        ctx: &RouteCtx,
2127        frame: Frame,
2128    ) -> Result<Vec<Frame>, RouterError> {
2129        self.handle_control_frame_timed(ctx, frame, None).await
2130    }
2131
2132    #[cfg(any(test, feature = "test-support"))]
2133    pub fn with_test_operator_app_policy(
2134        mut self,
2135        policy: crate::operator_apps::TestOperatorAppPolicy,
2136    ) -> Self {
2137        self.operator_app_policy = policy.into();
2138        self
2139    }
2140
2141    /// Inject the Windows signature check for tests. The injected check
2142    /// answers the verified version string or the rejection reason; the
2143    /// daemon enforces the floor itself on the returned version.
2144    #[cfg(all(windows, any(test, feature = "test-support")))]
2145    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
2146        self.windows_verify = Some(verify);
2147        self
2148    }
2149
2150    /// Record which pids the daemon would flash for `already_running`.
2151    #[cfg(all(windows, any(test, feature = "test-support")))]
2152    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
2153        self.windows_flash = Some(flash);
2154        self
2155    }
2156
2157    /// Inject a tracking failure for tests: makes `track_launched_process`
2158    /// fail so a test can prove a launch that cannot be tracked is stopped,
2159    /// never left running.
2160    #[cfg(all(windows, any(test, feature = "test-support")))]
2161    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2162        self.windows_track = Some(track);
2163        self
2164    }
2165
2166    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2167        self.local_connections
2168            .lock()
2169            .unwrap_or_else(|p| p.into_inner())
2170            .insert(connection);
2171    }
2172
2173    // Keep the connection-level delivery decision shared with route.bind. The
2174    // target's capability opt-in is separate from recognition of the caller.
2175    fn connection_operator_app(
2176        &self,
2177        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2178    ) -> Option<subc_protocol::peer::OperatorApp> {
2179        stamp
2180            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2181            .map(|stamp| stamp.app.clone())
2182    }
2183
2184    pub(crate) fn record_observed_peer(
2185        &self,
2186        connection: ConnectionId,
2187        peer: subc_os::local_peer::ObservedPeer,
2188    ) {
2189        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2190        let peer = match peer {
2191            OsPeer::Unobserved => ObservedPeer::unobserved(),
2192            OsPeer::Observed(peer) => {
2193                let observed = match peer.user {
2194                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2195                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2196                };
2197                observed
2198                    .with_exe(
2199                        peer.exe
2200                            .and_then(|path| path.into_os_string().into_string().ok()),
2201                    )
2202                    .with_signing_id(peer.signing_id)
2203            }
2204        };
2205        self.observed_peers
2206            .lock()
2207            .unwrap_or_else(|p| p.into_inner())
2208            .insert(connection, peer);
2209    }
2210
2211    pub(crate) fn record_caller_endpoints(
2212        &self,
2213        connection: ConnectionId,
2214        endpoints: Option<(SocketAddr, SocketAddr)>,
2215    ) {
2216        let mut callers = self
2217            .caller_endpoints
2218            .lock()
2219            .unwrap_or_else(|p| p.into_inner());
2220        callers.remove(&connection);
2221        if let Some(endpoints) = endpoints {
2222            callers.insert(connection, endpoints);
2223        }
2224    }
2225
2226    #[cfg(test)]
2227    pub(crate) fn with_caller_lookup_for_test(
2228        mut self,
2229        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2230    ) -> Self {
2231        self.caller_lookup = Some(Arc::new(lookup));
2232        self
2233    }
2234
2235    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2236        let endpoints = self
2237            .caller_endpoints
2238            .lock()
2239            .unwrap_or_else(|p| p.into_inner())
2240            .get(&connection)
2241            .copied();
2242        #[cfg(test)]
2243        let lookup = self.caller_lookup.clone();
2244        tokio::task::spawn_blocking(move || {
2245            #[cfg(test)]
2246            if let Some(lookup) = lookup {
2247                return lookup(endpoints);
2248            }
2249            endpoints
2250                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2251                .unwrap_or_default()
2252        })
2253        .await
2254        .unwrap_or_default()
2255    }
2256
2257    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2258        frame.header.channel == 0
2259            && frame.header.ty == FrameType::Request
2260            && self
2261                .forwarding
2262                .module_endpoint_for_connection(ctx.connection_id)
2263                .is_ok_and(|endpoint| endpoint.is_none())
2264            && parse_client_control_request(&frame.body)
2265                .ok()
2266                .is_some_and(|request| privileged_operation(&request).is_some())
2267    }
2268
2269    pub(crate) async fn handle_control_frame_timed(
2270        &self,
2271        ctx: &RouteCtx,
2272        frame: Frame,
2273        dispatch_started_at: Option<StdInstant>,
2274    ) -> Result<Vec<Frame>, RouterError> {
2275        let first = ctx.egress.first_ingress_frame();
2276        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2277            .await
2278    }
2279
2280    pub(crate) async fn handle_control_frame_ingress(
2281        &self,
2282        ctx: &RouteCtx,
2283        frame: Frame,
2284        dispatch_started_at: Option<StdInstant>,
2285        first: bool,
2286    ) -> Result<Vec<Frame>, RouterError> {
2287        if ctx.egress.ingress_terminal() {
2288            return Ok(Vec::new());
2289        }
2290        #[cfg(test)]
2291        self.claims.record_dispatch(frame.header.corr);
2292        let claim_binding = self.claims.binding(ctx.connection_id);
2293        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2294            && claim_binding
2295                .as_ref()
2296                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2297        .then(|| self.prefix_hello_attempt(ctx));
2298        if claim_binding
2299            .as_ref()
2300            .is_some_and(|binding| binding.prefix_module_id().is_some())
2301        {
2302            let registered = self
2303                .forwarding
2304                .module_endpoint_for_connection(ctx.connection_id)
2305                .map_err(RouterError::Forwarding)?
2306                .is_some();
2307            if !registered && frame.header.ty != FrameType::Hello {
2308                return self
2309                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2310                    .await;
2311            }
2312            if registered && frame.header.ty == FrameType::Goodbye {
2313                ctx.egress.terminate_ingress();
2314                let result = self.handle_goodbye(ctx.connection_id);
2315                self.claims.connection_closed(ctx.connection_id);
2316                self.request_refusal_close(
2317                    ctx.connection_id,
2318                    Some(&ctx.egress),
2319                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2320                );
2321                return result;
2322            }
2323            if registered && frame.header.ty == FrameType::Request {
2324                let allowed =
2325                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2326                        matches!(
2327                            probe.op.as_str(),
2328                            "catalog.update"
2329                                | "catalog.update_role_declarations"
2330                                | "scope.describe"
2331                                | "scope.watch"
2332                                | "supervisor.live_roots"
2333                                | "activity.record"
2334                        )
2335                    });
2336                if !allowed {
2337                    return Ok(vec![control_error_frame(
2338                        &frame,
2339                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2340                        "prefix registrations have only brokered module operations",
2341                    )?]);
2342                }
2343            }
2344            if registered
2345                && frame.header.ty == FrameType::Push
2346                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2347                    .is_ok_and(|probe| probe.op == "route.status")
2348            {
2349                return Ok(vec![control_error_frame(
2350                    &frame,
2351                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2352                    "prefix registrations may push only route.status for routes they serve",
2353                )?]);
2354            }
2355        }
2356        match frame.header.ty {
2357            FrameType::Ping => Ok(vec![pong(&frame)?]),
2358            FrameType::Hello => {
2359                if claim_binding
2360                    .as_ref()
2361                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2362                {
2363                    return self
2364                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2365                        .await;
2366                }
2367                // Resolved once, here: the blocking HELLO below may outlive this
2368                // reader and run after cleanup has forgotten the channel, and it
2369                // must still be judged as this channel's HELLO.
2370                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2371                if let Some(spawn) = &channel_spawn {
2372                    spawn.wait_launch().await;
2373                    // Refused launches close the channel. Leave their pending
2374                    // HELLO unanswered instead of racing a reply against shutdown.
2375                    if !spawn.launch_ready() {
2376                        ctx.egress.terminate_ingress();
2377                        return Ok(Vec::new());
2378                    }
2379                    #[cfg(test)]
2380                    self.pause_hello_ingress_for_test().await;
2381                } else if claim_binding.is_none() {
2382                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2383                        if let (Some(module), Some(nonce)) = (
2384                            hello
2385                                .get("manifest")
2386                                .and_then(|value| value.get("module_id"))
2387                                .and_then(|value| value.as_str()),
2388                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2389                        ) {
2390                            if !self
2391                                .config_runtime
2392                                .as_ref()
2393                                .is_some_and(|owner| owner.module_is_gated(module))
2394                                && !self.supervisor.wait_program_binding(module, nonce).await
2395                            {
2396                                self.request_refusal_close(
2397                                    ctx.connection_id,
2398                                    Some(&ctx.egress),
2399                                    CloseReason::new(
2400                                        "program_refused",
2401                                        "the spawned program binding failed",
2402                                    ),
2403                                );
2404                                return Ok(vec![control_error_frame(
2405                                    &frame,
2406                                    if self
2407                                        .config_runtime
2408                                        .as_ref()
2409                                        .is_some_and(|owner| owner.is_recovering())
2410                                    {
2411                                        "config_gated"
2412                                    } else {
2413                                        "program_refused"
2414                                    },
2415                                    "the spawned program binding failed",
2416                                )?]);
2417                            }
2418                        }
2419                    }
2420                }
2421                let handler = self.clone();
2422                let connection = ctx.connection_id;
2423                let egress = ctx.egress.clone();
2424                let correlation = frame.header.corr;
2425                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2426                let span = tracing::Span::current();
2427                let hello_binding = claim_binding.clone();
2428                let replies = tokio::task::spawn_blocking(move || {
2429                    tracing::dispatcher::with_default(&dispatcher, || {
2430                        span.in_scope(|| {
2431                            handler.handle_hello_checked(
2432                                connection,
2433                                Some(egress),
2434                                frame,
2435                                true,
2436                                hello_binding,
2437                                channel_spawn,
2438                            )
2439                        })
2440                    })
2441                })
2442                .await
2443                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2444                #[cfg(test)]
2445                if prefix_attempt.is_some() {
2446                    self.claims.pause_prefix_commit_for_test(false).await;
2447                }
2448                if let Some(attempt) = &mut prefix_attempt {
2449                    let accepted = !replies
2450                        .iter()
2451                        .any(|reply| reply.header.ty == FrameType::Error)
2452                        && self
2453                            .registry
2454                            .get_module_by_connection(ctx.connection_id)
2455                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2456                            .is_some();
2457                    if accepted {
2458                        attempt.accepted = true;
2459                    } else {
2460                        ctx.egress.terminate_ingress();
2461                        for reply in replies {
2462                            ctx.egress.send_flushed(reply).await?;
2463                        }
2464                        return Ok(Vec::new());
2465                    }
2466                }
2467                Ok(replies)
2468            }
2469            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2470            FrameType::Cancel => {
2471                // Channel-0 cancellation withdraws approvals and subscriptions
2472                // and fences pending agent declarations;
2473                // successful cancellation has no ordinary reply.
2474                // A config Apply may also own an OS prompt. Cancel that prompt
2475                // before config cancellation can report the request handled.
2476                if self
2477                    .agent_declarations
2478                    .cancel(ctx.connection_id, frame.header.corr)
2479                    || self
2480                        .forwarding
2481                        .operator_confirms()
2482                        .cancel(ctx.connection_id, frame.header.corr)
2483                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2484                    || self
2485                        .supervisor
2486                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2487                    || self.cancel_activity_subscription(ctx, &frame)?
2488                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2489                    || self
2490                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2491                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2492                {
2493                    Ok(Vec::new())
2494                } else {
2495                    Ok(vec![control_error_frame(
2496                        &frame,
2497                        "unknown_subscription",
2498                        "no subscription has this correlation id",
2499                    )?])
2500                }
2501            }
2502            FrameType::Request => {
2503                // This additive operation is not part of the existing exhaustive
2504                // module-control enum. Probe the op before decoding that enum.
2505                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2506                if let Some(probe) = &op {
2507                    self.record_control_usage(ctx.connection_id, &probe.op);
2508                }
2509                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2510                if let Some(refusal) = self
2511                    .recovery_request_refusal(
2512                        ctx,
2513                        &frame,
2514                        op.as_ref().map(|probe| probe.op.as_str()),
2515                    )
2516                    .await?
2517                {
2518                    if claim_present {
2519                        self.reclaim_presented_expiry(&frame);
2520                        return self
2521                            .refuse_claim_connection(ctx, &frame, "config_gated")
2522                            .await;
2523                    }
2524                    return Ok(vec![refusal]);
2525                }
2526                if claim_present {
2527                    return self.handle_claim_present(ctx, &frame, first).await;
2528                }
2529                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2530                    return self.handle_claim_mint(ctx, &frame).await;
2531                }
2532                if let Some(refusal) = self.registration_operation_refusal(
2533                    ctx,
2534                    &frame,
2535                    op.as_ref().map(|probe| probe.op.as_str()),
2536                )? {
2537                    return Ok(vec![refusal]);
2538                }
2539                if op
2540                    .as_ref()
2541                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2542                {
2543                    return self.handle_catalog_watch(ctx, frame);
2544                }
2545                if op
2546                    .as_ref()
2547                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2548                {
2549                    return self.handle_scope_watch(ctx, frame);
2550                }
2551                if op
2552                    .as_ref()
2553                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2554                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2555                        .unwrap_or(false)
2556                {
2557                    return Ok(vec![control_error_frame(
2558                        &frame,
2559                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2560                        "provider_declarations are fixed at HELLO; restart the module to change them",
2561                    )?]);
2562                }
2563                if let Some(probe) = op
2564                    .as_ref()
2565                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2566                {
2567                    return self
2568                        .handle_module_config_request(ctx, frame, &probe.op)
2569                        .await;
2570                }
2571                if op
2572                    .as_ref()
2573                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2574                {
2575                    return self.handle_config_gate_request(ctx, frame).await;
2576                }
2577                if op
2578                    .as_ref()
2579                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2580                {
2581                    return self.handle_activity_record(ctx, frame).await;
2582                }
2583                if op.as_ref().is_some_and(|probe| {
2584                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2585                }) {
2586                    return self.handle_activity_read(ctx, frame).await;
2587                }
2588                if op
2589                    .as_ref()
2590                    .is_some_and(|probe| probe.op == "operator.confirm")
2591                {
2592                    return self.handle_operator_confirm(ctx, frame).await;
2593                }
2594                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2595                    return self
2596                        .observe_control_wait(
2597                            ctx,
2598                            None,
2599                            ops::APP_OPEN,
2600                            self.handle_app_open(ctx, frame),
2601                        )
2602                        .await;
2603                }
2604                if op
2605                    .as_ref()
2606                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2607                {
2608                    return self.handle_connection_describe(ctx, frame).await;
2609                }
2610                if op
2611                    .as_ref()
2612                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2613                {
2614                    return self.handle_scope_served_by(ctx.connection_id, frame);
2615                }
2616                if self
2617                    .forwarding
2618                    .module_endpoint_for_connection(ctx.connection_id)
2619                    .map_err(RouterError::Forwarding)?
2620                    .is_some()
2621                {
2622                    if !is_known_module_request_op(&frame.body) {
2623                        return Ok(vec![control_error_frame(
2624                            &frame,
2625                            "unsupported_control_frame",
2626                            "module-originated channel-0 REQUEST is not supported",
2627                        )?]);
2628                    }
2629                    let request = match parse_module_control_request_from_module(&frame.body) {
2630                        Ok(request) => request,
2631                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2632                            return Ok(vec![control_error_frame(
2633                                &frame,
2634                                "unsupported_control_frame",
2635                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2636                            )?])
2637                        }
2638                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2639                            return Ok(vec![control_error_frame(
2640                                &frame,
2641                                "invalid_control_body",
2642                                format!("malformed module control body: {err}"),
2643                            )?])
2644                        }
2645                    };
2646                    let op = module_control_request_op(&request);
2647                    let corr = frame.header.corr;
2648                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2649                    if let ModuleControlRequestFromModule::AgentCommands {
2650                        started,
2651                        finished,
2652                        known,
2653                    } = request
2654                    {
2655                        return self
2656                            .agent_declarations
2657                            .enqueue(
2658                                self,
2659                                ctx,
2660                                frame,
2661                                crate::resource_totals::Declaration {
2662                                    started,
2663                                    finished,
2664                                    known,
2665                                },
2666                            )
2667                            .await;
2668                    }
2669                    let result =
2670                        self.handle_module_control_request(ctx.connection_id, frame, request);
2671                    log_slow_control_dispatch(
2672                        dispatch_started_at,
2673                        op,
2674                        ctx.connection_id,
2675                        corr,
2676                        None,
2677                    );
2678                    return result;
2679                }
2680
2681                if is_known_module_request_op(&frame.body) {
2682                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2683                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2684                    let code = if is_agents {
2685                        "not_supervised"
2686                    } else if op
2687                        .as_ref()
2688                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2689                    {
2690                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2691                    } else {
2692                        "not_registered"
2693                    };
2694                    return Ok(vec![control_error_frame(
2695                        &frame,
2696                        code,
2697                        "module-originated control requests require the module's own registered connection",
2698                    )?]);
2699                }
2700
2701                let request = match parse_client_control_request(&frame.body) {
2702                    Ok(request) => request,
2703                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2704                        return Ok(vec![control_error_frame(
2705                            &frame,
2706                            "unknown_control_op",
2707                            format!("unknown client control op: {err}"),
2708                        )?])
2709                    }
2710                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2711                        return Ok(vec![control_error_frame(
2712                            &frame,
2713                            "invalid_control_body",
2714                            format!("malformed client control body: {err}"),
2715                        )?])
2716                    }
2717                };
2718                let op = client_control_request_op(&request);
2719                let corr = frame.header.corr;
2720                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2721                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2722                #[cfg(test)]
2723                if let Some(delay) = self.control_dispatch_delay {
2724                    tokio::time::sleep(delay).await;
2725                }
2726                let result = self
2727                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2728                    .await;
2729                if let Some(timings) = route_open_timings.as_mut() {
2730                    timings.finish();
2731                }
2732                log_slow_control_dispatch(
2733                    dispatch_started_at,
2734                    op,
2735                    ctx.connection_id,
2736                    corr,
2737                    route_open_timings.as_ref(),
2738                );
2739                result
2740            }
2741            FrameType::Push => {
2742                let Some(endpoint) = self
2743                    .forwarding
2744                    .module_endpoint_for_connection(ctx.connection_id)
2745                    .map_err(RouterError::Forwarding)?
2746                else {
2747                    return Ok(vec![control_error_frame(
2748                        &frame,
2749                        "unsupported_control_frame",
2750                        "client-originated channel-0 PUSH is not supported",
2751                    )?]);
2752                };
2753                self.handle_status_update(endpoint, frame)
2754            }
2755            FrameType::Response | FrameType::Error
2756                if self
2757                    .forwarding
2758                    .module_endpoint_for_connection(ctx.connection_id)
2759                    .map_err(RouterError::Forwarding)?
2760                    .is_some() =>
2761            {
2762                self.handle_module_relay_response(ctx.connection_id, frame)
2763            }
2764            ty => Ok(vec![control_error_frame(
2765                &frame,
2766                "unsupported_control_frame",
2767                format!("unsupported channel-0 frame {ty:?}"),
2768            )?]),
2769        }
2770    }
2771
2772    #[cfg(test)]
2773    fn pause_cleanup_for_test(&self, stage: u8) {
2774        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2775        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2776            let (_, (reached, release)) = slot.take().unwrap();
2777            drop(slot);
2778            let _ = reached.send(());
2779            let _ = release.recv_timeout(Duration::from_secs(5));
2780        }
2781    }
2782
2783    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2784    /// right after the nonce is resolved.
2785    #[cfg(all(test, unix, feature = "test-support"))]
2786    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2787        *self
2788            .after_nonce_attestation
2789            .lock()
2790            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2791    }
2792
2793    #[cfg(test)]
2794    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2795        let hook = self
2796            .after_nonce_attestation
2797            .lock()
2798            .unwrap_or_else(|p| p.into_inner())
2799            .take();
2800        if let Some(hook) = hook {
2801            hook();
2802        }
2803    }
2804
2805    #[cfg(test)]
2806    async fn pause_hello_ingress_for_test(&self) {
2807        let pause = self
2808            .hello_ingress_pause
2809            .lock()
2810            .unwrap_or_else(|p| p.into_inner())
2811            .take();
2812        if let Some((reached, release)) = pause {
2813            let _ = reached.send(());
2814            let _ = release.await;
2815        }
2816    }
2817
2818    pub fn cleanup_connection(
2819        &self,
2820        connection_id: ConnectionId,
2821    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2822        // The server loop joins its offloaded request tasks (route opens,
2823        // privileged requests and activity reads) before this cleanup runs, and
2824        // inline dispatch has ended. Two kinds of work are not joined. Agent
2825        // command declarations run on their queue's detached worker, so the
2826        // queue is closed first: every declaration still queued or validating
2827        // has its commit fence cancelled before anything below can change how
2828        // the connection resolves. A HELLO whose reader was dropped keeps
2829        // running on its blocking thread. It carries the channel spawn its
2830        // reader resolved at ingress instead of re-reading the index forgotten
2831        // below, so it is still judged as that channel's HELLO: the retired
2832        // spawn refuses it before it records anything, and a channel HELLO
2833        // never records a launch nonce, so it cannot leave this connection any
2834        // nonce authority.
2835        self.agent_declarations.close(connection_id);
2836        self.close_catalog_subscriptions(connection_id);
2837        self.close_config_settings_subscriptions(connection_id);
2838        self.close_scope_subscriptions(connection_id);
2839        #[cfg(test)]
2840        self.pause_cleanup_for_test(0);
2841        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2842            spawn.retire_registration_channel();
2843        }
2844        self.supervisor
2845            .forget_registration_connection(connection_id);
2846        #[cfg(test)]
2847        self.pause_cleanup_for_test(1);
2848        self.local_connections
2849            .lock()
2850            .unwrap_or_else(|p| p.into_inner())
2851            .remove(&connection_id);
2852        self.caller_endpoints
2853            .lock()
2854            .unwrap_or_else(|p| p.into_inner())
2855            .remove(&connection_id);
2856        self.build_class_warned
2857            .lock()
2858            .unwrap_or_else(|p| p.into_inner())
2859            .remove(&connection_id);
2860        // Retire the capture before its published facts so an in-flight
2861        // verification cannot recreate them after cleanup.
2862        self.captured_peers
2863            .lock()
2864            .unwrap_or_else(|p| p.into_inner())
2865            .remove(&connection_id);
2866        self.observed_peers
2867            .lock()
2868            .unwrap_or_else(|p| p.into_inner())
2869            .remove(&connection_id);
2870        self.config_desktop_stamps
2871            .lock()
2872            .unwrap_or_else(|p| p.into_inner())
2873            .remove(&connection_id);
2874        self.operator_apps
2875            .lock()
2876            .unwrap_or_else(|p| p.into_inner())
2877            .remove(&connection_id);
2878        self.forwarding
2879            .operator_confirms()
2880            .connection_closed(connection_id);
2881        let cleanup = self.cleanup_connection_with_end_reason(
2882            connection_id,
2883            RegistrationEndReason::ConnectionClosed,
2884        );
2885        // A draining writer can still be reached by a route until forwarding
2886        // cleanup finishes. Keep its claim sink visible to launch retirement.
2887        self.claims.connection_closed(connection_id);
2888        cleanup
2889    }
2890
2891    fn cleanup_connection_with_end_reason(
2892        &self,
2893        connection_id: ConnectionId,
2894        requested_reason: RegistrationEndReason,
2895    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2896        #[cfg(test)]
2897        if let Some(pause) = self
2898            .activity_request_pause
2899            .lock()
2900            .unwrap()
2901            .as_ref()
2902            .filter(|pause| pause.connection == connection_id)
2903        {
2904            pause
2905                .cleanup_started
2906                .store(true, std::sync::atomic::Ordering::Release);
2907        }
2908        if let Some(runtime) = &self.config_runtime {
2909            runtime.disconnected(connection_id);
2910        }
2911        self.agent_declarations.close(connection_id);
2912        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2913            self.registry
2914                .get_module_by_connection(connection_id)?
2915                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2916                .and_then(|module| module.registration_end_reason().ok().flatten())
2917                .unwrap_or(requested_reason)
2918        } else {
2919            requested_reason
2920        };
2921        let crash_closed = self
2922            .registry
2923            .get_module_by_connection(connection_id)?
2924            .and_then(|registration| {
2925                self.forwarding
2926                    .module_endpoint_for_connection(connection_id)
2927                    .ok()
2928                    .flatten()
2929                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2930                    .map(|routes| (registration.manifest.module_id, routes))
2931            });
2932        let crash_closed = crash_closed.map(|(module_id, routes)| {
2933            let terminal = match self.supervisor.get(&module_id) {
2934                None => false,
2935                Some(module) => match module.will_recover_after_connection_loss() {
2936                    Ok(will_recover) => !will_recover,
2937                    Err(err) => {
2938                        warn!(
2939                            %module_id,
2940                            error = %err,
2941                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2942                        );
2943                        false
2944                    }
2945                },
2946            };
2947            // The forwarding table gates all providers at the start of daemon
2948            // shutdown, before their connections are closed. An ordinary
2949            // module disconnect still reports crash if that gate is not set.
2950            let (reason, drained) = match self
2951                .forwarding
2952                .daemon_drain_result_for_connection(connection_id)
2953            {
2954                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
2955                Ok(None) => (RouteCloseReason::Crash, false),
2956                Err(err) => {
2957                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
2958                    (RouteCloseReason::Crash, false)
2959                }
2960            };
2961            (module_id, routes, reason, drained, terminal)
2962        });
2963        let registrations = self.deregister_connection(connection_id, end_reason);
2964        // Read before teardown: the spawn whose registration this connection
2965        // was. Its registration ending is an authority change for it.
2966        let ended_authority = self
2967            .forwarding
2968            .target_authority_for_connection(connection_id)
2969            .ok()
2970            .flatten();
2971        let cleanup = if crash_closed.is_some() {
2972            self.forwarding.cleanup_connection_counted(connection_id)
2973        } else {
2974            // A module connection's teardown needs the count of abandoned
2975            // route.bind relays for its route.closed notice below. Any other
2976            // connection, such as a client's, sends no such notice and needs
2977            // only its routes released, so it uses the route-only wrapper and
2978            // reports zero.
2979            self.forwarding
2980                .cleanup_connection(connection_id)
2981                .map(|released| crate::forwarding::ConnectionCleanup {
2982                    released,
2983                    abandoned_relays: 0,
2984                })
2985        };
2986        // The route.closed push waits for forwarding teardown because only
2987        // teardown knows how many pending route.bind relays it aborted. It still
2988        // goes out before the GOODBYEs for the released routes, and its targets
2989        // were captured above, before teardown removed those routes.
2990        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
2991            let abandoned = cleanup
2992                .as_ref()
2993                .map_or(0, |cleanup| cleanup.abandoned_relays);
2994            send_route_control_pushes(
2995                &self.forwarding,
2996                routes,
2997                ClientControlPush::RouteClosed {
2998                    module_id,
2999                    channels: Vec::new(),
3000                    reason,
3001                    drained,
3002                    abandoned,
3003                    excluded_subscriptions: 0,
3004                    terminal: Some(terminal),
3005                },
3006            );
3007        }
3008        if let Ok(cleanup) = cleanup {
3009            self.emit_route_goodbyes(cleanup.released);
3010        }
3011        if let Some(record) = ended_authority {
3012            self.change_spawn_authority(&record);
3013        }
3014        // Signal the registration-release watch only now that BOTH registry and
3015        // forwarding teardown are done, so a supervisor waiting to spawn a
3016        // replacement never observes release while old routes still exist.
3017        if matches!(&registrations, Ok(r) if !r.is_empty()) {
3018            crate::supervise::notify_registration_release();
3019            self.capability_evaluator.wake_deadline_loop();
3020            self.refresh_capability_requirements();
3021        }
3022        self.supervisor.remove_spawn_subscribers(connection_id);
3023        self.activity_streams
3024            .lock()
3025            .unwrap_or_else(|p| p.into_inner())
3026            .retain(|(id, _), task| {
3027                if *id == connection_id {
3028                    task.abort();
3029                    false
3030                } else {
3031                    true
3032                }
3033            });
3034        // Sync authority dies with its connection, so the owner's next
3035        // connection can take it; the owner's scopes stay as they are.
3036        self.hello_launch_nonces
3037            .lock()
3038            .unwrap_or_else(|poisoned| poisoned.into_inner())
3039            .forget(connection_id);
3040        self.scopes
3041            .write()
3042            .unwrap_or_else(|poisoned| poisoned.into_inner())
3043            .release_connection(connection_id);
3044        registrations
3045    }
3046
3047    pub(crate) fn handle_route_goodbye(
3048        &self,
3049        connection_id: ConnectionId,
3050        route_channel: u16,
3051        route_epoch: u32,
3052    ) -> Result<bool, RouterError> {
3053        debug!(
3054            connection_id = connection_id.get(),
3055            route_channel, route_epoch, "handling route GOODBYE"
3056        );
3057        let RouteRelease::Removed(released_route) = self
3058            .forwarding
3059            .release_client_route(connection_id, route_channel, route_epoch)
3060            .map_err(RouterError::Forwarding)?
3061        else {
3062            return Ok(false);
3063        };
3064        self.emit_route_goodbyes(vec![released_route]);
3065        Ok(true)
3066    }
3067
3068    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
3069        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
3070    }
3071
3072    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
3073    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
3074    /// own commit failed after the module had already accepted). Without this, a
3075    /// module that accepts late keeps a binding subc has torn down, so a later
3076    /// frame on that module channel could misdeliver if the channel is reused.
3077    ///
3078    /// Never closes the shared module connection on failure: a dropped notification
3079    /// only wastes a bounded amount of warm module-side state, which the module's
3080    /// own idle reaper reclaims. Only call this once the route.bind relay was
3081    /// actually enqueued to the module — if the relay send itself failed, the
3082    /// module never created a binding and there is nothing to tear down.
3083    fn send_abandoned_route_bind_goodbye(
3084        &self,
3085        module_sink: &crate::FrameSink,
3086        negotiated_ver: u8,
3087        module_channel: u16,
3088        module_epoch: u32,
3089    ) {
3090        let frame = match Frame::build_with_version(
3091            negotiated_ver,
3092            FrameType::Goodbye,
3093            control_flags(),
3094            module_channel,
3095            module_epoch,
3096            0,
3097            Vec::new(),
3098        ) {
3099            Ok(frame) => frame,
3100            Err(err) => {
3101                warn!(
3102                    route_channel = module_channel,
3103                    error = %err,
3104                    "failed to build GOODBYE for abandoned route.bind"
3105                );
3106                return;
3107            }
3108        };
3109        crate::forwarding::send_module_route_goodbye(
3110            &self.counters,
3111            module_sink,
3112            frame,
3113            None,
3114            "abandoned route.bind",
3115        );
3116    }
3117
3118    #[cfg(test)]
3119    fn handle_hello(
3120        &self,
3121        connection_id: ConnectionId,
3122        egress: Option<crate::router::FrameSink>,
3123        frame: Frame,
3124    ) -> Result<Vec<Frame>, RouterError> {
3125        let binding = self.claims.binding(connection_id);
3126        let channel_spawn = self.supervisor.registration_spawn(connection_id);
3127        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
3128    }
3129
3130    fn handle_hello_checked(
3131        &self,
3132        connection_id: ConnectionId,
3133        sink: Option<crate::FrameSink>,
3134        frame: Frame,
3135        wait_for_gate: bool,
3136        prefix_binding: Option<claims::ClaimBinding>,
3137        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3138    ) -> Result<Vec<Frame>, RouterError> {
3139        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
3140        #[cfg(test)]
3141        if prefix_binding.is_some() {
3142            self.claims.pause_prefix_hello_for_test(5);
3143            match self.claims.take_prefix_hello_failure_for_test() {
3144                Some("error") => {
3145                    return Err(RouterError::backend(
3146                        0,
3147                        frame.header.corr,
3148                        "injected HELLO failure",
3149                    ))
3150                }
3151                Some("panic") => panic!("injected HELLO task panic"),
3152                _ => {}
3153            }
3154        }
3155        if let Some(binding) = &prefix_binding {
3156            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3157            let module = value
3158                .as_ref()
3159                .and_then(|value| value["manifest"]["module_id"].as_str());
3160            if !binding.admit_prefix_hello(module)
3161                || !self.prefix_binding_live(binding, connection_id)
3162                || !module.is_some_and(|module| {
3163                    self.supervisor
3164                        .prefix_claim_authorized(&binding.registration.module_id, module)
3165                })
3166                || binding.registration.check().is_err()
3167            {
3168                return Ok(vec![control_error_frame(
3169                    &frame,
3170                    "claim_prefix_refused",
3171                    "HELLO must name the prefix claim's exact module id once",
3172                )?]);
3173            }
3174        }
3175        struct RefuseUnregisteredChannel {
3176            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3177            sink: Option<crate::FrameSink>,
3178        }
3179        impl Drop for RefuseUnregisteredChannel {
3180            fn drop(&mut self) {
3181                if let Some(spawn) = &self.spawn {
3182                    if !spawn.registered() {
3183                        if let Some(sink) = &self.sink {
3184                            sink.terminate_ingress();
3185                        }
3186                        spawn.retire_registration_channel();
3187                    }
3188                }
3189            }
3190        }
3191        let _channel_attempt = RefuseUnregisteredChannel {
3192            spawn: channel_spawn.clone(),
3193            sink: sink.clone(),
3194        };
3195        if let Some(spawn) = &channel_spawn {
3196            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3197            if let Err(code) = spawn.admit_hello(
3198                value
3199                    .as_ref()
3200                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3201            ) {
3202                return Ok(vec![control_error_frame(
3203                    &frame,
3204                    code,
3205                    "registration channel HELLO refused",
3206                )?]);
3207            }
3208        }
3209        debug!(
3210            connection_id = connection_id.get(),
3211            corr = frame.header.corr,
3212            "handling HELLO"
3213        );
3214        // A module connection has one identity for its entire lifetime. A second
3215        // registration would leave the old registry owner behind while replacing
3216        // its forwarding endpoint and launch nonce.
3217        if self
3218            .registry
3219            .get_module_by_connection(connection_id)
3220            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3221            .is_some()
3222        {
3223            return Ok(vec![control_error_frame(
3224                &frame,
3225                "invalid_hello",
3226                "connection is already registered as a module",
3227            )?]);
3228        }
3229        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3230            Ok(value) => value,
3231            Err(err) => {
3232                return Ok(vec![control_error_frame(
3233                    &frame,
3234                    "invalid_hello",
3235                    format!("malformed HELLO body: {err}"),
3236                )?])
3237            }
3238        };
3239        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3240            return Ok(vec![control_error_frame(
3241                &frame,
3242                error_codes::INVALID_PROVIDER_DECLARATIONS,
3243                detail,
3244            )?]);
3245        }
3246        if let Some(module) = hello_value
3247            .get("manifest")
3248            .and_then(|value| value.get("module_id"))
3249            .and_then(|value| value.as_str())
3250        {
3251            let recovering = self
3252                .config_runtime
3253                .as_ref()
3254                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3255            // Defence in depth: RuntimeOwner::module_is_gated in
3256            // config_gate/admission.rs already gates every id during recovery.
3257            // A registration channel still never uses the nonce fallback.
3258            if recovering
3259                && channel_spawn.as_ref().is_none_or(|spawn| {
3260                    !self.supervisor.has_live_verified_channel_binding(spawn)
3261                        || spawn.check().is_err()
3262                })
3263                && !(channel_spawn.is_none()
3264                    && hello_value
3265                        .get("launch_nonce")
3266                        .and_then(|value| value.as_str())
3267                        .is_some_and(|nonce| {
3268                            self.supervisor.spawned_consumer_authorized(module, nonce)
3269                                && self
3270                                    .supervisor
3271                                    .has_live_verified_program_binding(module, nonce)
3272                        }))
3273            {
3274                return Ok(vec![control_error_frame(
3275                    &frame,
3276                    "config_gated",
3277                    "recovery admits only previously bound supervised launches",
3278                )?]);
3279            }
3280            if self
3281                .config_runtime
3282                .as_ref()
3283                .is_some_and(|owner| owner.module_is_gated(module))
3284                && (channel_spawn
3285                    .as_ref()
3286                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3287                    || self.config_runtime.as_ref().is_some_and(|owner| {
3288                        !recovering && owner.check_module_hold(module).is_err()
3289                    }))
3290            {
3291                return Ok(vec![control_error_frame(
3292                    &frame,
3293                    "reserved_module",
3294                    "a gated identity belongs only to its supervised child",
3295                )?]);
3296            }
3297        }
3298        if channel_spawn.is_none() {
3299            if let (Some(module), Some(nonce)) = (
3300                hello_value
3301                    .get("manifest")
3302                    .and_then(|value| value.get("module_id"))
3303                    .and_then(|value| value.as_str()),
3304                hello_value
3305                    .get("launch_nonce")
3306                    .and_then(|value| value.as_str()),
3307            ) {
3308                let binding = self.supervisor.has_program_binding_record(module, nonce);
3309                let required = self
3310                    .config_runtime
3311                    .as_ref()
3312                    .is_some_and(|owner| owner.module_is_gated(module));
3313                if let Some(error) = (binding || required)
3314                    .then(|| {
3315                        self.supervisor
3316                            .check_current_program_binding(module, nonce)
3317                            .err()
3318                    })
3319                    .flatten()
3320                {
3321                    let code = if error.code == "program_refused" {
3322                        "program_refused"
3323                    } else {
3324                        "config_delivery_deferred"
3325                    };
3326                    self.request_refusal_close(
3327                        connection_id,
3328                        sink.as_ref(),
3329                        CloseReason::new(code, error.detail.clone()),
3330                    );
3331                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3332                }
3333            }
3334        }
3335        if let Err(err) = validate_hello_display_name(&hello_value) {
3336            return Ok(vec![control_error_frame(
3337                &frame,
3338                "invalid_manifest",
3339                err.to_string(),
3340            )?]);
3341        }
3342        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3343            return Ok(vec![control_error_frame(
3344                &frame,
3345                "invalid_capability_grammar",
3346                err.to_string(),
3347            )?]);
3348        }
3349        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3350            return Ok(vec![control_error_frame(
3351                &frame,
3352                "invalid_manifest",
3353                err.to_string(),
3354            )?]);
3355        }
3356        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3357            return Ok(vec![control_error_frame(
3358                &frame,
3359                "invalid_event_declaration",
3360                err.to_string(),
3361            )?]);
3362        }
3363        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3364            return Ok(vec![control_error_frame(
3365                &frame,
3366                "invalid_manifest",
3367                err.to_string(),
3368            )?]);
3369        }
3370        if let Some(provenance) = hello_value
3371            .get("manifest")
3372            .and_then(|manifest| manifest.get("provenance"))
3373        {
3374            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3375                return Ok(vec![control_error_frame(
3376                    &frame,
3377                    "invalid_manifest",
3378                    format!("malformed manifest provenance: {err}"),
3379                )?]);
3380            }
3381        }
3382        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3383            let module_id = hello_value["manifest"]["module_id"]
3384                .as_str()
3385                .unwrap_or("<unknown>");
3386            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3387        }
3388        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3389            let module_id = hello_value
3390                .get("manifest")
3391                .and_then(|m| m.get("module_id"))
3392                .and_then(serde_json::Value::as_str)
3393                .unwrap_or("unknown");
3394            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3395        }
3396        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3397            let module_id = hello_value["manifest"]["module_id"]
3398                .as_str()
3399                .unwrap_or("<unknown>");
3400            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3401        }
3402        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3403            let module_id = hello_value["manifest"]["module_id"]
3404                .as_str()
3405                .unwrap_or("<unknown>");
3406            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3407        }
3408        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3409            Ok(hello) => hello,
3410            Err(err) => {
3411                return Ok(vec![control_error_frame(
3412                    &frame,
3413                    "invalid_hello",
3414                    format!("malformed HELLO body: {err}"),
3415                )?])
3416            }
3417        };
3418
3419        if hello.protocol_ver != hello.manifest.protocol_ver {
3420            return Ok(vec![control_error_frame(
3421                &frame,
3422                "invalid_manifest",
3423                format!(
3424                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3425                    hello.protocol_ver, hello.manifest.protocol_ver
3426                ),
3427            )?]);
3428        }
3429
3430        if hello.manifest.module_id.trim().is_empty() {
3431            return Ok(vec![control_error_frame(
3432                &frame,
3433                "invalid_manifest",
3434                "manifest module_id must not be empty",
3435            )?]);
3436        }
3437
3438        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3439            Ok(negotiated_ver) => negotiated_ver,
3440            Err(message) => {
3441                return Ok(vec![control_error_frame(
3442                    &frame,
3443                    "version_unsupported",
3444                    message,
3445                )?])
3446            }
3447        };
3448
3449        // Registration and forwarding publication use the same module gate as
3450        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3451        // precede those transitions. A program-refusal hold blocks future
3452        // spawns, but does not take this gate or revoke a HELLO whose supervised
3453        // child's image has already passed the check.
3454        let _publication_gate = if let Some(owner) = &self.config_runtime {
3455            let gate = owner
3456                .module_gate(&hello.manifest.module_id)
3457                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3458            Some(if wait_for_gate {
3459                gate.blocking_lock_owned()
3460            } else {
3461                match gate.try_lock_owned() {
3462                    Ok(guard) => guard,
3463                    Err(_) => {
3464                        return Ok(vec![control_error_frame(
3465                            &frame,
3466                            "config_delivery_deferred",
3467                            "module admission is busy",
3468                        )?])
3469                    }
3470                }
3471            })
3472        } else {
3473            None
3474        };
3475        #[cfg(test)]
3476        if let Some(hold) = &self.hello_before_publication_hold {
3477            hold.wait();
3478            hold.wait();
3479        }
3480        let module = &hello.manifest.module_id;
3481        let required = self
3482            .config_runtime
3483            .as_ref()
3484            .is_some_and(|owner| owner.module_is_gated(module));
3485        let recovering = self
3486            .config_runtime
3487            .as_ref()
3488            .is_some_and(|owner| owner.is_recovering());
3489        // Both entry paths (handle_control -> handle_hello and
3490        // handle_control_frame_timed -> spawn_blocking) enter this same
3491        // handle_hello_checked function. Its fresh, fail-closed store check
3492        // precedes parsing and this publication-gate check; this cached read
3493        // also observes any recovery transition published during that work.
3494        // The nonce-connection-only fallback is defence in depth alongside
3495        // RuntimeOwner::module_is_gated's all-id recovery gate.
3496        if recovering
3497            && channel_spawn.as_ref().is_none_or(|spawn| {
3498                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3499            })
3500            && !(channel_spawn.is_none()
3501                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3502                    self.supervisor.spawned_consumer_authorized(module, nonce)
3503                        && self
3504                            .supervisor
3505                            .has_live_verified_program_binding(module, nonce)
3506                }))
3507        {
3508            return Ok(vec![control_error_frame(
3509                &frame,
3510                "config_gated",
3511                "recovery admits only previously bound supervised launches",
3512            )?]);
3513        }
3514        if required
3515            && (channel_spawn
3516                .as_ref()
3517                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3518                || self
3519                    .config_runtime
3520                    .as_ref()
3521                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3522        {
3523            return Ok(vec![control_error_frame(
3524                &frame,
3525                "reserved_module",
3526                "gated admission requires the current supervised child's registration channel and verified image binding",
3527            )?]);
3528        }
3529        if let Some(spawn) = &channel_spawn {
3530            if let Err(code) = spawn.check() {
3531                return Ok(vec![control_error_frame(
3532                    &frame,
3533                    code,
3534                    "registration launch is no longer live",
3535                )?]);
3536            }
3537        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3538            if required || self.supervisor.has_program_binding_record(module, nonce) {
3539                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3540                    let code = if error.code == "program_refused" {
3541                        "program_refused"
3542                    } else {
3543                        "config_delivery_deferred"
3544                    };
3545                    self.request_refusal_close(
3546                        connection_id,
3547                        sink.as_ref(),
3548                        CloseReason::new(code, error.detail.clone()),
3549                    );
3550                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3551                }
3552            }
3553        }
3554
3555        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3556        // swap is open for this id, the only HELLO admitted as a second process
3557        // is the one carrying the candidate's launch nonce (the swap token), and
3558        // it registers into the candidate slot rather than being refused as a
3559        // duplicate. Run after the reserved gate, a reserved module's candidate
3560        // would be refused `reserved_module` for presenting a nonce that gate
3561        // does not know. See `SupervisorHandle::swap_hello_admission`.
3562        let swap_admission = match &channel_spawn {
3563            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3564            Some(_) => SwapHelloAdmission::NotSwapping,
3565            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3566            None => self
3567                .supervisor
3568                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3569        };
3570        if swap_admission == SwapHelloAdmission::ProtocolNone {
3571            warn!(
3572                module_id = %hello.manifest.module_id,
3573                connection_id = connection_id.get(),
3574                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3575            );
3576            // The code stays `swap_token_invalid` for existing callers; only the
3577            // explanation names the actual reason.
3578            return Ok(vec![control_error_frame(
3579                &frame,
3580                "swap_token_invalid",
3581                format!(
3582                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3583                    hello.manifest.module_id
3584                ),
3585            )?]);
3586        }
3587        if swap_admission == SwapHelloAdmission::ChannelRequired {
3588            warn!(
3589                module_id = %hello.manifest.module_id,
3590                connection_id = connection_id.get(),
3591                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3592            );
3593            // The code stays `swap_token_invalid` for existing callers; only the
3594            // explanation names the actual reason.
3595            return Ok(vec![control_error_frame(
3596                &frame,
3597                "swap_token_invalid",
3598                format!(
3599                    "module_id '{}' is gated; it must register over its supervised registration channel",
3600                    hello.manifest.module_id
3601                ),
3602            )?]);
3603        }
3604        if swap_admission == SwapHelloAdmission::Refused {
3605            warn!(
3606                module_id = %hello.manifest.module_id,
3607                connection_id = connection_id.get(),
3608                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3609            );
3610            return Ok(vec![control_error_frame(
3611                &frame,
3612                "swap_token_invalid",
3613                format!(
3614                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3615                    hello.manifest.module_id
3616                ),
3617            )?]);
3618        }
3619        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3620
3621        // A swap candidate proves its identity with the candidate nonce above.
3622        // Other registrations receive this catalog fact only when reserved-module
3623        // policy required and accepted a nonce; unreserved registrations require
3624        // no nonce check.
3625        let verification = if swap_candidate && channel_spawn.is_none() {
3626            ReservedHelloVerification {
3627                nonce_verified: true,
3628                prefix_owner: None,
3629            }
3630        } else {
3631            let verification = if let Some(binding) = &prefix_binding {
3632                if !self.supervisor.prefix_claim_authorized(
3633                    &binding.registration.module_id,
3634                    &hello.manifest.module_id,
3635                ) {
3636                    return Ok(vec![control_error_frame(
3637                        &frame,
3638                        "claim_prefix_refused",
3639                        "prefix ownership changed",
3640                    )?]);
3641                }
3642                Ok(ReservedHelloVerification {
3643                    nonce_verified: true,
3644                    prefix_owner: Some(binding.registration.module_id.clone()),
3645                })
3646            } else if channel_spawn.is_some() {
3647                self.supervisor
3648                    .channel_hello_verification(&hello.manifest.module_id)
3649            } else {
3650                self.supervisor.reserved_hello_verification(
3651                    &hello.manifest.module_id,
3652                    hello.launch_nonce.as_deref(),
3653                )
3654            };
3655            match verification {
3656                Ok(verified) => verified,
3657                Err(rejection) => {
3658                    let message = match rejection {
3659                        ReservedHelloRejection::Exact { module_id } => format!(
3660                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3661                        ),
3662                        ReservedHelloRejection::Prefix {
3663                            prefix,
3664                            owner_module_id,
3665                        } => format!(
3666                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3667                            hello.manifest.module_id
3668                        ),
3669                    };
3670                    return Ok(vec![control_error_frame(
3671                        &frame,
3672                        "reserved_module",
3673                        message,
3674                    )?]);
3675                }
3676            }
3677        };
3678
3679        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3680            &hello.manifest.module_id,
3681            hello.manifest.capabilities.as_ref(),
3682        );
3683        if let Some(refusal) = reserved_capability_refusals.first() {
3684            let capability = refusal.capability.clone();
3685            let bound_module = refusal.claimants[0].clone();
3686            log_duplicate_claim_events(reserved_capability_refusals);
3687            return Ok(vec![control_error_frame(
3688                &frame,
3689                "reserved_capability",
3690                format!(
3691                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3692                    capability, bound_module, hello.manifest.module_id
3693                ),
3694            )?]);
3695        }
3696
3697        // A connection that already opened client routes must not also register as
3698        // a module: cleanup would then release only one side and leak the other.
3699        if self
3700            .forwarding
3701            .connection_has_client_routes(connection_id)
3702            .map_err(RouterError::Forwarding)?
3703        {
3704            return Ok(vec![control_error_frame(
3705                &frame,
3706                "invalid_hello",
3707                "connection has open client routes and cannot also register as a module",
3708            )?]);
3709        }
3710
3711        // Kept for scope sync authority, which goes only to the connection that
3712        // presented the module's current launch nonce. Recorded before the
3713        // registration is attempted: a connection whose registration then fails
3714        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3715        // A registration channel's authority is the channel itself, never a
3716        // nonce it also presented, and a prefix registration's is its claim:
3717        // neither records one, so neither can fall back to nonce authority.
3718        self.hello_launch_nonces
3719            .lock()
3720            .unwrap_or_else(|poisoned| poisoned.into_inner())
3721            .record(
3722                connection_id,
3723                if prefix_binding.is_some() || channel_spawn.is_some() {
3724                    None
3725                } else {
3726                    hello.launch_nonce.as_deref()
3727                },
3728            );
3729        let control_ops = effective_module_control_ops(hello.control_ops);
3730        let prefix_submodule = verification.prefix_owner.is_some();
3731        // Built before anything is registered so an encoding failure leaves no
3732        // registry or forwarding state behind.
3733        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3734        #[cfg(test)]
3735        struct PublicationFinished(Arc<std::sync::Barrier>);
3736        #[cfg(test)]
3737        impl Drop for PublicationFinished {
3738            fn drop(&mut self) {
3739                self.0.wait();
3740            }
3741        }
3742        #[cfg(test)]
3743        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3744            hold.wait();
3745            hold.wait();
3746            PublicationFinished(hold.clone())
3747        });
3748        let publication_spawn = channel_spawn
3749            .as_ref()
3750            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3751        #[cfg(test)]
3752        if prefix_binding.is_some() {
3753            self.claims.pause_prefix_hello_for_test(7);
3754        }
3755        let _registration_publication = match publication_spawn {
3756            Some(spawn) => Some(match spawn.begin_publication() {
3757                Ok(guard) => guard,
3758                Err(code) => {
3759                    return Ok(vec![control_error_frame(
3760                        &frame,
3761                        code,
3762                        "registration ended before HELLO publication",
3763                    )?])
3764                }
3765            }),
3766            None => None,
3767        };
3768        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3769            let live = self.claims.lock_prefix_binding(binding, connection_id);
3770            let ownership = self.supervisor.prefix_claim_publication(
3771                &binding.registration.module_id,
3772                &hello.manifest.module_id,
3773            );
3774            if live.is_none()
3775                || ownership.is_none()
3776                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3777                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3778            {
3779                return Ok(vec![control_error_frame(
3780                    &frame,
3781                    "claim_prefix_refused",
3782                    "prefix authority ended before publication",
3783                )?]);
3784            }
3785            (live, ownership)
3786        } else {
3787            (None, None)
3788        };
3789        if let Some(spawn) = publication_spawn {
3790            self.forwarding
3791                .bind_spawn(connection_id, spawn)
3792                .map_err(RouterError::Forwarding)?;
3793        }
3794        // The spawn whose own registration this HELLO is, for `target` on
3795        // the route.open reply: its channel, or the launch its nonce was
3796        // minted for. A prefix child's HELLO names no spawn of its own. It is
3797        // only looked up here. The connection is bound to it and its
3798        // requested declarations are frozen once the registry has accepted
3799        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3800        // duplicate, or for any other reason, leaves the spawn untouched: its
3801        // closing connection is then no registration of the spawn and ends
3802        // none of the spawn's routes.
3803        let hello_authority = match (&channel_spawn, &prefix_binding) {
3804            (Some(spawn), _) => Some(spawn.authority.clone()),
3805            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3806                self.supervisor
3807                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3808            }),
3809            (None, Some(_)) => None,
3810        }
3811        .map(|record| HelloAuthority {
3812            record,
3813            requested: hello
3814                .manifest
3815                .provider_declarations
3816                .clone()
3817                .unwrap_or_default(),
3818            froze: Default::default(),
3819        });
3820        #[cfg(test)]
3821        if prefix_binding.is_some() {
3822            self.claims.pause_prefix_hello_for_test(8);
3823        }
3824        if swap_candidate {
3825            let module_id = hello.manifest.module_id.clone();
3826            let mut differing_declarations = Default::default();
3827            let reply = self.register_swap_candidate(
3828                connection_id,
3829                sink,
3830                &frame,
3831                hello.manifest,
3832                negotiated_ver,
3833                control_ops,
3834                hello_ack,
3835                hello_authority.as_ref(),
3836                &mut differing_declarations,
3837                #[cfg(windows)]
3838                hello.launch_nonce.as_deref(),
3839            )?;
3840            if let Some(spawn) = &channel_spawn {
3841                if self
3842                    .registry
3843                    .get_module_by_connection(connection_id)
3844                    .ok()
3845                    .flatten()
3846                    .is_some()
3847                {
3848                    if let Some(sink) = primary_sink {
3849                        spawn.bind_primary_sink(sink);
3850                    }
3851                    spawn.hello_accepted();
3852                }
3853            } else if self
3854                .registry
3855                .get_module_by_connection(connection_id)
3856                .ok()
3857                .flatten()
3858                .is_some()
3859            {
3860                self.supervisor
3861                    .retire_unused_registration_channel(&module_id, true);
3862            }
3863            if self
3864                .registry
3865                .get_module_by_connection(connection_id)
3866                .ok()
3867                .flatten()
3868                .is_some()
3869            {
3870                self.file_development_widening(
3871                    hello_authority.map(|authority| authority.record),
3872                    differing_declarations,
3873                );
3874            }
3875            return Ok(reply);
3876        }
3877        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3878        // is refused, but `catalog.list` does not show the module and the
3879        // catalog generation does not move until it is published below, once
3880        // its forwarding endpoint exists. Listing it now would advertise a
3881        // module that `route.open` still refuses for having no forwarding
3882        // connection.
3883        let registration = match self
3884            .registry
3885            .register_unpublished_verified_with_control_ops(
3886                hello.manifest,
3887                negotiated_ver,
3888                connection_id,
3889                control_ops,
3890                verification.nonce_verified,
3891            ) {
3892            Ok(registration) => registration,
3893            Err(RegistryError::DuplicateModuleId { module_id }) => {
3894                return Ok(vec![control_error_frame(
3895                    &frame,
3896                    "duplicate_module_id",
3897                    format!(
3898                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3899                    ),
3900                )?])
3901            }
3902            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3903                return Ok(vec![control_error_frame(
3904                    &frame,
3905                    "invalid_module_id",
3906                    err.to_string(),
3907                )?])
3908            }
3909            Err(err) => {
3910                return Ok(vec![control_error_frame(
3911                    &frame,
3912                    "registry_error",
3913                    err.to_string(),
3914                )?])
3915            }
3916        };
3917        let differing_declarations =
3918            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3919                Ok(differing) => differing,
3920                Err(err) => {
3921                    if matches!(
3922                        self.rollback_unpublished_hello(connection_id),
3923                        Ok(r) if !r.is_empty()
3924                    ) {
3925                        crate::supervise::notify_registration_release();
3926                    }
3927                    return Err(RouterError::Forwarding(err));
3928                }
3929            };
3930        #[cfg(test)]
3931        self.hold_between_registry_and_forwarding();
3932
3933        let mut reply = Vec::new();
3934        // Registry readers must wait from before the ACK can be read until
3935        // publication. Nest forwarding inside the registry lock, never reverse.
3936        let publication = self
3937            .registry
3938            .publish_registration_after(connection_id, || {
3939                if let Some(sink) = sink {
3940                    // The forwarding table's module store is also the daemon-to-module
3941                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3942                    // manifest has no routable provider role. Non-routable modules still
3943                    // cannot receive route.bind in production: `handle_route_open` checks
3944                    // the registry manifest with `target_has_required_role` before the
3945                    // only production call to `begin_route_bind_relay_for` below that
3946                    // route.open path. The remaining direct relay callers are unit tests
3947                    // and benchmark harnesses that construct forwarding state explicitly.
3948                    //
3949                    // The HELLO_ACK is queued by the forwarding table itself, before the
3950                    // endpoint becomes visible, and is NOT returned as a reply. A module
3951                    // reads HELLO_ACK first and exits on anything else; a reply is only
3952                    // written after this handler returns, by which time a route.open on
3953                    // another connection could already have queued a route.bind request
3954                    // for this module ahead of it.
3955                    let concurrency = manifest_concurrency(&registration.manifest);
3956                    self.forwarding.register_module_connection_acked(
3957                        connection_id,
3958                        registration.manifest.module_id.clone(),
3959                        negotiated_ver,
3960                        concurrency,
3961                        sink,
3962                        crate::forwarding::ModuleHelloAck {
3963                            frame: hello_ack,
3964                            verified_prefix_owner: verification.prefix_owner,
3965                        },
3966                    )?;
3967                } else {
3968                    // No sink means no forwarding endpoint, so nothing can be routed
3969                    // ahead of the ack; it goes out as the reply.
3970                    reply.push(hello_ack);
3971                }
3972                #[cfg(test)]
3973                self.hold_between_ack_and_publication();
3974                Ok(())
3975            })
3976            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3977        let published = match publication {
3978            Ok(published) => published,
3979            Err(err) => {
3980                // The registry lock has been released, so rollback can take it
3981                // again. No forwarding endpoint or route was published. Keep
3982                // forwarding's weak connection-to-spawn association until the
3983                // connection's read loop ends and removes its remaining routes.
3984                // Removing this unpublished entry does not advance the catalog
3985                // generation.
3986                if matches!(
3987                    self.rollback_unpublished_hello(connection_id),
3988                    Ok(r) if !r.is_empty()
3989                ) {
3990                    crate::supervise::notify_registration_release();
3991                }
3992                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3993                return Ok(vec![control_error_frame(
3994                    &frame,
3995                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
3996                        "invalid_hello"
3997                    } else {
3998                        forwarding_error_code(&err)
3999                    },
4000                    err.to_string(),
4001                )?]);
4002            }
4003        };
4004        if !published {
4005            debug!(
4006                module_id = %registration.manifest.module_id,
4007                connection_id = connection_id.get(),
4008                "registration was removed before it could be published"
4009            );
4010            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
4011            return Ok(reply);
4012        }
4013
4014        drop(_prefix_ownership);
4015        drop(_prefix_live);
4016
4017        // Exposure over assumption: Concurrency's serde default is pinned to the
4018        // pre-field behavior (ModuleManaged), so a management surface that is
4019        // genuinely Serial and just never declared it inherits concurrent
4020        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
4021        // turns "no module has been bitten yet" into the checkable claim "no
4022        // module is exposed" -- one read of the boot log instead of a fleet
4023        // audit. Detected from the raw HELLO bytes because the serde default
4024        // deliberately erases the absent/declared distinction from the type.
4025        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
4026            info!(
4027                module_id = %registration.manifest.module_id,
4028                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
4029            );
4030        }
4031        if registration.manifest.registration_channel == Some(false)
4032            && self
4033                .supervisor
4034                .module_is_gated(&registration.manifest.module_id)
4035            && self
4036                .config_runtime
4037                .as_ref()
4038                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
4039                .as_deref()
4040                == Some("declared")
4041        {
4042            warn!(module_id = %registration.manifest.module_id,
4043                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
4044        }
4045
4046        self.apply_registration_capabilities(&registration);
4047
4048        self.supervisor
4049            .record_activity_registration(&registration.manifest.module_id);
4050
4051        info!(
4052            module_id = %registration.manifest.module_id,
4053            module_version = %registration.manifest.module_version,
4054            negotiated_ver,
4055            routable_provider = manifest_provides_routable_role(&registration.manifest),
4056            connection_id = connection_id.get(),
4057            "module registered"
4058        );
4059
4060        if let Some(spawn) = &channel_spawn {
4061            if let Some(sink) = primary_sink {
4062                spawn.bind_primary_sink(sink);
4063            }
4064            spawn.hello_accepted();
4065        } else if !prefix_submodule {
4066            self.supervisor
4067                .retire_unused_registration_channel(&registration.manifest.module_id, false);
4068        }
4069        self.file_development_widening(
4070            hello_authority.map(|authority| authority.record),
4071            differing_declarations,
4072        );
4073        #[cfg(windows)]
4074        if let Some(nonce) = hello.launch_nonce.as_deref() {
4075            self.supervisor
4076                .program_hello_accepted(&registration.manifest.module_id, nonce);
4077        }
4078
4079        #[cfg(test)]
4080        if let Some(hold) = &self.hello_inside_publication_hold {
4081            hold.wait();
4082            hold.wait();
4083        }
4084
4085        Ok(reply)
4086    }
4087
4088    /// Register a HELLO the swap gate admitted into the candidate slot of the
4089    /// registry and of forwarding, where it is reachable over its own
4090    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
4091    /// nothing routes to it until the supervisor cuts over.
4092    ///
4093    /// Registry first (unpublished), then forwarding, then publication, the
4094    /// same order as an ordinary HELLO; a forwarding failure removes the
4095    /// registry entry again. The swap supervisor treats a published, ready
4096    /// candidate as registered and promotes it, and promotion needs the
4097    /// candidate's forwarding endpoint, so the candidate is published only
4098    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
4099    /// recompute capability verdicts or run the capability deny census
4100    /// (`enforce_capability_denies`): both are about the module in the active
4101    /// slot, which `route.open` can target. A candidate sits in the candidate
4102    /// slot, so it neither provides capabilities to other modules nor can be
4103    /// routed to until promotion moves it into the active slot.
4104    #[allow(clippy::too_many_arguments)]
4105    fn register_swap_candidate(
4106        &self,
4107        connection_id: ConnectionId,
4108        sink: Option<crate::FrameSink>,
4109        frame: &Frame,
4110        manifest: ModuleManifest,
4111        negotiated_ver: u8,
4112        control_ops: Vec<String>,
4113        hello_ack: Frame,
4114        hello_authority: Option<&HelloAuthority>,
4115        differing_declarations: &mut ProviderDeclarations,
4116        #[cfg(windows)] launch_nonce: Option<&str>,
4117    ) -> Result<Vec<Frame>, RouterError> {
4118        let module_id = manifest.module_id.clone();
4119        // Closing a swap and publishing its candidate must be ordered. The
4120        // spawn role proves which slot is intended, not that the slot is open.
4121        self.supervisor
4122            .with_swap_candidate_admission(&module_id, || {
4123                let reply = self.publish_swap_candidate(
4124                    connection_id,
4125                    sink,
4126                    frame,
4127                    manifest,
4128                    negotiated_ver,
4129                    control_ops,
4130                    hello_ack,
4131                    hello_authority,
4132                    differing_declarations,
4133                    #[cfg(windows)]
4134                    launch_nonce,
4135                );
4136                let admitted = self
4137                    .registry
4138                    .get_candidate(&module_id)
4139                    .ok()
4140                    .flatten()
4141                    .is_some_and(|candidate| candidate.connection_id == connection_id);
4142                (reply, admitted)
4143            })
4144            .unwrap_or_else(|| {
4145                Ok(vec![control_error_frame(
4146                    frame,
4147                    "swap_token_invalid",
4148                    "swap ended before candidate HELLO publication",
4149                )?])
4150            })
4151    }
4152
4153    #[allow(clippy::too_many_arguments)]
4154    fn publish_swap_candidate(
4155        &self,
4156        connection_id: ConnectionId,
4157        sink: Option<crate::FrameSink>,
4158        frame: &Frame,
4159        manifest: ModuleManifest,
4160        negotiated_ver: u8,
4161        control_ops: Vec<String>,
4162        hello_ack: Frame,
4163        hello_authority: Option<&HelloAuthority>,
4164        differing_declarations: &mut ProviderDeclarations,
4165        #[cfg(windows)] launch_nonce: Option<&str>,
4166    ) -> Result<Vec<Frame>, RouterError> {
4167        let module_id = manifest.module_id.clone();
4168        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4169            manifest,
4170            negotiated_ver,
4171            connection_id,
4172            control_ops,
4173        ) {
4174            Ok(registration) => registration,
4175            Err(RegistryError::DuplicateModuleId { module_id }) => {
4176                return Ok(vec![control_error_frame(
4177                    frame,
4178                    "duplicate_module_id",
4179                    format!(
4180                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4181                    ),
4182                )?])
4183            }
4184            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4185                return Ok(vec![control_error_frame(
4186                    frame,
4187                    "invalid_module_id",
4188                    err.to_string(),
4189                )?])
4190            }
4191            Err(err) => {
4192                return Ok(vec![control_error_frame(
4193                    frame,
4194                    "registry_error",
4195                    err.to_string(),
4196                )?])
4197            }
4198        };
4199        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4200            Ok(differing) => differing,
4201            Err(err) => {
4202                if matches!(
4203                    self.rollback_unpublished_hello(connection_id),
4204                    Ok(r) if !r.is_empty()
4205                ) {
4206                    crate::supervise::notify_registration_release();
4207                }
4208                return Err(RouterError::Forwarding(err));
4209            }
4210        };
4211        #[cfg(test)]
4212        self.hold_between_registry_and_forwarding();
4213        let mut reply = Vec::new();
4214        let publication = self
4215            .registry
4216            .publish_registration_after(connection_id, || {
4217                if let Some(sink) = sink {
4218                    // Same ordering as an ordinary HELLO: queue the ACK before
4219                    // inserting the endpoint, and keep registry readers excluded
4220                    // until the candidate is published.
4221                    let concurrency = manifest_concurrency(&registration.manifest);
4222                    self.forwarding.register_candidate_module_connection_acked(
4223                        connection_id,
4224                        module_id.clone(),
4225                        negotiated_ver,
4226                        concurrency,
4227                        sink,
4228                        hello_ack,
4229                    )?;
4230                } else {
4231                    reply.push(hello_ack);
4232                }
4233                #[cfg(test)]
4234                self.hold_between_ack_and_publication();
4235                Ok(())
4236            })
4237            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4238        let published = match publication {
4239            Ok(published) => published,
4240            Err(err) => {
4241                if matches!(
4242                    self.rollback_unpublished_hello(connection_id),
4243                    Ok(r) if !r.is_empty()
4244                ) {
4245                    crate::supervise::notify_registration_release();
4246                }
4247                self.refuse_hello_authority(connection_id, hello_authority);
4248                return Ok(vec![control_error_frame(
4249                    frame,
4250                    forwarding_error_code(&err),
4251                    err.to_string(),
4252                )?]);
4253            }
4254        };
4255        if !published {
4256            debug!(
4257                module_id = %module_id,
4258                connection_id = connection_id.get(),
4259                "swap candidate registration was removed before it could be published"
4260            );
4261            self.refuse_hello_authority(connection_id, hello_authority);
4262            return Ok(reply);
4263        }
4264        info!(
4265            module_id = %module_id,
4266            module_version = %registration.manifest.module_version,
4267            negotiated_ver,
4268            ready = registration.ready,
4269            connection_id = connection_id.get(),
4270            "swap candidate registered; not routable until cutover"
4271        );
4272        #[cfg(windows)]
4273        if let Some(nonce) = launch_nonce {
4274            self.supervisor.program_hello_accepted(&module_id, nonce);
4275        }
4276        Ok(reply)
4277    }
4278
4279    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4280    /// spawn's requested provider declarations. Runs only once the registry
4281    /// has accepted the HELLO, before its endpoint is published, so a route
4282    /// reserved on the endpoint always finds the spawn. Returns the requested
4283    /// entries that differ from the saved approvals, for a widening request.
4284    fn admit_hello_authority(
4285        &self,
4286        connection: ConnectionId,
4287        authority: Option<&HelloAuthority>,
4288    ) -> Result<ProviderDeclarations, ForwardingError> {
4289        let Some(authority) = authority else {
4290            return Ok(ProviderDeclarations::new());
4291        };
4292        let froze = authority
4293            .record
4294            .freeze_declarations(authority.requested.clone());
4295        authority
4296            .froze
4297            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4298        self.forwarding
4299            .bind_target_authority(connection, authority.record.clone())
4300            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4301        Ok(froze.unwrap_or_default())
4302    }
4303
4304    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4305    /// registry accepted it, so the refused connection is no registration of
4306    /// the spawn and the spawn's declarations are left for the HELLO that
4307    /// does register it to freeze.
4308    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4309        let Some(authority) = authority else {
4310            return;
4311        };
4312        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4313            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4314        }
4315        if authority
4316            .froze
4317            .swap(false, std::sync::atomic::Ordering::Relaxed)
4318        {
4319            authority.record.unfreeze_refused_declarations();
4320        }
4321    }
4322
4323    fn build_hello_ack(
4324        &self,
4325        frame: &Frame,
4326        negotiated_ver: u8,
4327        module_id: &str,
4328    ) -> Result<Frame, RouterError> {
4329        let ack = ModuleHelloAckBody {
4330            negotiated_ver,
4331            subc_ops: module_subc_ops(),
4332            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4333            storage: self
4334                .storage_config
4335                .as_ref()
4336                .map(|cfg| cfg.descriptor_for(module_id)),
4337            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4338        };
4339        let body = serde_json::to_vec(&ack).map_err(|err| {
4340            RouterError::backend(
4341                0,
4342                frame.header.corr,
4343                format!("failed to encode HELLO_ACK: {err}"),
4344            )
4345        })?;
4346
4347        Frame::build_with_version(
4348            negotiated_ver,
4349            FrameType::HelloAck,
4350            control_flags(),
4351            0,
4352            0,
4353            frame.header.corr,
4354            body,
4355        )
4356        .map_err(RouterError::FrameBuild)
4357    }
4358
4359    async fn handle_client_control_request(
4360        &self,
4361        ctx: &RouteCtx,
4362        frame: Frame,
4363        request: ClientControlRequest,
4364        route_open_timings: &mut Option<RouteOpenTimings>,
4365    ) -> Result<Vec<Frame>, RouterError> {
4366        if let Some(owner) = &self.config_runtime {
4367            let module = match &request {
4368                ClientControlRequest::SupervisorRestart { module_id, .. }
4369                | ClientControlRequest::SupervisorReload { module_id }
4370                | ClientControlRequest::SupervisorSwap { module_id, .. }
4371                | ClientControlRequest::SupervisorSetEnabled {
4372                    module_id,
4373                    enabled: true,
4374                } => Some(module_id.as_str()),
4375                _ => None,
4376            };
4377            let rescan = matches!(
4378                &request,
4379                ClientControlRequest::SupervisorRescan { preview: false }
4380                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4381            );
4382            let held = if module.is_some() || rescan {
4383                let module = module.map(str::to_owned);
4384                owner
4385                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4386                    .await
4387            } else {
4388                Ok(())
4389            };
4390            if let Err(error) = held {
4391                if error.code != "config_delivery_deferred" {
4392                    let code = if error.code == "store_tampered" {
4393                        "store_tampered"
4394                    } else {
4395                        "config_gated"
4396                    };
4397                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4398                }
4399            }
4400        }
4401        if let Some(operation) = privileged_operation(&request) {
4402            let caller = self.resolve_caller(ctx.connection_id).await;
4403            let op = client_control_request_op(&request);
4404            let text = prompt_text(operation, &caller);
4405            match self.privileged_operator_prompt {
4406                PrivilegedOperatorPrompt::Log => {
4407                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4408                        target = ?operation, caller = %caller.description(), summary = %text,
4409                        "privileged request would prompt the operator");
4410                }
4411                PrivilegedOperatorPrompt::Enforce => {
4412                    let key =
4413                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4414                    let shortcut =
4415                        self.operator_shortcut_stamp(ctx.connection_id)
4416                            .await
4417                            .map(|stamp| {
4418                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
4419                            });
4420                    let outcome = self
4421                        .forwarding
4422                        .operator_confirms()
4423                        .approve_privileged_with_shortcut(
4424                            ctx,
4425                            &frame,
4426                            op,
4427                            text,
4428                            caller.description(),
4429                            key,
4430                            shortcut,
4431                        )
4432                        .await;
4433                    if outcome.code != "confirmed" {
4434                        return Ok(vec![outcome.frame(&frame)]);
4435                    }
4436                }
4437            }
4438        }
4439        match request {
4440            ClientControlRequest::DaemonShutdownIntent { intent } => {
4441                if intent.as_str() != Some("restart") {
4442                    return Ok(vec![control_error_frame(
4443                        &frame,
4444                        "invalid_params",
4445                        "intent must be 'restart'",
4446                    )?]);
4447                }
4448                // A stamped daemon boots a newer approved generation only from a
4449                // durable restart intent, written here before the daemon exits.
4450                // Failing to write it never blocks the restart: the next start
4451                // then boots the last active generation and the newer one waits.
4452                if let Some(owner) = &self.config_runtime {
4453                    match owner
4454                        .on_blocking(|owner| owner.assign_daemon_restart())
4455                        .await
4456                    {
4457                        Ok(Some(generation)) => {
4458                            info!(
4459                                generation,
4460                                "daemon restart will warm up approved generation"
4461                            )
4462                        }
4463                        Ok(None) => {}
4464                        Err(error) => warn!(
4465                            %error,
4466                            "daemon restart intent not recorded; the next start boots the last active generation"
4467                        ),
4468                    }
4469                }
4470                let response = ClientControlResponse::DaemonShutdownIntent {
4471                    intent: "restart".to_owned(),
4472                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4473                };
4474                Ok(vec![control_response_body_frame(
4475                    &frame,
4476                    &response,
4477                    "ClientControlResponse::DaemonShutdownIntent",
4478                )?])
4479            }
4480            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4481            ClientControlRequest::CatalogList { module_id } => {
4482                self.handle_catalog_list(frame, module_id)
4483            }
4484            ClientControlRequest::RouteOpen {
4485                target,
4486                identity,
4487                consumer_identity,
4488                consumer_capabilities,
4489                role_versions,
4490                busy_refusals,
4491                admission_facts,
4492                scope,
4493                ..
4494            } => {
4495                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4496                    &frame.body,
4497                ) {
4498                    Ok(extensions) => extensions,
4499                    Err(err) => {
4500                        return Ok(vec![control_error_frame(
4501                            &frame,
4502                            "invalid_control_body",
4503                            format!("malformed route.open extensions: {err}"),
4504                        )?]);
4505                    }
4506                };
4507                self.handle_route_open(
4508                    ctx,
4509                    frame,
4510                    RouteOpenRequest {
4511                        target,
4512                        identity,
4513                        consumer_identity,
4514                        consumer_capabilities,
4515                        role_versions,
4516                        busy_refusals,
4517                        admission_facts,
4518                        scope,
4519                        accepts_close_reasons: extensions.accepts_close_reasons,
4520                    },
4521                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4522                )
4523                .await
4524            }
4525            ClientControlRequest::RoutePoll {
4526                route_channel,
4527                route_epoch,
4528                kind,
4529            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4530            ClientControlRequest::SupervisorList {} => {
4531                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4532                    self.agent_declarations.refuse(
4533                        self,
4534                        ctx,
4535                        control_error_frame(
4536                            &frame,
4537                            "busy",
4538                            "supervisor list work is at capacity; retry",
4539                        )?,
4540                    );
4541                    return Ok(Vec::new());
4542                };
4543                // Filesystem-backed diagnostics must not hold up this connection's reader.
4544                let handler = self.clone();
4545                let sink = ctx.egress.clone();
4546                tokio::spawn(
4547                    async move {
4548                        let _permit = permit;
4549                        let result = handler.handle_supervisor_list(frame.clone()).await;
4550                        let replies = match result {
4551                            Ok(replies) => replies,
4552                            Err(error) => {
4553                                control_error_frame(&frame, "backend_error", error.to_string())
4554                                    .into_iter()
4555                                    .collect()
4556                            }
4557                        };
4558                        for reply in replies {
4559                            if !matches!(
4560                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4561                                    .await,
4562                                Ok(Ok(()))
4563                            ) {
4564                                break;
4565                            }
4566                        }
4567                    }
4568                    .with_current_subscriber(),
4569                );
4570                Ok(Vec::new())
4571            }
4572            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4573                self.handle_supervisor_spawn_snapshot(frame)
4574            }
4575            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4576                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4577            }
4578            ClientControlRequest::SupervisorRestart {
4579                module_id,
4580                drain_timeout_ms,
4581            } => {
4582                self.log_supervisor_request_received(
4583                    ctx,
4584                    frame.header.corr,
4585                    ops::SUPERVISOR_RESTART,
4586                    Some(&module_id),
4587                    None,
4588                )?;
4589                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4590                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4591                    .await
4592            }
4593            ClientControlRequest::SupervisorSwap {
4594                module_id,
4595                ready_timeout_ms,
4596            } => {
4597                self.log_supervisor_request_received(
4598                    ctx,
4599                    frame.header.corr,
4600                    ops::SUPERVISOR_SWAP,
4601                    Some(&module_id),
4602                    None,
4603                )?;
4604                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4605                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4606                    .await
4607            }
4608            ClientControlRequest::SupervisorReload { module_id } => {
4609                self.log_supervisor_request_received(
4610                    ctx,
4611                    frame.header.corr,
4612                    ops::SUPERVISOR_RELOAD,
4613                    Some(&module_id),
4614                    None,
4615                )?;
4616                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4617                self.handle_supervisor_reload(frame, module_id, requester)
4618                    .await
4619            }
4620            ClientControlRequest::SupervisorRescan { preview } => {
4621                if !preview {
4622                    self.log_supervisor_request_received(
4623                        ctx,
4624                        frame.header.corr,
4625                        ops::SUPERVISOR_RESCAN,
4626                        None,
4627                        None,
4628                    )?;
4629                }
4630                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4631                let operation = self.handle_supervisor_rescan(
4632                    frame,
4633                    if preview {
4634                        RescanMode::Preview
4635                    } else {
4636                        RescanMode::Execute
4637                    },
4638                    requester,
4639                );
4640                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4641                    .await
4642            }
4643            ClientControlRequest::SupervisorRescanChecked {
4644                preview,
4645                candidate,
4646                expect,
4647            } => {
4648                self.observe_control_wait(
4649                    ctx,
4650                    None,
4651                    ops::SUPERVISOR_RESCAN,
4652                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4653                )
4654                .await
4655            }
4656            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4657                self.log_supervisor_request_received(
4658                    ctx,
4659                    frame.header.corr,
4660                    ops::SUPERVISOR_RELEASE_RESERVED,
4661                    Some(&module_id),
4662                    None,
4663                )?;
4664                self.handle_supervisor_release_reserved(frame, module_id)
4665                    .await
4666            }
4667            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4668                self.log_supervisor_request_received(
4669                    ctx,
4670                    frame.header.corr,
4671                    ops::SUPERVISOR_SET_ENABLED,
4672                    Some(&module_id),
4673                    Some(enabled),
4674                )?;
4675                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4676                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4677                    .await
4678            }
4679            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4680                self.handle_supervisor_health_probe(ctx, frame, module_id)
4681                    .await
4682            }
4683            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4684            ClientControlRequest::SupervisorRoutes { module_id } => {
4685                self.handle_supervisor_routes(frame, module_id)
4686            }
4687            ClientControlRequest::SupervisorProvenance { module_id } => {
4688                self.handle_supervisor_provenance(ctx, frame, module_id)
4689                    .await
4690            }
4691            ClientControlRequest::SupervisorStderrTail {
4692                module_id,
4693                max_lines,
4694                max_bytes,
4695            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4696            ClientControlRequest::SupervisorTerminals { module_id } => {
4697                self.handle_supervisor_terminals(ctx, frame, module_id)
4698                    .await
4699            }
4700        }
4701    }
4702
4703    fn log_supervisor_request_received(
4704        &self,
4705        ctx: &RouteCtx,
4706        corr: u64,
4707        op: &'static str,
4708        module_id: Option<&str>,
4709        enabled: Option<bool>,
4710    ) -> Result<(), RouterError> {
4711        let caller = self.supervisor_requester(ctx, corr)?;
4712        let caller = principal_label(&caller);
4713        // `Option` fields are recorded only when present, so a request with no
4714        // module id (rescan) or no enabled flag simply omits that field.
4715        info!(
4716            target: "control",
4717            op,
4718            module_id,
4719            enabled,
4720            connection_id = ctx.connection_id.get(),
4721            caller = %caller,
4722            "supervisor request received"
4723        );
4724        Ok(())
4725    }
4726
4727    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4728        Ok(self
4729            .registry
4730            .get_module_by_connection(ctx.connection_id)
4731            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4732            .map(|registration| Principal::Reserved {
4733                module_id: registration.manifest.module_id,
4734            })
4735            .unwrap_or(Principal::Direct))
4736    }
4737
4738    fn handle_module_control_request(
4739        &self,
4740        connection_id: ConnectionId,
4741        frame: Frame,
4742        request: ModuleControlRequestFromModule,
4743    ) -> Result<Vec<Frame>, RouterError> {
4744        match request {
4745            ModuleControlRequestFromModule::RouteAuthorize {
4746                principal,
4747                scope,
4748                target,
4749                expected,
4750            } => self.handle_route_authorize(
4751                connection_id,
4752                frame,
4753                principal,
4754                scope,
4755                target,
4756                expected,
4757            ),
4758            ModuleControlRequestFromModule::CatalogUpdate {
4759                provides,
4760                capabilities,
4761                ready,
4762            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4763            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4764                self.handle_catalog_update_role_declarations(
4765                    connection_id,
4766                    frame,
4767                    role_declarations,
4768                )
4769            }
4770            ModuleControlRequestFromModule::LiveRoots {} => {
4771                let registered = self
4772                    .registry
4773                    .get_module_by_connection(connection_id)
4774                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4775                let Some(registration) = registered else {
4776                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4777                };
4778                let response = self
4779                    .forwarding
4780                    .live_roots(&registration.manifest.module_id)
4781                    .map_err(RouterError::Forwarding)?;
4782                Ok(vec![control_response_body_frame(
4783                    &frame,
4784                    &response,
4785                    "ModuleControlResponseToModule::LiveRoots",
4786                )?])
4787            }
4788            ModuleControlRequestFromModule::AgentCommands {
4789                started,
4790                finished,
4791                known,
4792            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4793            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4794                self.handle_scope_sync(connection_id, frame, generation, scopes)
4795            }
4796            ModuleControlRequestFromModule::ScopeApply {
4797                generation,
4798                upsert,
4799                end,
4800            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4801            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4802                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4803            }
4804            _ => Ok(vec![control_error_frame(
4805                &frame,
4806                "unsupported_control_frame",
4807                "unsupported module control operation",
4808            )?]),
4809        }
4810    }
4811
4812    fn handle_scope_served_by(
4813        &self,
4814        connection_id: ConnectionId,
4815        frame: Frame,
4816    ) -> Result<Vec<Frame>, RouterError> {
4817        let registered = self
4818            .registry
4819            .get_module_by_connection(connection_id)
4820            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4821        let Some(registered) = registered else {
4822            return Ok(vec![control_error_frame(
4823                &frame,
4824                "not_registered",
4825                "scope.served_by requires an active module registration owned by this connection",
4826            )?]);
4827        };
4828        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4829        {
4830            Ok(request) => request,
4831            Err(err) => {
4832                return Ok(vec![control_error_frame(
4833                    &frame,
4834                    "invalid_control_body",
4835                    format!("malformed scope.served_by body: {err}"),
4836                )?])
4837            }
4838        };
4839        let answer = self
4840            .scopes
4841            .read()
4842            .unwrap_or_else(|poisoned| poisoned.into_inner())
4843            .served_by(
4844                &registered.manifest.module_id,
4845                &request.scope_ref,
4846                request.scope_epoch,
4847                &request.module_id,
4848            );
4849        let reply = subc_control::ScopeServedByReply::new(
4850            answer,
4851            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4852        );
4853        Ok(vec![control_response_body_frame(
4854            &frame,
4855            &reply,
4856            "ScopeServedByReply",
4857        )?])
4858    }
4859
4860    /// Explicit test-only phone policy; daemon configuration cannot select it.
4861    #[cfg(any(test, feature = "test-support"))]
4862    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
4863        self.operator_app_policy.phone_enabled = enabled;
4864        self
4865    }
4866
4867    /// Resolve folders before taking the scope-table lock: a slow filesystem
4868    /// must not hold up admissions for unrelated scoped routes.
4869    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
4870        let mut scopes = ScopeRecords::from(scopes);
4871        for (index, record) in scopes.records.iter_mut().enumerate() {
4872            if let Some(refusal) = Self::canonicalize_workdir(record) {
4873                scopes.refusals.insert(index, refusal);
4874            }
4875        }
4876        scopes
4877    }
4878
4879    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
4880        let workdir = record.workdir.as_mut()?;
4881        let path = std::path::Path::new(workdir);
4882        if !path.is_absolute() {
4883            return Some((
4884                error_codes::INVALID_WORKDIR,
4885                "workdir must be absolute".to_string(),
4886            ));
4887        }
4888        match ProjectRootId::from_path_allowing_missing(path) {
4889            Ok(root) => match root.as_path().to_str() {
4890                Some(canonical) => {
4891                    *workdir = canonical.to_string();
4892                    None
4893                }
4894                None => Some((
4895                    error_codes::INVALID_WORKDIR,
4896                    "canonical workdir is not UTF-8".to_string(),
4897                )),
4898            },
4899            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
4900        }
4901    }
4902
4903    /// `scope.sync`: the owner is the module registered on this connection.
4904    /// A connection with no registration (every client connection, `direct`
4905    /// included) is refused `not_registered` before the table is consulted.
4906    fn handle_scope_sync(
4907        &self,
4908        connection_id: ConnectionId,
4909        frame: Frame,
4910        generation: u64,
4911        scopes: Vec<ScopeRecord>,
4912    ) -> Result<Vec<Frame>, RouterError> {
4913        self.handle_scope_change(connection_id, frame, generation, scopes, None)
4914    }
4915
4916    fn handle_scope_change(
4917        &self,
4918        connection_id: ConnectionId,
4919        frame: Frame,
4920        generation: u64,
4921        scopes: Vec<ScopeRecord>,
4922        end: Option<Vec<ScopeEnd>>,
4923    ) -> Result<Vec<Frame>, RouterError> {
4924        let is_apply = end.is_some();
4925        let Some(registration) = self
4926            .registry
4927            .get_module_by_connection(connection_id)
4928            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4929        else {
4930            return Ok(vec![control_error_frame(
4931                &frame,
4932                "not_registered",
4933                "scope.sync and scope.apply require an active module registration owned by this connection",
4934            )?]);
4935        };
4936        let owner = registration.manifest.module_id;
4937        let scopes = Self::prepare_scope_records(scopes);
4938        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
4939        let is_current_launch = |connection: ConnectionId| {
4940            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
4941        };
4942        // Lock order is the scope table, then the forwarding table: the new
4943        // tags are published, and the routes the change closes are selected,
4944        // while the scope table is still write-locked, so no admission can read
4945        // a record whose tag is not yet published.
4946        let mut table = self
4947            .scopes
4948            .write()
4949            .unwrap_or_else(|poisoned| poisoned.into_inner());
4950        let outcome = match end {
4951            Some(end) => table.apply(
4952                &owner,
4953                connection_id,
4954                is_current_launch,
4955                generation,
4956                scopes,
4957                end,
4958            ),
4959            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
4960        };
4961        let drained = match &outcome {
4962            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
4963            Err(_) => Vec::new(),
4964        };
4965        let has_deadlines = outcome.is_ok() && table.has_deadlines();
4966        drop(table);
4967        if has_deadlines {
4968            self.scope_deadline_added.notify_one();
4969        }
4970        match outcome {
4971            Ok(applied) => {
4972                let counts = ScopeOutcomeCounts::of(&applied.results);
4973                info!(
4974                    owner = %owner,
4975                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4976                    generation,
4977                    records = applied.results.len(),
4978                    created = counts.created,
4979                    replaced = counts.replaced,
4980                    updated = counts.updated,
4981                    unchanged = counts.unchanged,
4982                    refused = counts.refused,
4983                    ended = applied.ended.len(),
4984                    tag_changes = applied.tag_changes.len(),
4985                    routes_closed = drained.len(),
4986                    "scope change accepted"
4987                );
4988                // An accepted scope change can still refuse individual records, and the
4989                // owner is the only party that sees the reply. Name them here so
4990                // an operator can tell a refused session from a missing one
4991                // without the owner's logs. Capped so a call that refuses
4992                // thousands cannot flood the log; the count above is complete.
4993                for refused in applied
4994                    .results
4995                    .iter()
4996                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
4997                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
4998                {
4999                    warn!(
5000                        owner = %owner,
5001                        generation,
5002                        scope_ref = %refused.scope_ref,
5003                        scope_epoch = refused.scope_epoch,
5004                        code = refused.code.as_deref().unwrap_or(""),
5005                        "scope record refused"
5006                    );
5007                }
5008                self.close_scope_drained_routes(drained);
5009                let response = if is_apply {
5010                    ModuleControlResponseToModule::ScopeApply {
5011                        generation,
5012                        results: applied.results,
5013                        end_results: applied.end_results,
5014                        ended: applied.ended,
5015                    }
5016                } else {
5017                    ModuleControlResponseToModule::ScopeSync {
5018                        generation,
5019                        results: applied.results,
5020                        ended: applied.ended,
5021                    }
5022                };
5023                Ok(vec![control_response_body_frame(
5024                    &frame,
5025                    &response,
5026                    "scope change response",
5027                )?])
5028            }
5029            Err(refusal) => {
5030                info!(
5031                    owner = %owner,
5032                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
5033                    generation,
5034                    code = refusal.code,
5035                    "scope change refused"
5036                );
5037                Ok(vec![control_error_frame(
5038                    &frame,
5039                    refusal.code,
5040                    refusal.message,
5041                )?])
5042            }
5043        }
5044    }
5045
5046    /// Notify both endpoints of routes drained by a scope change.
5047    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
5048        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
5049    }
5050
5051    /// Re-authorize a stored source on a principal the module supplies.
5052    ///
5053    /// That principal carries no spawn or authority epoch, so this reply never
5054    /// conveys a caller attestation or a first-party mark, and a provider must
5055    /// not apply automatic grants on anything it authorizes.
5056    fn handle_route_authorize(
5057        &self,
5058        connection_id: ConnectionId,
5059        frame: Frame,
5060        principal: Principal,
5061        scope: subc_protocol::scope::RouteAuthorizeScope,
5062        target: String,
5063        expected: subc_protocol::scope::RouteAuthorizeExpected,
5064    ) -> Result<Vec<Frame>, RouterError> {
5065        use crate::scopes::admission::{admit_route, AdmissionMode};
5066        use subc_protocol::scope::{
5067            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
5068        };
5069        let registry = self
5070            .registry
5071            .route_admission_snapshot()
5072            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5073        let owner_configured = match &scope.owner {
5074            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5075            _ => false,
5076        };
5077        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
5078        let answer = {
5079            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
5080            let permitted = registry
5081                .iter()
5082                .find(|r| r.connection_id == connection_id)
5083                .is_some_and(|r| {
5084                    scopes.is_federated_owner(&Principal::Reserved {
5085                        module_id: r.module_id.clone(),
5086                    }) && r.capabilities.as_ref().is_some_and(|caps| {
5087                        caps.provides
5088                            .iter()
5089                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
5090                    })
5091                });
5092            if !permitted {
5093                drop(scopes);
5094                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
5095                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
5096            }
5097            admit_route(
5098                &scopes,
5099                &registry,
5100                &principal,
5101                &target,
5102                Some(&selector),
5103                owner_configured,
5104                AdmissionMode::Authorize(&expected),
5105            )
5106        };
5107        let response = match answer {
5108            Ok(admission) => {
5109                let mut response = RouteAuthorizeResponse::new(
5110                    RouteAuthorizeOutcome::Authorized,
5111                    "route admission authorized",
5112                );
5113                response.content_version = admission.content_version;
5114                response
5115            }
5116            Err(refusal) => refusal.response(),
5117        };
5118        Ok(vec![control_response_body_frame(
5119            &frame,
5120            &response,
5121            "RouteAuthorizeResponse",
5122        )?])
5123    }
5124
5125    /// `scope.describe`: any registered module may read any scope, because a
5126    /// provider must read the scope a route it serves is stamped with.
5127    fn handle_scope_describe(
5128        &self,
5129        connection_id: ConnectionId,
5130        frame: Frame,
5131        owner: Principal,
5132        scope_ref: String,
5133    ) -> Result<Vec<Frame>, RouterError> {
5134        let registered = self
5135            .registry
5136            .get_module_by_connection(connection_id)
5137            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5138        let Some(registered) = registered else {
5139            return Ok(vec![control_error_frame(
5140                &frame,
5141                "not_registered",
5142                "scope.describe requires an active module registration owned by this connection",
5143            )?]);
5144        };
5145        let scopes = self
5146            .scopes
5147            .read()
5148            .unwrap_or_else(|poisoned| poisoned.into_inner());
5149        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5150            return Ok(vec![control_error_frame(
5151                &frame,
5152                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5153                "scope.describe of the federated owner requires scope-federated/v1",
5154            )?]);
5155        }
5156        let mut description = scopes.describe(&owner, &scope_ref);
5157        drop(scopes);
5158        if owner
5159            != (Principal::Reserved {
5160                module_id: registered.manifest.module_id.clone(),
5161            })
5162        {
5163            if let Some(facts) = description
5164                .stamp
5165                .as_mut()
5166                .and_then(|stamp| stamp.attributes.federated.as_mut())
5167            {
5168                facts.stamp_required = false;
5169            }
5170        }
5171        // Describe readers also decode strict ScopeAttributes. Attribution is
5172        // safe to omit unless the requesting module declares it understands it.
5173        if !registered
5174            .manifest
5175            .capabilities
5176            .as_ref()
5177            .is_some_and(|caps| {
5178                caps.provides
5179                    .iter()
5180                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5181            })
5182        {
5183            if let Some(stamp) = description.stamp.as_mut() {
5184                stamp.attributes.on_behalf_of_agent = None;
5185            }
5186        }
5187        if !registered
5188            .manifest
5189            .capabilities
5190            .as_ref()
5191            .is_some_and(|caps| {
5192                caps.provides
5193                    .iter()
5194                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5195            })
5196        {
5197            if let Some(stamp) = description.stamp.as_mut() {
5198                stamp.attributes.flow_version = None;
5199                stamp.attributes.flow_code_hash = None;
5200                stamp.attributes.flow_install_id = None;
5201            }
5202        }
5203        let owner_configured = match &owner {
5204            // Ask whether the owner is configured (`is_configured`), not
5205            // whether it is on the roster (`get(..).is_some()`): a supervised
5206            // module's process can register and describe a scope before the
5207            // supervisor has put it on the roster.
5208            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5209            _ => false,
5210        };
5211        let response = ModuleControlResponseToModule::ScopeDescribe {
5212            status: description.status,
5213            scope_epoch: description.scope_epoch,
5214            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5215            owner_synced: description.owner_synced,
5216            owner_configured,
5217            scope: description.stamp,
5218        };
5219        Ok(vec![control_response_body_frame(
5220            &frame,
5221            &response,
5222            "ModuleControlResponseToModule::ScopeDescribe",
5223        )?])
5224    }
5225
5226    fn handle_catalog_update_role_declarations(
5227        &self,
5228        connection_id: ConnectionId,
5229        frame: Frame,
5230        role_declarations: serde_json::Value,
5231    ) -> Result<Vec<Frame>, RouterError> {
5232        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5233            return Ok(vec![control_error_frame(
5234                &frame,
5235                "invalid_role_declarations",
5236                err.to_string(),
5237            )?]);
5238        }
5239        let declarations = serde_json::from_value(role_declarations)
5240            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5241        if self
5242            .registry
5243            .replace_role_declarations_for_connection(connection_id, declarations)
5244            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5245            .is_none()
5246        {
5247            return Ok(vec![control_error_frame(
5248                &frame,
5249                "not_registered",
5250                "catalog.update_role_declarations requires an active module registration owned by this connection",
5251            )?]);
5252        }
5253        control_response_body_frame(
5254            &frame,
5255            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5256            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5257        )
5258        .map(|frame| vec![frame])
5259    }
5260
5261    fn handle_catalog_update(
5262        &self,
5263        connection_id: ConnectionId,
5264        frame: Frame,
5265        provides: Vec<ProviderRole>,
5266        capabilities: Option<CapabilityDeclarations>,
5267        ready: Option<bool>,
5268    ) -> Result<Vec<Frame>, RouterError> {
5269        self.refresh_capability_requirements();
5270        let Some(registration) = self
5271            .registry
5272            .get_module_by_connection(connection_id)
5273            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5274        else {
5275            return Ok(vec![control_error_frame(
5276                &frame,
5277                "not_registered",
5278                "catalog.update requires an active module registration owned by this connection",
5279            )?]);
5280        };
5281
5282        if let Some(message) =
5283            catalog_update_frozen_field_message(&registration.manifest, &provides)
5284        {
5285            return Ok(vec![control_error_frame(
5286                &frame,
5287                "catalog_update_frozen_field",
5288                message,
5289            )?]);
5290        }
5291
5292        let mut candidate = registration.manifest.clone();
5293        candidate.provides = provides.clone();
5294        candidate.capabilities = capabilities
5295            .clone()
5296            .or_else(|| registration.manifest.capabilities.clone());
5297        if let Some(rich_ui) = &candidate.rich_ui {
5298            if let Err(err) = rich_ui.validate() {
5299                return Ok(vec![control_error_frame(
5300                    &frame,
5301                    "invalid_manifest",
5302                    err.to_string(),
5303                )?]);
5304            }
5305        }
5306        if let Err(err) = candidate.validate_capability_grammar() {
5307            return Ok(vec![control_error_frame(
5308                &frame,
5309                "invalid_capability_grammar",
5310                err.to_string(),
5311            )?]);
5312        }
5313
5314        // Updates must honor the same reserved owner as initial registration;
5315        // otherwise an empty HELLO could acquire the claim after admission.
5316        let mut conflicts = self
5317            .capability_evaluator
5318            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5319        if let Some(conflict) = conflicts.first() {
5320            let message = format!(
5321                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5322                conflict.capability, conflict.claimants[0], candidate.module_id
5323            );
5324            for conflict in &mut conflicts {
5325                conflict.source = DuplicateClaimSource::CatalogUpdate;
5326            }
5327            log_duplicate_claim_events(conflicts);
5328            return Ok(vec![control_error_frame(
5329                &frame,
5330                "reserved_capability",
5331                message,
5332            )?]);
5333        }
5334
5335        let updated = match self.registry.replace_catalog_for_connection(
5336            connection_id,
5337            provides,
5338            capabilities,
5339            ready,
5340        ) {
5341            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5342                return Ok(vec![control_error_frame(
5343                    &frame,
5344                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5345                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5346                )?])
5347            }
5348            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5349                return Ok(vec![control_error_frame(
5350                    &frame,
5351                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5352                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5353                )?])
5354            }
5355            result => {
5356                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5357            }
5358        };
5359        if updated.is_none() {
5360            return Ok(vec![control_error_frame(
5361                &frame,
5362                "not_registered",
5363                "catalog.update requires an active module registration owned by this connection",
5364            )?]);
5365        }
5366        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5367            log_duplicate_claim_events(
5368                self.capability_evaluator
5369                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5370            );
5371        }
5372        if capability_census_trigger(
5373            registration.manifest.capabilities.as_ref(),
5374            updated
5375                .as_ref()
5376                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5377        ) {
5378            self.enforce_capability_denies();
5379        }
5380        self.refresh_capability_requirements();
5381
5382        let response = ModuleControlResponseToModule::CatalogUpdate {};
5383        control_response_body_frame(
5384            &frame,
5385            &response,
5386            "ModuleControlResponseToModule::CatalogUpdate",
5387        )
5388        .map(|frame| vec![frame])
5389    }
5390
5391    pub(crate) fn with_activity_ledger_config(
5392        mut self,
5393        run_dir: &Path,
5394        incarnation: String,
5395        config: crate::activity::ActivityConfig,
5396    ) -> Self {
5397        self.activity = Some(crate::activity::ActivityLedger::open_config(
5398            run_dir.join("activity.jsonl"),
5399            incarnation,
5400            config,
5401        ));
5402        self.supervisor.set_activity(self.activity.clone());
5403        self
5404    }
5405
5406    pub(crate) async fn configure_activity(
5407        &self,
5408        config: crate::activity::ActivityConfig,
5409    ) -> Result<(), &'static str> {
5410        match &self.activity {
5411            Some(ledger) => ledger.configure(config).await,
5412            None => Ok(()),
5413        }
5414    }
5415
5416    fn cancel_activity_subscription(
5417        &self,
5418        ctx: &RouteCtx,
5419        frame: &Frame,
5420    ) -> Result<bool, RouterError> {
5421        let task = self
5422            .activity_streams
5423            .lock()
5424            .unwrap_or_else(|p| p.into_inner())
5425            .remove(&(ctx.connection_id, frame.header.corr));
5426        let Some(task) = task else {
5427            return Ok(false);
5428        };
5429        task.abort();
5430        let end = Frame::build_with_version(
5431            response_version(frame),
5432            FrameType::StreamEnd,
5433            control_flags(),
5434            0,
5435            0,
5436            frame.header.corr,
5437            Vec::new(),
5438        )
5439        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5440        let sink = ctx.egress.clone();
5441        tokio::spawn(async move {
5442            let _ = sink.send(end).await;
5443        });
5444        Ok(true)
5445    }
5446
5447    async fn handle_activity_read(
5448        &self,
5449        ctx: &RouteCtx,
5450        frame: Frame,
5451    ) -> Result<Vec<Frame>, RouterError> {
5452        #[cfg(test)]
5453        {
5454            let pause = self
5455                .activity_request_pause
5456                .lock()
5457                .unwrap()
5458                .clone()
5459                .filter(|pause| pause.connection == ctx.connection_id);
5460            if let Some(pause) = pause {
5461                let _cancelled = ActivityRequestCancellation(pause.clone());
5462                pause.started.notify_one();
5463                std::future::pending::<()>().await;
5464            }
5465        }
5466        use subc_control::{
5467            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5468            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5469        };
5470        #[derive(Deserialize)]
5471        struct Identity {
5472            #[serde(default)]
5473            consumer_identity: Option<ConsumerIdentity>,
5474        }
5475        // A registration channel or claim-bound connection carries its module in
5476        // its binding, so no request field can name another principal, and its
5477        // subscription ends when the bound spawn's authority does.
5478        let mut bound_spawn = None;
5479        let legacy = match self.activity_reader(ctx.connection_id) {
5480            channel_operations::ActivityReader::Module { module_id, spawn } => {
5481                bound_spawn = Some(spawn);
5482                Some(Ok(Principal::Reserved { module_id }))
5483            }
5484            // Refused outright: falling back to `direct` would admit it.
5485            channel_operations::ActivityReader::Refused => {
5486                return Ok(vec![control_error_frame(
5487                    &frame,
5488                    ACTIVITY_READ_FORBIDDEN,
5489                    "helper, relay and retired connections cannot read activity",
5490                )?]);
5491            }
5492            channel_operations::ActivityReader::Legacy => None,
5493        };
5494        // A registered module connection already identifies its caller. Ignore
5495        // consumer_identity there so a module cannot borrow a mirror's identity.
5496        // Only separate consumer connections use the Direct/nonce trust boundary.
5497        let principal = match legacy {
5498            Some(principal) => principal,
5499            None => match self
5500                .forwarding
5501                .module_id_for_connection(ctx.connection_id)
5502                .map_err(RouterError::Forwarding)?
5503            {
5504                Some(module_id) => Ok(Principal::Reserved { module_id }),
5505                None => {
5506                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5507                        Ok(identity) => identity,
5508                        Err(_) => {
5509                            return Ok(vec![control_error_frame(
5510                                &frame,
5511                                ACTIVITY_MALFORMED,
5512                                "malformed activity read",
5513                            )?])
5514                        }
5515                    };
5516                    self.route_open_principal(
5517                        ctx.connection_id,
5518                        &frame,
5519                        identity.consumer_identity,
5520                    )?
5521                }
5522            },
5523        };
5524        let admitted = matches!(principal, Ok(Principal::Direct))
5525            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5526        if !admitted {
5527            return Ok(vec![control_error_frame(
5528                &frame,
5529                ACTIVITY_READ_FORBIDDEN,
5530                "activity reads require an operator or trusted mirror principal",
5531            )?]);
5532        }
5533        let Some(ledger) = &self.activity else {
5534            return Ok(vec![control_error_frame(
5535                &frame,
5536                ACTIVITY_UNAVAILABLE,
5537                "activity ledger unavailable",
5538            )?]);
5539        };
5540        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5541            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5542        {
5543            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5544                Ok(request) => ledger.query(request).await,
5545                Err(_) => Err(ACTIVITY_MALFORMED),
5546            };
5547            return match result {
5548                Ok(reply) => Ok(vec![control_response_body_frame(
5549                    &frame,
5550                    &reply,
5551                    ops::ACTIVITY_QUERY,
5552                )?]),
5553                Err(code) => Ok(vec![control_error_frame(
5554                    &frame,
5555                    code,
5556                    "activity query refused",
5557                )?]),
5558            };
5559        }
5560        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5561            Ok(request) => request,
5562            Err(_) => {
5563                return Ok(vec![control_error_frame(
5564                    &frame,
5565                    ACTIVITY_MALFORMED,
5566                    "malformed activity subscription",
5567                )?])
5568            }
5569        };
5570        let mut subscription = match ledger.subscribe(request.since).await {
5571            Ok(subscription) => subscription,
5572            Err(code) => {
5573                return Ok(vec![control_error_frame(
5574                    &frame,
5575                    code,
5576                    "activity subscription refused",
5577                )?])
5578            }
5579        };
5580        let key = (ctx.connection_id, frame.header.corr);
5581        let sink = ctx.egress.clone();
5582        let mut streams = self
5583            .activity_streams
5584            .lock()
5585            .unwrap_or_else(|p| p.into_inner());
5586        streams.retain(|_, task| !task.is_finished());
5587        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5588            return Ok(vec![control_error_frame(
5589                &frame,
5590                "duplicate_subscription",
5591                "activity subscription correlation id already in use",
5592            )?]);
5593        }
5594        let stream = async move {
5595            loop {
5596                let entry = if let Some(entry) = subscription.replay.pop_front() {
5597                    Some(entry)
5598                } else {
5599                    subscription.receiver.recv().await
5600                };
5601                let Some(entry) = entry else {
5602                    break;
5603                };
5604                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5605                    return;
5606                };
5607                let Ok(next) = Frame::build_with_version(
5608                    response_version(&frame),
5609                    FrameType::StreamData,
5610                    control_flags(),
5611                    0,
5612                    0,
5613                    frame.header.corr,
5614                    body,
5615                ) else {
5616                    return;
5617                };
5618                if sink.send(next).await.is_err() {
5619                    return;
5620                }
5621            }
5622            // Dropping a full subscriber's sender drains its accepted entries
5623            // before the terminal error, preserving their order on the wire.
5624            if let Some(code) = subscription.terminal_code() {
5625                if let Ok(end) =
5626                    control_error_frame(&frame, code, "activity subscriber fell behind")
5627                {
5628                    let _ = sink.send(end).await;
5629                }
5630            }
5631        };
5632        // The spawn's retirement revokes this connection's authority. End the
5633        // subscription then, rather than when the connection's close is
5634        // eventually processed or the next entry fails to send.
5635        let task = tokio::spawn(async move {
5636            match bound_spawn {
5637                Some(spawn) => {
5638                    tokio::select! {
5639                        () = stream => {}
5640                        () = spawn.wait_closed() => {}
5641                    }
5642                }
5643                None => stream.await,
5644            }
5645        });
5646        streams.insert(key, task.abort_handle());
5647        Ok(Vec::new())
5648    }
5649
5650    async fn handle_activity_record(
5651        &self,
5652        ctx: &RouteCtx,
5653        frame: Frame,
5654    ) -> Result<Vec<Frame>, RouterError> {
5655        use subc_control::{
5656            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5657            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5658        };
5659        let result = async {
5660            let module = self
5661                .forwarding
5662                .module_id_for_connection(ctx.connection_id)
5663                .ok()
5664                .flatten()
5665                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5666            let request: ActivityRecordRequest =
5667                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5668            crate::activity::validate(&module, &request)?;
5669            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5670            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5671            let at_ms = std::time::SystemTime::now()
5672                .duration_since(std::time::UNIX_EPOCH)
5673                .unwrap_or_default()
5674                .as_millis() as u64;
5675            ledger.record(module, request, actor, at_ms).await
5676        }
5677        .await;
5678        match result {
5679            Ok(entry) => Ok(vec![control_response_body_frame(
5680                &frame,
5681                &ActivityRecordResponse { seq: entry.seq },
5682                "activity.record",
5683            )?]),
5684            Err(code) => Ok(vec![control_error_frame(
5685                &frame,
5686                code,
5687                "activity recording refused",
5688            )?]),
5689        }
5690    }
5691
5692    fn activity_actor(
5693        &self,
5694        connection: ConnectionId,
5695        module: &str,
5696        on: Option<&subc_control::ActivityOn>,
5697    ) -> Result<subc_control::ActivityActor, &'static str> {
5698        use crate::forwarding::{DataRoute, DataRouteState};
5699        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5700        let principal = |id: &str| Principal::Reserved {
5701            module_id: id.to_owned(),
5702        };
5703        let mut actor = ActivityActor {
5704            principal: principal(module),
5705            scope_owner: None,
5706            agent_id: None,
5707            run_id: None,
5708            flow_id: None,
5709            project_root: None,
5710            workdir: None,
5711            project_id: None,
5712        };
5713        let scope = match on {
5714            None => return Ok(actor),
5715            Some(ActivityOn::Scope(scope)) => {
5716                let selector = subc_protocol::scope::ScopeSelector::new(
5717                    principal(module),
5718                    scope.scope_ref.clone(),
5719                    Some(scope.epoch),
5720                );
5721                self.scopes
5722                    .read()
5723                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5724                    .attribute(&principal(module), module, &selector, true)
5725                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5726            }
5727            Some(ActivityOn::Route(route)) => {
5728                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5729                    .forwarding
5730                    .lookup_data_route(connection, route.channel, route.epoch)
5731                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5732                else {
5733                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5734                };
5735                if binding.module_id != module {
5736                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5737                }
5738                actor.principal = binding.principal.clone();
5739                actor.project_root = binding
5740                    .project_root
5741                    .as_ref()
5742                    .map(|root| root.as_path().to_path_buf());
5743                let Some(bound) = &binding.scope else {
5744                    return Ok(actor);
5745                };
5746                let owner = principal(&bound.owner);
5747                let selector = subc_protocol::scope::ScopeSelector::new(
5748                    owner.clone(),
5749                    bound.scope_ref.clone(),
5750                    Some(bound.tag.scope_epoch),
5751                );
5752                let admitted = self
5753                    .scopes
5754                    .read()
5755                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5756                    .attribute(&owner, module, &selector, true)
5757                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5758                if admitted.tag != bound.tag {
5759                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5760                }
5761                admitted
5762            }
5763        };
5764        actor.scope_owner = Some(scope.stamp.owner);
5765        actor.agent_id = scope.stamp.attributes.agent_id;
5766        actor.run_id = scope.stamp.attributes.run_id;
5767        actor.flow_id = scope.stamp.attributes.flow_id;
5768        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5769        actor.project_id = scope.stamp.project_id;
5770        Ok(actor)
5771    }
5772
5773    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5774        let module_id = self
5775            .claims
5776            .binding(connection)
5777            .filter(|binding| {
5778                binding.consumer_live(connection) && binding.registration.authority.alive()
5779            })
5780            .map(|binding| binding.registration.module_id.clone())
5781            .or_else(|| {
5782                self.registry
5783                    .module_id_for_connection(connection)
5784                    .ok()
5785                    .flatten()
5786            });
5787        let principal = module_id
5788            .map(|module_id| format!("reserved:{module_id}"))
5789            .unwrap_or_else(|| "direct".to_owned());
5790        self.control_usage
5791            .lock()
5792            .unwrap_or_else(|poisoned| poisoned.into_inner())
5793            .record(op, &principal);
5794    }
5795
5796    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5797        self.refresh_capability_requirements();
5798        // A bare connection count is ambiguous between many clients holding a
5799        // route each and one client accumulating hundreds, so publish the
5800        // concentration alongside it. Route state is best-effort here: a
5801        // diagnostic endpoint must still answer if the forwarding lock is
5802        // contended.
5803        let mut counters = self.counters.snapshot();
5804        if let Some(obj) = counters.as_object_mut() {
5805            obj.insert(
5806                "control_usage".into(),
5807                self.control_usage
5808                    .lock()
5809                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5810                    .snapshot(),
5811            );
5812        }
5813        let losses = self.resource_tracker.loss_diagnostics();
5814        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5815            if let Some(obj) = counters.as_object_mut() {
5816                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5817            }
5818        }
5819        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5820            obj.insert(
5821                "activity_unparseable_lines".into(),
5822                ledger.read_errors().into(),
5823            );
5824            obj.insert(
5825                "activity_lifecycle_append_failures".into(),
5826                ledger.lifecycle_failures().into(),
5827            );
5828            obj.insert(
5829                "activity_started_digest_skips".into(),
5830                ledger.lifecycle_digest_skips().into(),
5831            );
5832        }
5833        if let (Ok((connections_with_routes, max)), Some(obj)) = (
5834            self.forwarding.client_route_concentration(),
5835            counters.as_object_mut(),
5836        ) {
5837            obj.insert(
5838                "client_connections_with_routes".into(),
5839                connections_with_routes.into(),
5840            );
5841            obj.insert("max_routes_on_one_connection".into(), max.into());
5842        }
5843        // A module that is being fast-refused and a module that is fine look
5844        // identical from a client that retries and succeeds, so name the open
5845        // breakers here. This rides the existing free-form counters object
5846        // rather than a new wire field, so no sibling that deserializes
5847        // `ServerDescribe` has to be rebuilt to keep reading it.
5848        if let (Some(open_breakers), Some(obj)) = (
5849            self.route_bind_breakers.open_snapshot(),
5850            counters.as_object_mut(),
5851        ) {
5852            obj.insert("route_bind_breakers_open".into(), open_breakers);
5853        }
5854        // A daemon whose local endpoint could not be bound keeps serving TCP,
5855        // and the connection file names no endpoint. Name the reason here, in
5856        // the free-form counters object, so an operator reading daemon facts
5857        // sees it without searching the log, and no wire field changes.
5858        if let (Some(reason), Some(obj)) = (
5859            self.local_endpoint_unavailable.clone(),
5860            counters.as_object_mut(),
5861        ) {
5862            obj.insert("local_endpoint_unavailable".into(), reason.into());
5863        }
5864        let response = ClientControlResponse::ServerDescribe {
5865            protocol_ver: PROTOCOL_VERSION,
5866            subc_ops: subc_ops(),
5867            capabilities: self.describe_capabilities(),
5868            connected_clients: self.connected_clients.count(),
5869            counters: Some(counters),
5870            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
5871            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
5872            capability_requirements: self.capability_requirement_statuses(),
5873            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
5874            config_path: self
5875                .rescan
5876                .as_ref()
5877                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
5878        };
5879        Ok(vec![control_response_body_frame(
5880            &frame,
5881            &response,
5882            "ClientControlResponse::ServerDescribe",
5883        )?])
5884    }
5885
5886    fn handle_catalog_list(
5887        &self,
5888        frame: Frame,
5889        module_id: Option<String>,
5890    ) -> Result<Vec<Frame>, RouterError> {
5891        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
5892        Ok(vec![Frame::build_with_version(
5893            response_version(&frame),
5894            FrameType::Response,
5895            control_flags(),
5896            0,
5897            0,
5898            frame.header.corr,
5899            body,
5900        )
5901        .map_err(RouterError::FrameBuild)?])
5902    }
5903
5904    #[cfg(test)]
5905    fn uncached_catalog_list(
5906        &self,
5907        corr: u64,
5908        module_id: Option<&str>,
5909    ) -> Result<ClientControlResponse, RouterError> {
5910        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
5911    }
5912
5913    fn catalog_list_snapshot(
5914        &self,
5915        corr: u64,
5916        module_id: Option<&str>,
5917        include_declarations: bool,
5918    ) -> Result<ClientControlResponse, RouterError> {
5919        let (generation, modules) = self
5920            .registry
5921            .list_modules_with_nonce_verification()
5922            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
5923        let entries = modules
5924            .into_iter()
5925            .filter(|(registration, _)| {
5926                module_id
5927                    .map(|wanted| registration.manifest.module_id == wanted)
5928                    .unwrap_or(true)
5929            })
5930            .map(|(registration, nonce_verified)| {
5931                let entry = self
5932                    .catalog_discovery_entry(&registration, include_declarations)
5933                    .map_err(|err| RouterError::backend(0, corr, err))?;
5934                let not_ready = self.not_ready_reason(&registration);
5935                let mut entry = entry;
5936                entry.roles = registration.manifest.provides;
5937                entry.control_ops = registration.control_ops;
5938                Ok(entry
5939                    .with_ready(not_ready.is_none())
5940                    .with_display_name(registration.manifest.display_name)
5941                    .with_not_ready(not_ready)
5942                    .with_module_version(Some(registration.manifest.module_version))
5943                    .with_provenance(registration.manifest.provenance)
5944                    .with_capabilities(registration.manifest.capabilities)
5945                    .with_self_signals(registration.manifest.self_signals)
5946                    .with_events(registration.manifest.events)
5947                    .with_operation_delivery(registration.manifest.operation_delivery)
5948                    .with_operation_payload(registration.manifest.operation_payload)
5949                    .with_flow_operations(registration.manifest.flow_operations)
5950                    .with_operation_deferral(registration.manifest.operation_deferral)
5951                    .with_confirm_operations(registration.manifest.confirm_operations)
5952                    .with_rich_ui(registration.manifest.rich_ui)
5953                    .with_role_declarations(registration.manifest.role_declarations)
5954                    .with_nonce_verified(nonce_verified))
5955            })
5956            .collect::<Result<Vec<_>, RouterError>>()?;
5957        Ok(ClientControlResponse::CatalogList {
5958            generation,
5959            modules: entries,
5960            subc_ops: subc_ops(),
5961        })
5962    }
5963
5964    /// The caller fields for a refusal that only has the raw request frame,
5965    /// such as the connection-level admission refusal sent before the request
5966    /// reaches [`Self::handle_route_open`].
5967    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
5968        let Ok(ClientControlRequest::RouteOpen {
5969            identity,
5970            consumer_identity,
5971            scope,
5972            ..
5973        }) = parse_client_control_request(&frame.body)
5974        else {
5975            return RouteOpenCaller::unknown();
5976        };
5977        let principal = self
5978            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
5979            .map(|attested| attested.principal);
5980        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
5981    }
5982
5983    fn route_open_principal(
5984        &self,
5985        connection_id: ConnectionId,
5986        frame: &Frame,
5987        consumer_identity: Option<ConsumerIdentity>,
5988    ) -> Result<Result<Principal, Frame>, RouterError> {
5989        let attested = self
5990            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
5991            .map(|attested| attested.principal);
5992        self.route_open_principal_attested(frame, consumer_identity, attested)
5993    }
5994
5995    /// [`Self::route_open_principal`] with `attested` already taken by
5996    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
5997    /// claim or launch nonce once.
5998    fn route_open_principal_attested(
5999        &self,
6000        frame: &Frame,
6001        consumer_identity: Option<ConsumerIdentity>,
6002        attested: Option<Principal>,
6003    ) -> Result<Result<Principal, Frame>, RouterError> {
6004        if let Some(principal) = attested {
6005            return Ok(Ok(principal));
6006        }
6007        Ok(Err(control_error_frame(
6008            frame,
6009            "bad_consumer_identity",
6010            consumer_identity.map_or_else(
6011                || "connection claim is no longer authorized for routes".to_string(),
6012                |identity| format!(
6013                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
6014                    identity.module_id
6015                ),
6016            ),
6017        )?))
6018    }
6019
6020    /// Ordinary `route.open` refusals go through here; admission and breaker
6021    /// refusals log separately with their capacity or breaker state. The daemon can
6022    /// attest which code it sent: without the event, a client's "the daemon
6023    /// refused me" and the daemon's own view could only be reconciled by
6024    /// argument. Malformed input (`invalid_project_root`) does not come here;
6025    /// rejecting a request that was never a valid open is not a refusal of one.
6026    #[allow(clippy::too_many_arguments)]
6027    fn route_open_refusal_frame(
6028        &self,
6029        ctx: &RouteCtx,
6030        caller: &RouteOpenCaller,
6031        frame: &Frame,
6032        module_id: &str,
6033        reason: &'static str,
6034        code: &'static str,
6035        message: impl Into<String>,
6036    ) -> Result<Frame, RouterError> {
6037        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
6038        let detail = if matches!(
6039            reason,
6040            "registration_not_active"
6041                | "supervisor_not_live"
6042                | "no_forwarding_connection"
6043                | "reloading"
6044        ) {
6045            // A planned restart, reload or swap is already replacing the
6046            // process; it does not need a slot in the crash-restart budget.
6047            let expected_back = (reason == "reloading").then_some(true);
6048            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
6049        } else {
6050            None
6051        };
6052        control_error_body_frame(
6053            frame,
6054            ErrorBody {
6055                code: code.to_string(),
6056                message: message.into(),
6057                detail,
6058            },
6059        )
6060    }
6061
6062    fn route_open_recovery_detail(
6063        &self,
6064        module_id: &str,
6065        corr: u64,
6066        detail: Option<serde_json::Value>,
6067        expected_back: Option<bool>,
6068    ) -> Result<Option<serde_json::Value>, RouterError> {
6069        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
6070            return Ok(detail);
6071        };
6072        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
6073        detail["state"] = serde_json::json!(status.state.to_string());
6074        if let Some(expected_back) = expected_back {
6075            detail["expected_back"] = serde_json::json!(expected_back);
6076        } else if let Some(module) = self.supervisor.get(module_id) {
6077            match module.will_recover_after_connection_loss() {
6078                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
6079                Err(err) => warn!(
6080                    %module_id,
6081                    error = %err,
6082                    "failed to read route.open recovery verdict; omitting expected_back"
6083                ),
6084            }
6085        }
6086        Ok(Some(detail))
6087    }
6088
6089    /// Answer a waiting `route.open` whose relayed bind was refused.
6090    ///
6091    /// `daemon_authored` is provenance, not a code match: the daemon
6092    /// synthesized the refusal itself (a drain, a late reply, a scope that
6093    /// ended mid-bind) or the module refused the bind with its own body. A
6094    /// daemon refusal carries the daemon-origin bit; a module's own
6095    /// rejection is relayed with the bit clear, so a module that refuses
6096    /// with `module_reloading` still cannot mint a daemon refusal.
6097    #[allow(clippy::too_many_arguments)]
6098    fn route_bind_rejection(
6099        &self,
6100        ctx: &RouteCtx,
6101        caller: &RouteOpenCaller,
6102        frame: &Frame,
6103        target_module_id: &str,
6104        body: ErrorBody,
6105        daemon_authored: bool,
6106    ) -> Result<Vec<Frame>, RouterError> {
6107        // The daemon's own commit re-check refused the bind because the
6108        // scope ended or changed after admission. The module accepted;
6109        // counting it as a module rejection would blame the module. This
6110        // branch only runs for daemon-synthesized bodies: a module that
6111        // refuses with a scope code is answered as a module rejection below.
6112        if daemon_authored {
6113            let scope_code = match body.code.as_str() {
6114                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
6115                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
6116                _ => None,
6117            };
6118            if let Some(code) = scope_code {
6119                self.observe_route_open_refusal(
6120                    ctx,
6121                    caller,
6122                    target_module_id,
6123                    "scope_changed_before_commit",
6124                    code,
6125                );
6126                return Ok(vec![control_error_body_frame(frame, body)?]);
6127            }
6128        }
6129        self.counters
6130            .increment_route_open_refused("module_rejected");
6131        info!(
6132            target: "control",
6133            code = "module_rejected",
6134            module_code = ?body.code,
6135            module_id = ?target_module_id,
6136            connection_id = ctx.connection_id.get(),
6137            principal = %caller.principal,
6138            scope = %caller.scope,
6139            harness = %caller.harness,
6140            "route.open refused"
6141        );
6142        let refusal = if daemon_authored {
6143            control_error_body_frame(frame, body)?
6144        } else {
6145            control_relayed_error_body_frame(frame, body)?
6146        };
6147        Ok(vec![refusal])
6148    }
6149
6150    /// Refuse a `route.open` because the target module's bind-relay breaker is
6151    /// open, without attempting the relay.
6152    ///
6153    /// The wire code is `module_timeout`, which is the truth (the module has
6154    /// not been answering binds) and which both SDKs already classify as
6155    /// retryable with capped backoff. Reusing it is what keeps this change out
6156    /// of both SDKs; the daemon-side distinction lives in the counter key
6157    /// instead.
6158    ///
6159    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6160    /// While a breaker is open this fires on every open to that module, and the
6161    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6162    /// produced 261 lines about a single module inside 3000 lines of daemon
6163    /// log. The rare transitions are logged at warn/info instead and the volume
6164    /// is carried by the counter, so the evidence survives without the flood.
6165    /// The debug line keeps a per-refusal record reachable for whoever turns
6166    /// the level up.
6167    #[allow(clippy::too_many_arguments)]
6168    fn route_open_breaker_refusal_frame(
6169        &self,
6170        ctx: &RouteCtx,
6171        caller: &RouteOpenCaller,
6172        frame: &Frame,
6173        module_id: &str,
6174        consecutive_timeouts: u32,
6175        retry_in: Duration,
6176        probe_in_flight: bool,
6177    ) -> Result<Frame, RouterError> {
6178        self.counters
6179            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6180        debug!(
6181            target: "control",
6182            code = "module_timeout",
6183            module_id = ?module_id,
6184            connection_id = ctx.connection_id.get(),
6185            principal = %caller.principal,
6186            scope = %caller.scope,
6187            harness = %caller.harness,
6188            consecutive_timeouts,
6189            retry_in_ms = retry_in.as_millis() as u64,
6190            probe_in_flight,
6191            "route.open refused by open bind-relay breaker"
6192        );
6193        // Say what a caller can act on. An open bind-relay breaker means the
6194        // module timed out accepting several new routes in a row. The module
6195        // is still running and its established routes keep working; only new
6196        // route.open requests are refused until the cooldown ends and one
6197        // test route (the probe) gets through. A message that only counts
6198        // failed relays reads as "the module is down" to a worker that sees it.
6199        let detail = if probe_in_flight {
6200            "one test route is already being tried; retry once it settles".to_string()
6201        } else {
6202            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6203        };
6204        control_error_frame(
6205            frame,
6206            "module_timeout",
6207            format!(
6208                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6209                 timed out in a row); {detail}; its established routes are unaffected"
6210            ),
6211        )
6212    }
6213
6214    /// `reason` names the check that refused, because one wire code has
6215    /// several senders: after a module registers, `target_unavailable` can
6216    /// come from a missing role, an inactive registration, a supervisor that
6217    /// has not marked the process live, a missing forwarding connection, or a
6218    /// failed relay, and a log that records only the code cannot say which of
6219    /// them fired. It is a static, daemon-chosen label per branch, so it is
6220    /// safe to print plainly and stays a closed set.
6221    fn observe_route_open_refusal(
6222        &self,
6223        ctx: &RouteCtx,
6224        caller: &RouteOpenCaller,
6225        module_id: &str,
6226        reason: &'static str,
6227        code: &'static str,
6228    ) {
6229        self.counters.increment_route_open_refused(code);
6230        self.route_refusal_log
6231            .record(module_id, code, reason, caller, ctx.connection_id.get());
6232        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6233            self.route_outages.record_not_serving(module_id, reason);
6234        }
6235    }
6236
6237    /// Record an ACCEPTED route.open.
6238    ///
6239    /// Refusals have been logged and counted since the attestation work; accepts
6240    /// were invisible, so the daemon knew every principal it stamped and wrote
6241    /// none of them down. The party that attests the identity was the only party
6242    /// not recording it, which left a credential vault unable to name the sender
6243    /// of a call that reached it (claustrum #43) and left the launch-nonce
6244    /// concurrency question unanswerable from the outside.
6245    ///
6246    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6247    /// `code`/`module_id`/`connection_id` returns both directions of the same
6248    /// decision rather than two shapes a reader has to join by hand.
6249    ///
6250    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6251    /// and the difference carries information rather than being an
6252    /// inconsistency. This line is only reachable after a successful bind to a
6253    /// REGISTERED module, so the value has already passed HELLO validation
6254    /// including the path-hazard refusal and cannot contain control bytes. A
6255    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6256    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6257    ///
6258    /// Bare is also what every other daemon line already emits (`module
6259    /// registered`, `configured module supervised`). Shipping `?module_id` here
6260    /// made this instrument the only one in the file whose ids did not answer
6261    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6262    /// line whose whole purpose is being grepped beside its sibling.
6263    ///
6264    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6265    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6266    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6267    /// one are recorded identically. A test written against that harness passes
6268    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6269    /// green assertion that cannot fail. The same limit applies to the escaping
6270    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6271    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6272    /// Fencing either needs the real formatter, not the capture layer.
6273    ///
6274    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6275    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6276    /// to record. The ephemeral port would decay within minutes and answer only a
6277    /// live question. The identity question is instead answered by counting
6278    /// distinct live connections presenting one module's `consumer_identity` --
6279    /// "is anyone else holding this secret" rather than "is this the right
6280    /// process".
6281    fn observe_route_open_accept(
6282        &self,
6283        ctx: &RouteCtx,
6284        module_id: &str,
6285        principal: &str,
6286        scope: &str,
6287    ) {
6288        self.route_outages.record_accepted(module_id);
6289        self.counters.increment_route_open_accepted(principal);
6290        debug!(
6291            target: "control",
6292            principal,
6293            module_id,
6294            connection_id = ctx.connection_id.get(),
6295            scope = %scope,
6296            "route.open accepted"
6297        );
6298    }
6299
6300    fn supervised_absent_route_open_refusal_frame(
6301        &self,
6302        ctx: &RouteCtx,
6303        caller: &RouteOpenCaller,
6304        frame: &Frame,
6305        module_id: &str,
6306        code: &'static str,
6307        status: &crate::supervise::ModuleStatus,
6308    ) -> Result<Frame, RouterError> {
6309        self.counters.increment_route_open_refused(code);
6310        info!(
6311            target: "control",
6312            code,
6313            reason = "supervised_not_registered",
6314            module_id = ?module_id,
6315            connection_id = ctx.connection_id.get(),
6316            principal = %caller.principal,
6317            scope = %caller.scope,
6318            harness = %caller.harness,
6319            state = %status.state,
6320            enabled = status.enabled,
6321            live = status.live,
6322            "route.open refused"
6323        );
6324        // A supervised module whose process has not registered is not
6325        // serving, whatever the reason; the supervisor knows this id, so it is
6326        // safe to track.
6327        self.route_outages
6328            .record_not_serving(module_id, "supervised_not_registered");
6329        let message = if let Some(pid) = status.waiting_for_previous_pid {
6330            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6331                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6332            })
6333        } else {
6334            format!(
6335                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6336                status.state, status.enabled, status.live
6337            )
6338        };
6339        // `module_warming` here means the process is starting, running or
6340        // being restarted and has not registered yet. Nothing has to be
6341        // restarted for it to serve, so the crash budget does not decide it.
6342        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6343        control_error_body_frame(
6344            frame,
6345            ErrorBody {
6346                code: code.to_string(),
6347                message,
6348                detail: self.route_open_recovery_detail(
6349                    module_id,
6350                    frame.header.corr,
6351                    None,
6352                    expected_back,
6353                )?,
6354            },
6355        )
6356    }
6357
6358    async fn handle_route_open(
6359        &self,
6360        ctx: &RouteCtx,
6361        frame: Frame,
6362        request: RouteOpenRequest,
6363        timings: &mut RouteOpenTimings,
6364    ) -> Result<Vec<Frame>, RouterError> {
6365        let RouteOpenRequest {
6366            target,
6367            mut identity,
6368            consumer_identity,
6369            consumer_capabilities,
6370            role_versions,
6371            busy_refusals,
6372            admission_facts,
6373            scope,
6374            accepts_close_reasons,
6375        } = request;
6376        let target_module_id = target_module_id(&target).to_string();
6377        timings.module_id.clone_from(&target_module_id);
6378        if self
6379            .registry
6380            .get_module_by_connection(ctx.connection_id)
6381            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6382            .is_some()
6383        {
6384            return Ok(vec![control_error_frame(
6385                &frame,
6386                "invalid_request",
6387                "module connections cannot open client routes",
6388            )?]);
6389        }
6390        debug!(
6391            connection_id = ctx.connection_id.get(),
6392            corr = frame.header.corr,
6393            module_id = %target_module_id,
6394            "handling route.open"
6395        );
6396
6397        // The caller's attested principal, requested scope and harness, for
6398        // every `route.open refused` line below. The connection's claim
6399        // binding or launch nonce is checked here, once, and the answer is
6400        // reused where the principal is enforced further down, so the order
6401        // of refusals is unchanged.
6402        let attested =
6403            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6404        let mut caller = RouteOpenCaller::new(
6405            attested.as_ref().map(|attested| &attested.principal),
6406            scope.as_ref(),
6407            &identity,
6408        );
6409
6410        // A malformed declaration is refused first, before anything about the
6411        // target is looked up: the same body would be refused against any
6412        // module, so the caller learns nothing by retrying or waiting. An empty
6413        // map declares nothing and travels as no field at all, so a provider
6414        // only ever sees a missing field or a non-empty one.
6415        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6416        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6417            self.observe_route_open_refusal(
6418                ctx,
6419                &caller,
6420                &target_module_id,
6421                "invalid_role_versions",
6422                error_codes::INVALID_REQUEST,
6423            );
6424            return Ok(vec![control_error_body_frame(
6425                &frame,
6426                ErrorBody {
6427                    code: error_codes::INVALID_REQUEST.to_string(),
6428                    message: error.to_string(),
6429                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6430                },
6431            )?]);
6432        }
6433
6434        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6435            if status.waiting_for_previous_pid.is_some() {
6436                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6437                    ctx,
6438                    &caller,
6439                    &frame,
6440                    &target_module_id,
6441                    "module_warming",
6442                    &status,
6443                )?]);
6444            }
6445        }
6446
6447        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6448        // opposite. Below, a caller learns whether a module is unregistered,
6449        // supervised-but-down (with state/enabled/live), or registered without the
6450        // requested role. Elsewhere that is an enumeration leak: a probe learning
6451        // the shape of a fleet it cannot otherwise see.
6452        //
6453        // It is not one here, and the reason is the ACCESS MODEL rather than
6454        // anything about these errors. Reaching route.open requires the
6455        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6456        // connection file, so any caller who completes it already runs as this
6457        // user -- and can read subc.jsonc for the module list and `ck module
6458        // status` for live state. The reply discloses nothing the caller cannot
6459        // read more easily from disk, while the precision is load-bearing:
6460        // `unknown_module` is retryable and a missing role is not.
6461        //
6462        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6463        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6464        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6465        let admission_registry = self
6466            .registry
6467            .route_admission_snapshot()
6468            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6469        let Some(registration) =
6470            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6471        else {
6472            if let Some((status, warming)) =
6473                self.supervisor_status(&target_module_id, frame.header.corr)?
6474            {
6475                // BEFORE the two availability codes below, because for a module
6476                // that speaks no subc wire both of them are false comfort: they
6477                // say "not right now" and are retried, and this module will
6478                // never register no matter how long the caller waits. The
6479                // absence here is the declaration being honoured, not a module
6480                // that is late.
6481                if status.protocol == ModuleProtocol::None {
6482                    return Ok(vec![self.route_open_refusal_frame(
6483                        ctx,
6484                        &caller,
6485                        &frame,
6486                        &target_module_id,
6487                        "protocol_none",
6488                        error_codes::MODULE_NO_PROTOCOL,
6489                        format!(
6490                            "module_id '{target_module_id}' is declared protocol: none; \
6491                             it speaks no subc wire and serves no routes"
6492                        ),
6493                    )?]);
6494                }
6495                let code = if warming {
6496                    "module_warming"
6497                } else {
6498                    "target_unavailable"
6499                };
6500                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6501                    ctx,
6502                    &caller,
6503                    &frame,
6504                    &target_module_id,
6505                    code,
6506                    &status,
6507                )?]);
6508            }
6509            if let Some(removed_ago_ms) =
6510                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6511            {
6512                return Ok(vec![self.route_open_refusal_frame(
6513                    ctx,
6514                    &caller,
6515                    &frame,
6516                    &target_module_id,
6517                    "removed",
6518                    error_codes::MODULE_REMOVED,
6519                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6520                )?]);
6521            }
6522            return Ok(vec![self.route_open_refusal_frame(
6523                ctx,
6524                &caller,
6525                &frame,
6526                &target_module_id,
6527                "not_registered",
6528                error_codes::UNKNOWN_MODULE,
6529                format!("module_id '{target_module_id}' is not registered"),
6530            )?]);
6531        };
6532
6533        // Best-effort only: registry readiness and forwarding reservation use
6534        // different locks, so a module can flip readiness between this read and
6535        // the relay. Modules must still tolerate an `on_bind` while not ready.
6536        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6537            .is_err()
6538        {
6539            self.counters
6540                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6541            info!(
6542                target: "control",
6543                code = error_codes::MODULE_WARMING,
6544                module_id = ?target_module_id,
6545                connection_id = ctx.connection_id.get(),
6546                principal = %caller.principal,
6547                scope = %caller.scope,
6548                harness = %caller.harness,
6549                reason = "declared_not_ready",
6550                "route.open refused"
6551            );
6552            // The module is registered but says it cannot take work, which is
6553            // an outage from the caller's side even though its process is up.
6554            self.route_outages
6555                .record_not_serving(&target_module_id, "declared_not_ready");
6556            // The registered process can declare itself ready without a
6557            // restart, so an exhausted crash budget does not prevent serving.
6558            return Ok(vec![control_error_body_frame(
6559                &frame,
6560                ErrorBody {
6561                    code: error_codes::MODULE_WARMING.to_string(),
6562                    message: format!(
6563                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6564                    ),
6565                    detail: self.route_open_recovery_detail(
6566                        &target_module_id,
6567                        frame.header.corr,
6568                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6569                        Some(true),
6570                    )?,
6571                },
6572            )?]);
6573        }
6574
6575        // Effective readiness, second half: a module that declares a capability
6576        // `need: required` is not routable while that capability has no
6577        // registered provider. It is enforced HERE, as a retryable routing
6578        // refusal, and deliberately not as spawn ordering or a boot block. The
6579        // module is still started and registered and can make its own calls;
6580        // spawn ordering is a promise that cannot be kept once a provider
6581        // crashes at runtime, and refusing to boot would stop the whole
6582        // machine, including the tools needed to fix its configuration.
6583        //
6584        // "Provided" is the evaluator's verdict, which counts a provider as
6585        // soon as it has REGISTERED, not once it is ready. Two modules that
6586        // require each other's capabilities are therefore both routable once
6587        // both register; counting readiness instead would deadlock them.
6588        //
6589        // Only new opens are refused. Routes already bound when a provider
6590        // goes away stay bound: nothing here tears them down, and the module
6591        // answers them as it can. Like the readiness read above this is
6592        // best-effort against a provider registering or leaving concurrently.
6593        if let Some(capability) = self.first_unprovided_required_capability_for(
6594            &registration.module_id,
6595            registration.capabilities.as_ref(),
6596        ) {
6597            self.counters
6598                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6599            info!(
6600                target: "control",
6601                code = error_codes::MODULE_WARMING,
6602                module_id = ?target_module_id,
6603                connection_id = ctx.connection_id.get(),
6604                principal = %caller.principal,
6605                scope = %caller.scope,
6606                harness = %caller.harness,
6607                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6608                capability = %capability,
6609                "route.open refused"
6610            );
6611            return Ok(vec![control_error_body_frame(
6612                &frame,
6613                ErrorBody {
6614                    code: error_codes::MODULE_WARMING.to_string(),
6615                    message: format!(
6616                        "module_id '{target_module_id}' requires capability '{capability}', \
6617                         which no registered module provides; retry"
6618                    ),
6619                    detail: Some(serde_json::json!({
6620                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6621                        "capability": capability,
6622                    })),
6623                },
6624            )?]);
6625        }
6626
6627        if !target_has_required_role(&target, &registration.roles) {
6628            return Ok(vec![self.route_open_refusal_frame(
6629                ctx,
6630                &caller,
6631                &frame,
6632                &target_module_id,
6633                "role_not_provided",
6634                "target_unavailable",
6635                format!("module_id '{target_module_id}' does not provide the requested target"),
6636            )?]);
6637        }
6638
6639        if registration.state != ChannelState::Active {
6640            return Ok(vec![self.route_open_refusal_frame(
6641                ctx,
6642                &caller,
6643                &frame,
6644                &target_module_id,
6645                "registration_not_active",
6646                "target_unavailable",
6647                format!("module_id '{target_module_id}' is not active"),
6648            )?]);
6649        }
6650
6651        if self
6652            .forwarding
6653            .module_is_draining(&target_module_id)
6654            .map_err(RouterError::Forwarding)?
6655        {
6656            return Ok(vec![self.route_open_refusal_frame(
6657                ctx,
6658                &caller,
6659                &frame,
6660                &target_module_id,
6661                "reloading",
6662                "module_reloading",
6663                format!("module_id '{target_module_id}' is reloading"),
6664            )?]);
6665        }
6666
6667        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6668            process_liveness.process_live(&target_module_id) == Some(false)
6669        }) {
6670            // A module the supervisor is restarting or reloading can still hold
6671            // a registration: the old process before its connection closes, or
6672            // a new one that registered while the supervisor was draining. The
6673            // forwarding table does not see that as draining, but the consumer
6674            // should still be told to retry soon, exactly as for the drain
6675            // above, rather than that the target is unavailable.
6676            if process_liveness.process_replacing(&target_module_id) {
6677                return Ok(vec![self.route_open_refusal_frame(
6678                    ctx,
6679                    &caller,
6680                    &frame,
6681                    &target_module_id,
6682                    "reloading",
6683                    "module_reloading",
6684                    format!("module_id '{target_module_id}' is reloading"),
6685                )?]);
6686            }
6687            return Ok(vec![self.route_open_refusal_frame(
6688                ctx,
6689                &caller,
6690                &frame,
6691                &target_module_id,
6692                "supervisor_not_live",
6693                "target_unavailable",
6694                format!("module_id '{target_module_id}' is not live"),
6695            )?]);
6696        }
6697
6698        if !self
6699            .forwarding
6700            .has_live_module_connection(&target_module_id)
6701            .map_err(RouterError::Forwarding)?
6702        {
6703            return Ok(vec![self.route_open_refusal_frame(
6704                ctx,
6705                &caller,
6706                &frame,
6707                &target_module_id,
6708                "no_forwarding_connection",
6709                "target_unavailable",
6710                format!("module_id '{target_module_id}' has no live forwarding connection"),
6711            )?]);
6712        }
6713
6714        if let Some(error) =
6715            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6716        {
6717            self.observe_route_open_refusal(
6718                ctx,
6719                &caller,
6720                &target_module_id,
6721                "op_not_allowed",
6722                "op_not_allowed",
6723            );
6724            return Ok(vec![error]);
6725        }
6726
6727        let principal = match (&attested, consumer_identity.is_some()) {
6728            // A claim-bound connection whose launch ended attests nothing,
6729            // and it must never fall back to opening as `direct`.
6730            (None, false) => {
6731                self.observe_route_open_refusal(
6732                    ctx,
6733                    &caller,
6734                    &target_module_id,
6735                    "registration_channel_closed",
6736                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6737                );
6738                return Ok(vec![control_error_frame(
6739                    &frame,
6740                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6741                    "the claim binding's launch has ended",
6742                )?]);
6743            }
6744            _ => match self.route_open_principal_attested(
6745                &frame,
6746                consumer_identity,
6747                attested.as_ref().map(|attested| attested.principal.clone()),
6748            )? {
6749                Ok(principal) => principal,
6750                Err(error) => {
6751                    self.observe_route_open_refusal(
6752                        ctx,
6753                        &caller,
6754                        &target_module_id,
6755                        "bad_consumer_identity",
6756                        "bad_consumer_identity",
6757                    );
6758                    return Ok(vec![error]);
6759                }
6760            },
6761        };
6762        let attested = attested.expect("an attested principal was resolved above");
6763        timings.principal = principal_label(&principal);
6764
6765        // The opener's spawn authority, read once here and carried with the
6766        // relay; nothing below reads its record again.
6767        let Ok(mut caller_capture) = attested.capture() else {
6768            self.observe_route_open_refusal(
6769                ctx,
6770                &caller,
6771                &target_module_id,
6772                "registration_channel_closed",
6773                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6774            );
6775            return Ok(vec![control_error_frame(
6776                &frame,
6777                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6778                "the opener's launch has ended",
6779            )?]);
6780        };
6781        // The caller-side checks below read the opener's own spawn: its
6782        // module from its record and its manifest from its own registration,
6783        // never another launch's active registration under the same id.
6784        let caller_module_id = match &attested.spawn {
6785            Some((record, _)) => Some(record.module_id().to_owned()),
6786            None => match &principal {
6787                Principal::Reserved { module_id } => Some(module_id.clone()),
6788                _ => None,
6789            },
6790        };
6791
6792        // Only Callosum can attest a production phone build. Consume the raw
6793        // claim here; opted-in targets receive only the honoured peer fact.
6794        let build_class = identity.build_class.take().filter(|build_class| {
6795            if caller_module_id.as_deref() == Some("callosum") {
6796                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6797            } else {
6798                if self
6799                    .build_class_warned
6800                    .lock()
6801                    .unwrap_or_else(|p| p.into_inner())
6802                    .insert(ctx.connection_id)
6803                {
6804                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6805                        "ignoring build_class from a non-Callosum opener");
6806                }
6807                false
6808            }
6809        });
6810
6811        // This is attested, control-plane policy for supervised module origins.
6812        // Keep it before route reservation and out of the opaque forwarding hot
6813        // path: data frames must never acquire a per-frame capability check.
6814        if let Some(opening_registration) = self.caller_registration(&attested, &admission_registry)
6815        {
6816            let opening_module_id = opening_registration.module_id.as_str();
6817            if let Some(capability) = denied_capability(
6818                opening_registration.capabilities.as_ref(),
6819                registration.capabilities.as_ref(),
6820            ) {
6821                warn!(
6822                    opening_module_id,
6823                    target_module_id,
6824                    capability,
6825                    "refusing route.open because an attested capability deny edge matches"
6826                );
6827                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6828                    &frame,
6829                    &target_module_id,
6830                    "capability_deny_edge",
6831                    "capability_forbidden",
6832                    format!(
6833                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
6834                    ),
6835                )?]);
6836            }
6837        }
6838
6839        if admission_facts.is_some() {
6840            let carrier_matches = caller_module_id.is_some()
6841                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
6842            if !carrier_matches {
6843                return Ok(vec![self.route_open_refusal_frame(
6844                    ctx,
6845                    &caller,
6846                    &frame,
6847                    &target_module_id,
6848                    "admission_facts_carrier_not_permitted",
6849                    "admission_facts_not_permitted",
6850                    "admission facts may only be carried by the configured reserved module",
6851                )?]);
6852            }
6853
6854            let target_allowed = self
6855                .admission_facts_targets
6856                .as_ref()
6857                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
6858            if !target_allowed {
6859                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6860                    &frame,
6861                    &target_module_id,
6862                    "admission_facts_target_not_listed",
6863                    "admission_facts_target_not_allowed",
6864                    format!(
6865                        "admission facts are not permitted for target module_id '{target_module_id}'"
6866                    ),
6867                )?]);
6868            }
6869
6870            // Keep the value opaque to subc. The downstream admission validator owns
6871            // schema and semantic checks; this daemon only enforces carrier authority
6872            // and the configured destination allowlist.
6873        }
6874
6875        // Scope admission, on the attested principal above and never on the
6876        // request body. The tag read here travels with the pending bind and is
6877        // compared with the published one at commit, so a sync between here
6878        // and the module's ack refuses the open instead of binding a stamp
6879        // that is no longer true.
6880        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
6881            None => (None, None, false),
6882            Some(selector) => {
6883                let owner_configured = match &selector.owner {
6884                    // A reserved owner counts as configured from before its
6885                    // process is spawned (see `SupervisorHandle::is_configured`).
6886                    // So an owner that has not synced its scopes yet is refused
6887                    // as retryable (`scope_not_synced`), not as one that will
6888                    // never sync.
6889                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
6890                    _ => false,
6891                };
6892                let mut scopes = self
6893                    .scopes
6894                    .write()
6895                    .unwrap_or_else(|poisoned| poisoned.into_inner());
6896                let admitted = crate::scopes::admission::admit_route(
6897                    &scopes,
6898                    &admission_registry,
6899                    &principal,
6900                    &target_module_id,
6901                    Some(selector),
6902                    owner_configured,
6903                    crate::scopes::admission::AdmissionMode::Open,
6904                )
6905                .map(|route| {
6906                    let admission = route.scope.expect("scoped admission");
6907                    let bound = scopes.reserve_bind(
6908                        &admission,
6909                        &principal,
6910                        ctx.connection_id,
6911                        selector.hold_presence,
6912                    );
6913                    (admission, bound)
6914                });
6915                match admitted {
6916                    Ok((admission, bound)) => {
6917                        (Some(bound), Some(admission.stamp), admission.stamp_required)
6918                    }
6919                    Err(refusal) => {
6920                        return Ok(vec![self.route_open_refusal_frame(
6921                            ctx,
6922                            &caller,
6923                            &frame,
6924                            &target_module_id,
6925                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6926                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6927                            refusal.message,
6928                        )?]);
6929                    }
6930                }
6931            }
6932        };
6933        // From here on a refusal names the scope by the stamp admission
6934        // issued, exactly as the `route.open accepted` line does.
6935        if let Some(stamp) = &scope_stamp {
6936            caller.scope = route_open_scope_label(stamp);
6937        }
6938        // Decided from the admitted stamp, before any field of it is stripped
6939        // for a target that lacks the capability to read it.
6940        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
6941            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
6942        }
6943
6944        // Allow resolvable missing-tail paths so a vanished directory does not
6945        // prevent reopening an existing session for cleanup. Binding does not
6946        // authorize creation of durable provider state.
6947        //
6948        // Resolve real paths rather than lexical cleanup: canonicalize the
6949        // longest existing ancestor and append the missing tail, retaining the
6950        // path's real existing ancestry even when a leaf is missing.
6951        timings.enter(RouteOpenPhase::ProjectRoot);
6952        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
6953            Ok(project) => project,
6954            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
6955        };
6956        timings.enter(RouteOpenPhase::Admission);
6957        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
6958            Ok(root) => root,
6959            Err(err) => {
6960                return Ok(vec![control_error_frame(
6961                    &frame,
6962                    "invalid_project_root",
6963                    err.to_string(),
6964                )?])
6965            }
6966        };
6967        // Compute compatibility project fields before stripping optional stamp
6968        // members. Preserve the canonical opener root and its project ID,
6969        // including absence. For rootless openers, use stamp workdir or `/`, and
6970        // opener ID, else stamp ID, else no ID. Emit these identity fields only
6971        // to targets without bind-no-project/v1.
6972        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
6973
6974        // Last gate before any relay work, and deliberately after the cheap
6975        // registry and availability checks above: those name a more precise
6976        // condition (unknown, removed, reloading) and a caller is better served
6977        // by the precise code than by this one.
6978        //
6979        // Everything below this point costs an egress permit, a reserved handle
6980        // pair and, if the module does not answer, the whole relay budget. The
6981        // reader no longer waits for that budget, so cap each target explicitly;
6982        // serial dispatch used to provide the accidental cap of one relay per
6983        // connection. Admission is a mutex-protected count and never waits.
6984        let _concurrency_guard = match self
6985            .route_bind_concurrency
6986            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
6987        {
6988            Ok(guard) => guard,
6989            Err(in_flight) => {
6990                return Ok(vec![self.route_open_target_capacity_refusal(
6991                    ctx,
6992                    &caller,
6993                    &frame,
6994                    &target_module_id,
6995                    in_flight,
6996                )?]);
6997            }
6998        };
6999
7000        // A module that has already burned the whole budget `threshold` times
7001        // in a row does not get to charge it again until a probe says it recovered.
7002        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
7003            RouteBindAdmission::Admitted { guard, probe } => {
7004                if probe {
7005                    info!(
7006                        module_id = %target_module_id,
7007                        connection_id = ctx.connection_id.get(),
7008                        "route.bind breaker half-open: admitting one probe"
7009                    );
7010                }
7011                guard
7012            }
7013            RouteBindAdmission::Refused {
7014                consecutive_timeouts,
7015                retry_in,
7016                probe_in_flight,
7017            } => {
7018                return Ok(vec![self.route_open_breaker_refusal_frame(
7019                    ctx,
7020                    &caller,
7021                    &frame,
7022                    &target_module_id,
7023                    consecutive_timeouts,
7024                    retry_in,
7025                    probe_in_flight,
7026                )?]);
7027            }
7028        };
7029
7030        let operator_app = self
7031            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
7032            .await;
7033        // Resolve the per-module budget here so the wait matches the operator's
7034        // intent for this specific target. A per-module override in
7035        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
7036        // daemons) wins over the daemon-wide default.
7037        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
7038        let relay_deadline = Instant::now() + route_bind_relay_timeout;
7039        let production_peer_build =
7040            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
7041        timings.enter(RouteOpenPhase::EgressReservation);
7042        let pending = match self
7043            .forwarding
7044            .begin_route_bind_relay_for(
7045                ctx.connection_id,
7046                ctx.egress.clone(),
7047                response_version(&frame),
7048                frame.header.corr,
7049                &target_module_id,
7050                principal.clone(),
7051                bound_scope,
7052                project_root,
7053                identity.harness.clone(),
7054                build_class,
7055                operator_app.clone(),
7056                crate::forwarding::RouteAuthority {
7057                    incarnation: self.supervisor.daemon_incarnation(),
7058                    caller: caller_capture
7059                        .as_ref()
7060                        .map(|caller| caller.authority.pair()),
7061                },
7062                relay_deadline,
7063                busy_refusals == Some(true),
7064                accepts_close_reasons,
7065            )
7066            .await
7067        {
7068            Ok(pending) => pending,
7069            Err(err) => {
7070                return Ok(vec![self.route_open_refusal_frame(
7071                    ctx,
7072                    &caller,
7073                    &frame,
7074                    &target_module_id,
7075                    "relay_reservation_failed",
7076                    forwarding_error_code(&err),
7077                    err.to_string(),
7078                )?])
7079            }
7080        };
7081        timings.enter(RouteOpenPhase::Admission);
7082        let crate::forwarding::PendingRouteBindRelay {
7083            endpoint,
7084            module_sink,
7085            negotiated_ver,
7086            client_channel,
7087            client_epoch,
7088            module_channel,
7089            module_epoch,
7090            corr: relay_corr,
7091            receiver,
7092        } = pending;
7093        let mut reservation =
7094            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
7095
7096        // Reserving egress can wait while a module reconnects or a swap cuts
7097        // over. Check the relay's captured connection, not the earlier by-id
7098        // lookup: the original module's flow/run capabilities cannot authorize
7099        // its replacement. The captured sink stays bound to that connection.
7100        let relay_registration = self
7101            .registry
7102            .route_registration_by_connection(endpoint.connection_id)
7103            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7104        let relay_capabilities = relay_registration
7105            .as_ref()
7106            .and_then(|registration| registration.capabilities.as_ref());
7107        if let Some(selector) = &scope {
7108            // Egress reservation may wait across a scope update. Recheck the
7109            // proof against the current record before sending the captured bind.
7110            if let Err(refusal) = self
7111                .scopes
7112                .read()
7113                .unwrap_or_else(|poisoned| poisoned.into_inner())
7114                .check_bind_proof(&principal, selector)
7115            {
7116                reservation.release_and_disarm();
7117                return Ok(vec![self.route_open_refusal_frame(
7118                    ctx,
7119                    &caller,
7120                    &frame,
7121                    &target_module_id,
7122                    refusal.code,
7123                    refusal.code,
7124                    refusal.message,
7125                )?]);
7126            }
7127        }
7128        if let Some(stamp) = scope_stamp.as_ref() {
7129            if let Err(refusal) = crate::scopes::check_target_required_stamp(
7130                stamp_required,
7131                &target_module_id,
7132                relay_capabilities,
7133            )
7134            .and_then(|()| {
7135                crate::scopes::check_target_flow_support(
7136                    stamp,
7137                    &target_module_id,
7138                    relay_capabilities,
7139                )
7140            })
7141            .and_then(|()| {
7142                crate::scopes::check_target_agent_run_support(
7143                    stamp,
7144                    &target_module_id,
7145                    relay_capabilities,
7146                )
7147            }) {
7148                reservation.release_and_disarm();
7149                return Ok(vec![self.route_open_refusal_frame(
7150                    ctx,
7151                    &caller,
7152                    &frame,
7153                    &target_module_id,
7154                    refusal.code,
7155                    refusal.code,
7156                    refusal.message,
7157                )?]);
7158            }
7159        }
7160
7161        // Older readers may reject unknown fields. Select optional fields from
7162        // the captured endpoint's declaration, including on unscoped binds.
7163        if scope_stamp
7164            .as_ref()
7165            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7166            && !crate::scopes::target_supports_federated(relay_capabilities)
7167        {
7168            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7169            scope_stamp = None;
7170        }
7171        if !relay_capabilities.is_some_and(|caps| {
7172            caps.provides
7173                .iter()
7174                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7175        }) {
7176            if let Some(stamp) = scope_stamp.as_mut() {
7177                stamp.workdir = None;
7178                stamp.project_id = None;
7179            }
7180        }
7181        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7182        // attribution. The run gate above has already required the target to
7183        // declare `worker-runs/v1`, which promises to read both
7184        // `on_behalf_of_agent` and `call_mode`.
7185        let worker_run = scope_stamp
7186            .as_ref()
7187            .is_some_and(crate::scopes::is_worker_run)
7188            && relay_capabilities.is_some_and(|caps| {
7189                caps.provides
7190                    .iter()
7191                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7192            });
7193        if !worker_run
7194            && !relay_capabilities.is_some_and(|caps| {
7195                caps.provides
7196                    .iter()
7197                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7198            })
7199        {
7200            if let Some(stamp) = scope_stamp.as_mut() {
7201                stamp.attributes.on_behalf_of_agent = None;
7202            }
7203        }
7204        if !relay_capabilities.is_some_and(|caps| {
7205            caps.provides
7206                .iter()
7207                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7208        }) {
7209            if let Some(stamp) = scope_stamp.as_mut() {
7210                stamp.attributes.flow_version = None;
7211                stamp.attributes.flow_code_hash = None;
7212                stamp.attributes.flow_install_id = None;
7213            }
7214        }
7215        let call_mode = if worker_run
7216            || relay_capabilities
7217                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7218        {
7219            Some(derive_call_mode(scope_stamp.as_ref()))
7220        } else {
7221            if let Some(stamp) = scope_stamp.as_mut() {
7222                stamp.expires_at_ms = None;
7223            }
7224            None
7225        };
7226
7227        debug!(
7228            connection_id = ctx.connection_id.get(),
7229            client_channel,
7230            client_epoch,
7231            module_channel,
7232            module_epoch,
7233            "reserved route handle pair"
7234        );
7235        // Rendered BEFORE the move into the relay, because the accept arm below
7236        // is where it is logged and the principal is gone by then.
7237        let route_principal_label = principal_label(&principal);
7238        let relay = ModuleControlRequest::RouteBind {
7239            route_channel: module_channel,
7240            epoch: module_epoch,
7241            target,
7242            identity,
7243            principal: Some(principal),
7244            consumer_capabilities,
7245            role_versions,
7246            admission_facts,
7247            scope: scope_stamp,
7248            call_mode,
7249        };
7250        let peer = RouteBindPeer::new()
7251            .with_observed_peer(
7252                relay_capabilities
7253                    .is_some_and(|caps| {
7254                        caps.provides
7255                            .iter()
7256                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7257                    })
7258                    .then(|| {
7259                        self.observed_peers
7260                            .lock()
7261                            .unwrap_or_else(|p| p.into_inner())
7262                            .get(&ctx.connection_id)
7263                            .cloned()
7264                            .unwrap_or_else(ObservedPeer::unobserved)
7265                    }),
7266            )
7267            .with_operator_app(
7268                self.connection_operator_app(operator_app.as_ref())
7269                    .filter(|_| {
7270                        relay_capabilities.is_some_and(|caps| {
7271                            caps.provides
7272                                .iter()
7273                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7274                        })
7275                    }),
7276            )
7277            .with_caller(caller_for_target(
7278                caller_capture.as_ref(),
7279                relay_capabilities,
7280                &target_module_id,
7281            ))
7282            .with_peer_build(
7283                (production_peer_build
7284                    && relay_capabilities.is_some_and(|caps| {
7285                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7286                    }))
7287                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7288            );
7289        let relay_body = crate::bind_compat::encode_bind(
7290            &relay,
7291            &peer,
7292            &legacy_bind_project,
7293            relay_capabilities,
7294        )
7295        .map_err(|err| {
7296            RouterError::backend(
7297                0,
7298                frame.header.corr,
7299                format!("failed to encode route.bind request: {err}"),
7300            )
7301        })?;
7302        let relay_frame = Frame::build_with_version(
7303            negotiated_ver,
7304            FrameType::Request,
7305            control_flags(),
7306            0,
7307            0,
7308            relay_corr,
7309            relay_body,
7310        )
7311        .map_err(RouterError::FrameBuild)?;
7312
7313        timings.enter(RouteOpenPhase::BindSend);
7314        let sent = module_sink.send(relay_frame).await;
7315        timings.enter(RouteOpenPhase::Admission);
7316        if let Err(err) = sent {
7317            reservation.release_and_disarm();
7318            return Ok(vec![self.route_open_refusal_frame(
7319                ctx,
7320                &caller,
7321                &frame,
7322                &target_module_id,
7323                "relay_send_failed",
7324                "target_unavailable",
7325                err.to_string(),
7326            )?]);
7327        }
7328
7329        #[cfg(test)]
7330        if let Some(hold) = &self.route_bind_relay_sent_hold {
7331            // First wait: tell the test the bind is queued. Second wait: stay
7332            // here until the test has driven whatever it wants to happen
7333            // between queueing the bind and marking it enqueued.
7334            hold.wait().await;
7335            hold.wait().await;
7336        }
7337
7338        // A missing relay is not by itself an abandoned bind: the module may
7339        // already have acked it and the route may be committed. Only a relay
7340        // dropped without any module reply needs this GOODBYE; one a reply
7341        // settled has already had its GOODBYE decided by the reply path.
7342        if self
7343            .forwarding
7344            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7345            .map_err(RouterError::Forwarding)?
7346            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7347        {
7348            self.send_abandoned_route_bind_goodbye(
7349                &module_sink,
7350                negotiated_ver,
7351                module_channel,
7352                module_epoch,
7353            );
7354        }
7355
7356        timings.enter(RouteOpenPhase::BindAckWait);
7357        let outcome = timeout_at(relay_deadline, receiver).await;
7358        timings.enter(RouteOpenPhase::Admission);
7359        match outcome {
7360            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7361                reservation.disarm();
7362                if breaker.record_accepted() {
7363                    info!(
7364                        module_id = %target_module_id,
7365                        "route.bind breaker closed: the probe was accepted"
7366                    );
7367                }
7368                self.observe_route_open_accept(
7369                    ctx,
7370                    &target_module_id,
7371                    &route_principal_label,
7372                    &caller.scope,
7373                );
7374                Ok(Vec::new())
7375            }
7376            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7377                reservation.release_and_disarm();
7378                // A module that says no in microseconds is healthy. Rejection
7379                // is a different condition with its own refusal and must not
7380                // move the breaker.
7381                breaker.record_inconclusive();
7382                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7383            }
7384            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7385                reservation.release_and_disarm();
7386                breaker.record_inconclusive();
7387                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7388            }
7389            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7390                reservation.release_and_disarm();
7391                breaker.record_inconclusive();
7392                // Fires when the module's connection closes while a relayed
7393                // bind is pending -- typically a caller racing a module restart
7394                // whose bind was relayed BEFORE the drain mark went up. Logged
7395                // because the caller sees only its own error and the fleet has
7396                // already spent one diagnosis round unable to tell this arm
7397                // from a relay timeout without daemon-side evidence.
7398                tracing::warn!(
7399                    module_id = %target_module_id,
7400                    "route.bind relay abandoned: {message}"
7401                );
7402                Ok(vec![self.route_open_refusal_frame(
7403                    ctx,
7404                    &caller,
7405                    &frame,
7406                    &target_module_id,
7407                    "relay_abandoned",
7408                    "target_unavailable",
7409                    message,
7410                )?])
7411            }
7412            Ok(Err(_)) => {
7413                reservation.release_and_disarm();
7414                breaker.record_inconclusive();
7415                Ok(vec![self.route_open_refusal_frame(
7416                    ctx,
7417                    &caller,
7418                    &frame,
7419                    &target_module_id,
7420                    "relay_waiter_canceled",
7421                    "target_unavailable",
7422                    "route.bind relay waiter was canceled before the module responded",
7423                )?])
7424            }
7425            Err(_) => {
7426                reservation.release_and_disarm();
7427                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7428                // answer at all is the one condition a fast refusal can
7429                // usefully stand in for; every other arm already answered.
7430                if let Some(opened) = breaker.record_timeout(
7431                    self.route_bind_breaker_threshold,
7432                    self.route_bind_breaker_cooldown,
7433                ) {
7434                    warn!(
7435                        module_id = %target_module_id,
7436                        consecutive_timeouts = opened.consecutive_timeouts,
7437                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7438                        reopened_after_probe = opened.reopened_after_probe,
7439                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7440                    );
7441                }
7442                // The generous budget just burned to no answer: the module is
7443                // registered and its connection is up, but its bind handler sat
7444                // on the ack for the full budget (warm-on-bind, cold configure,
7445                // or a wedged handler). Every earlier unavailability shape
7446                // fast-refuses BEFORE the relay, so this arm firing means the
7447                // slowness is module-side -- log it so the per-module timeline
7448                // is reconstructable without client audit rows.
7449                tracing::warn!(
7450                    module_id = %target_module_id,
7451                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7452                    "route.bind relay timed out: module did not ack within budget"
7453                );
7454                Ok(vec![self.route_open_refusal_frame(
7455                    ctx,
7456                    &caller,
7457                    &frame,
7458                    &target_module_id,
7459                    "relay_timed_out",
7460                    "module_timeout",
7461                    format!(
7462                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7463                        route_bind_relay_timeout
7464                    ),
7465                )?])
7466            }
7467        }
7468    }
7469
7470    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7471        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7472            snapshot: self.supervisor.spawn_snapshot(),
7473        };
7474        Ok(vec![control_response_body_frame(
7475            &frame,
7476            &response,
7477            "ClientControlResponse::SupervisorSpawnSnapshot",
7478        )?])
7479    }
7480
7481    fn handle_supervisor_spawn_subscribe(
7482        &self,
7483        ctx: &RouteCtx,
7484        frame: Frame,
7485        since: Option<SpawnCursor>,
7486    ) -> Result<Vec<Frame>, RouterError> {
7487        match self.supervisor.subscribe_spawns(
7488            ctx.connection_id,
7489            frame.header.corr,
7490            response_version(&frame),
7491            since,
7492            ctx.egress.clone(),
7493        ) {
7494            Ok(()) => Ok(Vec::new()),
7495            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7496                Ok(vec![control_error_body_frame(
7497                    &frame,
7498                    ErrorBody {
7499                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7500                        message: "spawn cursor belongs to a different daemon incarnation"
7501                            .to_string(),
7502                        detail: Some(serde_json::json!({
7503                            "current_daemon_incarnation": current
7504                        })),
7505                    },
7506                )?])
7507            }
7508            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7509                &frame,
7510                ErrorBody {
7511                    code: "spawn_cursor_too_old".to_string(),
7512                    message: "spawn cursor predates the retained event ring".to_string(),
7513                    detail: Some(serde_json::json!({
7514                        "oldest_retained_cursor": oldest
7515                    })),
7516                },
7517            )?]),
7518            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7519                0,
7520                frame.header.corr,
7521                format!("failed to open supervisor spawn subscription: {error}"),
7522            )),
7523        }
7524    }
7525
7526    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7527        // Status/configuration snapshots may wait on synchronous supervisor
7528        // locks. Keep that work off the connection's async runtime thread.
7529        let handler = self.clone();
7530        let runtime = tokio::runtime::Handle::current();
7531        // The blocking pool does not inherit the control request's tracing
7532        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7533        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7534        let corr = frame.header.corr;
7535        tokio::task::spawn_blocking(move || {
7536            runtime.block_on(
7537                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7538                    .with_subscriber(subscriber),
7539            )
7540        })
7541        .await
7542        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7543    }
7544
7545    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7546        use crate::config_gate::runtime::ApprovedDaemonView;
7547        let publication = self
7548            .config_runtime
7549            .as_ref()
7550            .and_then(|owner| owner.polled_snapshot().ok());
7551        let approved = publication
7552            .as_ref()
7553            .map(|view| view.approved_daemon.clone())
7554            .unwrap_or_else(|| {
7555                if self.config_runtime.is_some() {
7556                    ApprovedDaemonView::Unavailable
7557                } else {
7558                    ApprovedDaemonView::NotStamped
7559                }
7560            });
7561        let generation = self
7562            .registry
7563            .generation()
7564            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7565        let supervised = self.supervisor.list();
7566        let mut statuses = BTreeMap::new();
7567        let mut not_running = BTreeSet::new();
7568        for module in &supervised {
7569            let status = module.status_for_control("list").map_err(|err| {
7570                RouterError::backend(
7571                    0,
7572                    frame.header.corr,
7573                    format!("failed to read supervisor status: {err}"),
7574                )
7575            })?;
7576            if !status.enabled || !status.process_alive {
7577                not_running.insert(module.module_id().to_owned());
7578            }
7579            statuses.insert(module.module_id().to_owned(), status);
7580        }
7581        // Legacy per-process diagnostics keep their shared optional budget.
7582        // The cached tree and accounting export below does not spend it.
7583        let mut process_resources = BTreeMap::new();
7584        for module in &supervised {
7585            process_resources.insert(
7586                module.module_id().to_owned(),
7587                crate::subtree_resources::read_process(module.clone()).await,
7588            );
7589        }
7590        // Image evidence uses the same optional deadline, but an exhausted
7591        // budget must not suppress the committed resource view.
7592        let mut image_readings = BTreeMap::new();
7593        for module in &supervised {
7594            image_readings.insert(
7595                module.module_id().to_owned(),
7596                module.running_image_agreement().await,
7597            );
7598        }
7599        let readings = self.resource_tracker.list(supervised.clone());
7600        let mut modules = Vec::new();
7601        for module in supervised {
7602            let status = statuses
7603                .remove(module.module_id())
7604                .expect("each supervised module has a status snapshot");
7605            let (configured, _) = module.configuration().map_err(|err| {
7606                RouterError::backend(
7607                    0,
7608                    frame.header.corr,
7609                    format!("failed to read module configuration: {err}"),
7610                )
7611            })?;
7612            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7613                RouterError::backend(
7614                    0,
7615                    frame.header.corr,
7616                    format!("failed to read retry time: {err}"),
7617                )
7618            })?;
7619            let image = image_readings
7620                .remove(module.module_id())
7621                .expect("each supervised module has an image snapshot");
7622            let resources = process_resources.remove(module.module_id());
7623            let mut verdict =
7624                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7625            verdict.spec = Some(launch_spec_agreement(
7626                &configured,
7627                status.process_alive,
7628                status.launch_spec_digest.as_ref(),
7629            ));
7630            let pending_reload = Some(verdict);
7631            let pending_entry = match &approved {
7632                ApprovedDaemonView::Approved { config, .. } => config
7633                    .modules
7634                    .iter()
7635                    .find(|m| m.module_id == module.module_id()),
7636                _ => None,
7637            };
7638            let pending = self
7639                .pending_module_fields(
7640                    &module,
7641                    pending_entry,
7642                    false,
7643                    Self::registration_channel_in_force(
7644                        publication
7645                            .as_ref()
7646                            .and_then(|view| view.registration_declaration(module.module_id()))
7647                            .as_deref(),
7648                        pending_entry.map(|entry| entry.registration_channel),
7649                    ),
7650                    publication.as_deref(),
7651                )
7652                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7653            let script = configured.script.as_ref().map(|entry| {
7654                let approved = self
7655                    .config_runtime
7656                    .as_ref()
7657                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7658                crate::supervise::script::status(entry, approved.as_ref())
7659            });
7660            let configured_enabled = match &approved {
7661                ApprovedDaemonView::Approved {
7662                    config: approved, ..
7663                } => approved
7664                    .modules
7665                    .iter()
7666                    .find(|module| module.module_id == status.module_id)
7667                    .map(|module| module.enabled),
7668                ApprovedDaemonView::NotStamped => self
7669                    .capability_evaluator
7670                    .configured_enabled(&status.module_id),
7671                ApprovedDaemonView::Unavailable => None,
7672            };
7673            let admission_refused = status
7674                .admission_refused
7675                .clone()
7676                .filter(|_| status.enabled && !status.process_alive)
7677                .filter(|_| {
7678                    publication
7679                        .as_ref()
7680                        .and_then(|view| view.registration_declaration(&status.module_id))
7681                        .as_deref()
7682                        == Some("undeclared")
7683                });
7684            // Keep the retired policy field on the wire for one release so
7685            // existing status consumers still receive the platform policy.
7686            let mut entry = SupervisorEntry::new(
7687                status.module_id,
7688                status.state.to_string(),
7689                status.enabled,
7690                status.live,
7691                status.health.status,
7692            )
7693            .with_configured_enabled(configured_enabled)
7694            .with_script(script)
7695            .with_admission_refused(admission_refused)
7696            .with_next_retry_at_ms(next_retry_at_ms)
7697            .with_launch_nonce_env(Some(!cfg!(unix)))
7698            .with_launch_nonce_source(status.launch_nonce_source)
7699            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7700            .with_protocol(status.protocol)
7701            .with_pending_reload(pending_reload)
7702            .with_last_probe_ms(status.health.last_probe_ms)
7703            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7704            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7705            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7706            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7707            .with_restart_count(Some(status.restart_count))
7708            .with_max_restarts(Some(status.max_restarts))
7709            .with_lifetime_restarts(Some(status.lifetime_restarts))
7710            .with_spawn_generation(Some(status.spawn_generation))
7711            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7712            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7713            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7714            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7715            .with_resources(resources);
7716            entry.pending = pending;
7717            modules.push(entry);
7718        }
7719        for module in &mut modules {
7720            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7721                module.tree = tree.clone();
7722                module.cpu_last_hour = hour.clone();
7723            }
7724            module.tree_unavailable = readings
7725                .reasons
7726                .get(&module.module_id)
7727                .map(|reason| (*reason).to_owned());
7728            if module.tree.is_none() {
7729                module.tree_unavailable = Some(
7730                    if not_running.contains(&module.module_id) {
7731                        "not_running"
7732                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7733                        reason
7734                    } else {
7735                        "not_yet_measured"
7736                    }
7737                    .to_owned(),
7738                );
7739            }
7740        }
7741        let response = ClientControlResponse::SupervisorList {
7742            generation,
7743            modules,
7744            daemon: readings.daemon,
7745            agent_commands: readings.agent_commands,
7746        };
7747        Ok(vec![control_response_body_frame(
7748            &frame,
7749            &response,
7750            "ClientControlResponse::SupervisorList",
7751        )?])
7752    }
7753
7754    fn handle_supervisor_stderr_tail(
7755        &self,
7756        frame: Frame,
7757        module_id: String,
7758        max_lines: Option<u32>,
7759        max_bytes: Option<u32>,
7760    ) -> Result<Vec<Frame>, RouterError> {
7761        let Some(module) = self.supervisor.get(&module_id) else {
7762            return Ok(vec![control_error_frame(
7763                &frame,
7764                "unknown_module",
7765                format!("module_id '{module_id}' is not supervised"),
7766            )?]);
7767        };
7768
7769        let snapshot = module.stderr_tail(
7770            max_lines.map(|value| value as usize),
7771            max_bytes.map(|value| value as usize),
7772        );
7773
7774        let response = ClientControlResponse::SupervisorStderrTail {
7775            module_id,
7776            tail: StderrTail {
7777                capture: match snapshot.capture {
7778                    CaptureState::Captured => StderrCaptureState::Captured,
7779                    CaptureState::Incomplete { reason } => {
7780                        StderrCaptureState::Incomplete { reason }
7781                    }
7782                    CaptureState::NotCaptured { reason } => {
7783                        StderrCaptureState::NotCaptured { reason }
7784                    }
7785                },
7786                entries: snapshot
7787                    .entries
7788                    .into_iter()
7789                    .map(|entry| match entry {
7790                        TailEntry::Line {
7791                            text,
7792                            truncated,
7793                            at_ms,
7794                        } => StderrTailEntry::Line {
7795                            text,
7796                            truncated,
7797                            at_ms,
7798                        },
7799                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7800                    })
7801                    .collect(),
7802                dropped_lines: snapshot.dropped_lines,
7803            },
7804        };
7805        Ok(vec![control_response_body_frame(
7806            &frame,
7807            &response,
7808            "ClientControlResponse::SupervisorStderrTail",
7809        )?])
7810    }
7811
7812    async fn observe_control_wait<F: std::future::Future>(
7813        &self,
7814        ctx: &RouteCtx,
7815        target: Option<&str>,
7816        kind: &'static str,
7817        future: F,
7818    ) -> F::Output {
7819        self.counters
7820            .observe_reader_wait(
7821                || {
7822                    let module = self
7823                        .forwarding
7824                        .module_id_for_connection(ctx.connection_id)
7825                        .ok()
7826                        .flatten();
7827                    let principal = if module.is_some() { "module" } else { "direct" };
7828                    (
7829                        self.resolve_reader_wait_target(kind, target)
7830                            .or(module)
7831                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7832                        principal.into(),
7833                    )
7834                },
7835                kind,
7836                future,
7837            )
7838            .await
7839    }
7840
7841    /// Resolve the reader-wait module ID only from supervisor or registry
7842    /// records; never attribute a wait from the request selector alone.
7843    pub(crate) fn resolve_reader_wait_target(
7844        &self,
7845        op: &str,
7846        selector: Option<&str>,
7847    ) -> Option<String> {
7848        let selector = selector?;
7849        match op {
7850            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7851                .supervisor
7852                .get(selector)
7853                .map(|module| module.module_id().to_owned()),
7854            ops::SUPERVISOR_HEALTH_PROBE => self
7855                .registry
7856                .get_module(selector)
7857                .ok()
7858                .flatten()
7859                .map(|registration| registration.manifest.module_id),
7860            _ => None,
7861        }
7862    }
7863
7864    async fn handle_supervisor_terminals(
7865        &self,
7866        ctx: &RouteCtx,
7867        frame: Frame,
7868        module_id: String,
7869    ) -> Result<Vec<Frame>, RouterError> {
7870        let Some(module) = self.supervisor.get(&module_id) else {
7871            return Ok(vec![control_error_frame(
7872                &frame,
7873                "unknown_module",
7874                format!("module_id '{module_id}' is not supervised"),
7875            )?]);
7876        };
7877
7878        // The journal read runs on a blocking thread: it can be megabytes of
7879        // file I/O and must not occupy a runtime worker.
7880        let terminals = self
7881            .observe_control_wait(
7882                ctx,
7883                Some(module.module_id()),
7884                ops::SUPERVISOR_TERMINALS,
7885                module.read_durable_terminal_history(),
7886            )
7887            .await
7888            .map_err(|error| {
7889                RouterError::backend(
7890                    0,
7891                    frame.header.corr,
7892                    format!("failed to read terminal history: {error}"),
7893                )
7894            })?;
7895        let response = ClientControlResponse::SupervisorTerminals {
7896            module_id,
7897            terminals,
7898        };
7899        Ok(vec![control_response_body_frame(
7900            &frame,
7901            &response,
7902            "ClientControlResponse::SupervisorTerminals",
7903        )?])
7904    }
7905
7906    fn handle_supervisor_routes(
7907        &self,
7908        frame: Frame,
7909        module_id: Option<String>,
7910    ) -> Result<Vec<Frame>, RouterError> {
7911        let modules = self
7912            .forwarding
7913            .route_census(module_id.as_deref())
7914            .map_err(RouterError::Forwarding)?
7915            .into_iter()
7916            .map(|(module_id, routes)| SupervisorRouteModule {
7917                module_id,
7918                routes: routes
7919                    .into_iter()
7920                    .map(|route| SupervisorRoute {
7921                        consumer: match route.principal {
7922                            Principal::Reserved { module_id } => {
7923                                SupervisorRouteConsumer::Reserved { module_id }
7924                            }
7925                            Principal::Direct | Principal::Unverified => {
7926                                SupervisorRouteConsumer::Direct {
7927                                    connection_id: route.goodbye_target.connection_id.get(),
7928                                }
7929                            }
7930                        },
7931                        age_ms: Instant::now()
7932                            .saturating_duration_since(route.bound_at)
7933                            .as_millis()
7934                            .try_into()
7935                            .unwrap_or(u64::MAX),
7936                        draining: route.draining,
7937                        drain_reason: route.drain_reason,
7938                    })
7939                    .collect(),
7940            })
7941            .collect();
7942        let response = ClientControlResponse::SupervisorRoutes { modules };
7943        Ok(vec![control_response_body_frame(
7944            &frame,
7945            &response,
7946            "ClientControlResponse::SupervisorRoutes",
7947        )?])
7948    }
7949
7950    fn running_registration_method(
7951        &self,
7952        module: &str,
7953    ) -> Option<subc_control::RegistrationMethod> {
7954        let registration = self.registry.get_module(module).ok()??;
7955        let connection = registration.connection_id;
7956        let channel = self.supervisor.registration_spawn(connection).is_some();
7957        let nonce = if channel {
7958            None
7959        } else {
7960            self.hello_launch_nonces
7961                .lock()
7962                .ok()?
7963                .nonce(connection)
7964                .map(str::to_owned)
7965        };
7966        if !channel && nonce.is_none() {
7967            return None;
7968        }
7969        self.supervisor
7970            .registration_snapshot_is_current_live(
7971                &self.registry,
7972                module,
7973                connection,
7974                nonce.as_deref(),
7975            )
7976            .then_some(if channel {
7977                subc_control::RegistrationMethod::Channel
7978            } else {
7979                subc_control::RegistrationMethod::Nonce
7980            })
7981    }
7982
7983    async fn handle_supervisor_provenance(
7984        &self,
7985        ctx: &RouteCtx,
7986        frame: Frame,
7987        module_id: Option<String>,
7988    ) -> Result<Vec<Frame>, RouterError> {
7989        let targeted = module_id.is_some();
7990        let selected = if let Some(module_id) = module_id {
7991            let Some(module) = self.supervisor.get(&module_id) else {
7992                return Ok(vec![control_error_frame(
7993                    &frame,
7994                    "unknown_module",
7995                    format!("module_id '{module_id}' is not supervised"),
7996                )?]);
7997            };
7998            vec![module]
7999        } else {
8000            self.supervisor.list()
8001        };
8002
8003        let target = targeted.then(|| selected[0].module_id());
8004        let declarations = if let Some(owner) = &self.config_runtime {
8005            owner
8006                .on_blocking(|owner| owner.registration_declarations())
8007                .await
8008                .ok()
8009        } else {
8010            None
8011        };
8012        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
8013            let mut modules = Vec::with_capacity(selected.len());
8014            let mut extensions = Vec::with_capacity(selected.len());
8015            for module in &selected {
8016                let (status, observed_image) = module
8017                    .status_and_running_image_agreement()
8018                    .await
8019                    .map_err(|err| {
8020                        RouterError::backend(
8021                            0,
8022                            frame.header.corr,
8023                            format!("failed to read supervisor status: {err}"),
8024                        )
8025                    })?;
8026                let module_declared = self
8027                    .registry
8028                    .get_module(&status.module_id)
8029                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8030                    .and_then(|registration| registration.manifest.provenance)
8031                    .map(|build| ModuleDeclaredProvenance::Reported { build })
8032                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
8033                #[cfg(test)]
8034                let running_image = match &self.provenance_probe_override {
8035                    Some(result) => result.clone(),
8036                    None => observed_image,
8037                };
8038                #[cfg(not(test))]
8039                let running_image = observed_image;
8040                let registration = self.running_registration_method(&status.module_id);
8041                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
8042                    .with_registration(registration);
8043                extension.registration_declaration = declarations
8044                    .as_ref()
8045                    .and_then(|entries| entries.get(&status.module_id))
8046                    .cloned();
8047                if status.process_alive && status.registration_declaration.is_some() {
8048                    extension.registration_declaration = status.registration_declaration.clone();
8049                }
8050                extensions.push(extension);
8051                modules.push(SupervisorModuleProvenance {
8052                    module_id: status.module_id,
8053                    module_declared,
8054                    daemon_observed: SupervisorObservedProcess {
8055                        launch_nonce_source: status.launch_nonce_source,
8056                        pid: status.pid,
8057                        spawned_at_ms: status.spawned_at_ms,
8058                        spawned_from: status.spawned_from,
8059                        running_image,
8060                    },
8061                });
8062            }
8063            let daemon = SupervisorDaemonProvenance {
8064                daemon_build: self.daemon_provenance.build.clone(),
8065                daemon_observed: DaemonObservedProcess {
8066                    pid: self.daemon_provenance.pid,
8067                    started_at_ms: self
8068                        .daemon_provenance
8069                        .start_clock
8070                        .map(|clock| clock.started_at_ms())
8071                        .or(self.daemon_provenance.started_at_ms),
8072                    running_image: self
8073                        .daemon_provenance
8074                        .probe
8075                        .observe(
8076                            self.daemon_provenance.pid,
8077                            self.daemon_provenance.executable_path.as_deref(),
8078                            self.daemon_provenance.executable_identity.clone(),
8079                            self.daemon_provenance.process_start_time,
8080                        )
8081                        .await,
8082                },
8083            };
8084            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8085            let mut response = serde_json::to_value(response)
8086                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8087            for (entry, extension) in response["modules"]
8088                .as_array_mut()
8089                .expect("provenance modules are an array")
8090                .iter_mut()
8091                .zip(extensions)
8092            {
8093                extension.write_to(entry).map_err(|error| {
8094                    RouterError::backend(0, frame.header.corr, error.to_string())
8095                })?;
8096            }
8097            Ok(vec![control_response_body_frame(
8098                &frame,
8099                &response,
8100                "ClientControlResponse::SupervisorProvenance",
8101            )?])
8102        })
8103        .await
8104    }
8105
8106    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8107        self.refresh_capability_requirements();
8108        let publication = self
8109            .config_runtime
8110            .as_ref()
8111            .and_then(|owner| owner.polled_snapshot().ok());
8112        let generation = self
8113            .registry
8114            .generation()
8115            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8116        let modules = self
8117            .supervisor
8118            .list()
8119            .into_iter()
8120            .map(|module| {
8121                let status = module.status_for_control("health").map_err(|err| {
8122                    RouterError::backend(
8123                        0,
8124                        frame.header.corr,
8125                        format!("failed to read supervisor health: {err}"),
8126                    )
8127                })?;
8128                let module_id = status.module_id;
8129                let capability_detail = self
8130                    .capability_evaluator
8131                    .required_problem_detail(&module_id);
8132                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8133                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8134                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8135                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8136                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8137                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8138                Ok(SupervisorHealthEntry {
8139                    module_id,
8140                    status: status.health.status,
8141                    detail: append_capability_problem_detail(
8142                        status.health.detail,
8143                        capability_detail,
8144                    ),
8145                    metrics: status.health.metrics,
8146                    consecutive_failures: status.health.consecutive_failures,
8147                    late_answer_count: status.health.late_answer_count,
8148                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8149                    last_action: status.health.last_action,
8150                    last_action_ms: status.health.last_action_ms,
8151                    last_probe_ms: status.health.last_probe_ms,
8152                })
8153            })
8154            .collect::<Result<Vec<_>, RouterError>>()?;
8155        let response = ClientControlResponse::SupervisorHealth {
8156            generation,
8157            modules,
8158        };
8159        Ok(vec![control_response_body_frame(
8160            &frame,
8161            &response,
8162            "ClientControlResponse::SupervisorHealth",
8163        )?])
8164    }
8165
8166    async fn handle_supervisor_restart(
8167        &self,
8168        frame: Frame,
8169        module_id: String,
8170        drain_timeout_ms: Option<u64>,
8171        requester: Principal,
8172    ) -> Result<Vec<Frame>, RouterError> {
8173        let operation_lock = self.supervisor.operation_lock();
8174        let _operation_guard = operation_lock.lock().await;
8175        let Some(module) = self.supervisor.get(&module_id) else {
8176            return Ok(vec![control_error_frame(
8177                &frame,
8178                "unknown_module",
8179                format!("module_id '{module_id}' is not supervised"),
8180            )?]);
8181        };
8182
8183        self.route_outages.mark_operator_action(&module_id);
8184        if let Err(err) = module
8185            .restart_requested(drain_timeout_ms, Some(requester))
8186            .await
8187        {
8188            self.route_outages
8189                .operator_action_ended_unrefused(&module_id);
8190            let (code, message) = match err {
8191                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8192                crate::supervise::SuperviseError::Disabled { .. } => {
8193                    ("module_disabled", err.to_string())
8194                }
8195                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8196                    ("swap_in_progress", err.to_string())
8197                }
8198                _ => (
8199                    "target_unavailable",
8200                    format!("failed to restart module_id '{module_id}': {err}"),
8201                ),
8202            };
8203            return Ok(vec![control_error_frame(&frame, code, message)?]);
8204        }
8205
8206        let response = ClientControlResponse::SupervisorAck {
8207            module_id,
8208            applied: true,
8209        };
8210        Ok(vec![control_response_body_frame(
8211            &frame,
8212            &response,
8213            "ClientControlResponse::SupervisorAck",
8214        )?])
8215    }
8216
8217    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8218    /// when the old process has finished draining: a caller whose own lane
8219    /// rides the old process must get its reply before that drain waits on it.
8220    async fn handle_supervisor_swap(
8221        &self,
8222        frame: Frame,
8223        module_id: String,
8224        ready_timeout_ms: Option<u64>,
8225        requester: Principal,
8226    ) -> Result<Vec<Frame>, RouterError> {
8227        // The daemon-wide operation lock is held only to resolve the handle,
8228        // not across the swap. The swap can take its whole readiness budget,
8229        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8230        // holding it here would park an operator's stop behind the swap it is
8231        // meant to abort. A rescan or stop that reaches the module during the
8232        // swap is served by the swap itself (see `supervise_swap`).
8233        let module = {
8234            let operation_lock = self.supervisor.operation_lock();
8235            let _operation_guard = operation_lock.lock().await;
8236            self.supervisor.get(&module_id)
8237        };
8238        let Some(module) = module else {
8239            return Ok(vec![control_error_frame(
8240                &frame,
8241                "unknown_module",
8242                format!("module_id '{module_id}' is not supervised"),
8243            )?]);
8244        };
8245
8246        self.route_outages.mark_operator_action(&module_id);
8247        if let Err(err) = module
8248            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8249            .await
8250        {
8251            self.route_outages
8252                .operator_action_ended_unrefused(&module_id);
8253            use crate::supervise::SuperviseError;
8254            let message = err.to_string();
8255            let error = match err {
8256                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8257                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8258                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8259                    code: "swap_refused".to_string(),
8260                    message,
8261                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8262                },
8263                SuperviseError::SwapFailed {
8264                    arm,
8265                    candidate_exit,
8266                    ..
8267                } => ErrorBody {
8268                    code: "swap_failed".to_string(),
8269                    message,
8270                    detail: Some(serde_json::json!({
8271                        "arm": arm.as_str(),
8272                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8273                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8274                    })),
8275                },
8276                _ => ErrorBody::new(
8277                    "target_unavailable",
8278                    format!("failed to swap module_id '{module_id}': {message}"),
8279                ),
8280            };
8281            return Ok(vec![control_error_body_frame(&frame, error)?]);
8282        }
8283        // A completed swap kept the incumbent serving until cutover, so it
8284        // usually opened no outage; a mark left behind would make the next,
8285        // unrelated outage read as requested.
8286        self.route_outages
8287            .operator_action_ended_unrefused(&module_id);
8288
8289        let response = ClientControlResponse::SupervisorAck {
8290            module_id,
8291            applied: true,
8292        };
8293        Ok(vec![control_response_body_frame(
8294            &frame,
8295            &response,
8296            "ClientControlResponse::SupervisorAck",
8297        )?])
8298    }
8299
8300    async fn handle_supervisor_reload(
8301        &self,
8302        frame: Frame,
8303        module_id: String,
8304        requester: Principal,
8305    ) -> Result<Vec<Frame>, RouterError> {
8306        let operation_lock = self.supervisor.operation_lock();
8307        let _operation_guard = operation_lock.lock().await;
8308        let Some(module) = self.supervisor.get(&module_id) else {
8309            return Ok(vec![control_error_frame(
8310                &frame,
8311                "unknown_module",
8312                format!("module_id '{module_id}' is not supervised"),
8313            )?]);
8314        };
8315
8316        self.route_outages.mark_operator_action(&module_id);
8317        if let Err(err) = module.reload_requested(Some(requester)).await {
8318            self.route_outages
8319                .operator_action_ended_unrefused(&module_id);
8320            let (code, message) = match err {
8321                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8322                crate::supervise::SuperviseError::Disabled { .. } => {
8323                    ("module_disabled", err.to_string())
8324                }
8325                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8326                    ("swap_in_progress", err.to_string())
8327                }
8328                _ => (
8329                    "reload_failed",
8330                    format!("failed to reload module_id '{module_id}': {err}"),
8331                ),
8332            };
8333            return Ok(vec![control_error_frame(&frame, code, message)?]);
8334        }
8335
8336        let response = ClientControlResponse::SupervisorAck {
8337            module_id,
8338            applied: true,
8339        };
8340        Ok(vec![control_response_body_frame(
8341            &frame,
8342            &response,
8343            "ClientControlResponse::SupervisorAck",
8344        )?])
8345    }
8346
8347    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8348    /// the configuration comes from and whether to apply it; every mode then
8349    /// runs the same comparison, so a preview describes the apply it previews.
8350    async fn handle_supervisor_rescan(
8351        &self,
8352        frame: Frame,
8353        mode: RescanMode,
8354        requester: Principal,
8355    ) -> Result<Vec<Frame>, RouterError> {
8356        let preview = mode.previews();
8357        let Some(context) = self.rescan.clone() else {
8358            return Ok(vec![control_error_frame(
8359                &frame,
8360                "rescan_unavailable",
8361                "the daemon was not started with a reloadable config path".to_string(),
8362            )?]);
8363        };
8364
8365        let _rescan_guard = context.rescan_lock.lock().await;
8366        let rescan_checked::RescanInput {
8367            config: loaded,
8368            approved_preview,
8369            guard: _operation_guard,
8370        } = match self.rescan_input(&mode, &context).await {
8371            Ok(input) => input,
8372            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
8373        };
8374        // `load` reports a missing file as Ok(None), which is correct at boot
8375        // (no config, nothing to supervise) and catastrophic here: rescan treats
8376        // "not in the config" as "remove it", so an absent file would read as an
8377        // empty module list and retire the entire running fleet. An editor
8378        // writing via write-new-then-rename, or a half-finished edit, is enough
8379        // to open that window. Refuse instead: a config that cannot be read
8380        // carries no instruction to remove anything.
8381        let Some((config, activity_config)) = loaded else {
8382            return Ok(vec![control_error_frame(
8383                &frame,
8384                "invalid_daemon_config",
8385                format!(
8386                    "daemon config not found at {}; refusing to rescan (an absent config would \
8387                     retire every supervised module)",
8388                    context.config_path.display()
8389                ),
8390            )?]);
8391        };
8392        let (
8393            configured_port,
8394            storage_config,
8395            admission_facts_carrier_module_id,
8396            admission_facts_targets,
8397            scope_authority_owners,
8398            federated_scope_owner,
8399            privileged_operator_prompt,
8400            modules,
8401            reserved_capabilities,
8402        ) = (
8403            config.port,
8404            config.storage,
8405            config.admission_facts_carrier_module_id,
8406            config.admission_facts_targets,
8407            config.scope_authority_owners,
8408            config.federated_scope_owner,
8409            config.privileged_operator_prompt,
8410            config.modules,
8411            config.reserved_capabilities,
8412        );
8413
8414        // Collect the sections rescan cannot apply, so the REPLY carries them.
8415        //
8416        // The warning below has always been correct and has always gone only to
8417        // the journal -- addressed to whoever reads logs, while the person who
8418        // just edited the config is looking at the CLI. Naming each section
8419        // individually rather than setting a flag: "something outside modules
8420        // changed" sends the operator back to diffing their own file, which is
8421        // the work this is meant to save.
8422        let mut restart_required = Vec::new();
8423        for section in RestartRequiredSection::ALL {
8424            let changed = match section {
8425                RestartRequiredSection::Port => configured_port != context.configured_port,
8426                RestartRequiredSection::Storage => storage_config != context.storage_config,
8427                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8428                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8429                }
8430                RestartRequiredSection::AdmissionFactsTargets => {
8431                    admission_facts_targets != context.admission_facts_targets
8432                }
8433                RestartRequiredSection::ScopeAuthorityOwners => {
8434                    scope_authority_owners != context.scope_authority_owners
8435                }
8436                RestartRequiredSection::FederatedScopeOwner => {
8437                    federated_scope_owner != context.federated_scope_owner
8438                }
8439                RestartRequiredSection::PrivilegedOperatorPrompt => {
8440                    privileged_operator_prompt != context.privileged_operator_prompt
8441                }
8442            };
8443            if changed {
8444                restart_required.push(section.label().to_string());
8445            }
8446        }
8447        if !restart_required.is_empty() {
8448            warn!(
8449                config_path = %context.config_path.display(),
8450                sections = %restart_required.join(", "),
8451                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8452            );
8453        }
8454
8455        for configured in &modules {
8456            if let Err(err) = validate_spec(&configured.module_spec()) {
8457                return Ok(vec![control_error_frame(
8458                    &frame,
8459                    "invalid_daemon_config",
8460                    format!("supervisor rescan rejected daemon config: {err}"),
8461                )?]);
8462            }
8463        }
8464
8465        let configured_capabilities = modules
8466            .iter()
8467            .map(|module| (module.module_id.clone(), module.enabled))
8468            .collect::<Vec<_>>();
8469        let preview_capability_warnings = if preview {
8470            let (_, registrations) = self.runtime_capability_snapshot()?;
8471            let current_modules = self
8472                .supervisor
8473                .list()
8474                .into_iter()
8475                .map(|module| module.module_id().to_string())
8476                .collect::<BTreeSet<_>>();
8477            let resulting_modules = configured_capabilities.clone();
8478            let removed = current_modules
8479                .into_iter()
8480                .filter(|module_id| {
8481                    !resulting_modules
8482                        .iter()
8483                        .any(|(configured_id, _)| configured_id == module_id)
8484                })
8485                .collect::<Vec<_>>();
8486            // A candidate preview also names providers the candidate disables.
8487            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8488            let disabled = match &mode {
8489                RescanMode::Candidate(_) => resulting_modules
8490                    .iter()
8491                    .filter(|(_, enabled)| !enabled)
8492                    .map(|(module_id, _)| module_id.clone())
8493                    .collect::<Vec<_>>(),
8494                _ => Vec::new(),
8495            };
8496            self.capability_evaluator.preview_warnings(
8497                resulting_modules,
8498                &removed,
8499                &disabled,
8500                &registrations,
8501            )
8502        } else {
8503            Vec::new()
8504        };
8505        let reconciled = match (&mode, approved_preview.as_ref()) {
8506            (RescanMode::Preview, Some(approved)) => Ok((
8507                config_gate::preview_approved_daemon(approved, &modules),
8508                Vec::new(),
8509            )),
8510            (RescanMode::Candidate(candidate), _) => self
8511                .preview_candidate(&context, modules, candidate)
8512                .map(|result| (result, Vec::new())),
8513            _ => {
8514                self.reconcile_supervised_modules(
8515                    &context.supervisor,
8516                    modules,
8517                    preview,
8518                    requester.clone(),
8519                )
8520                .await
8521            }
8522        };
8523        let (result, changed) = match reconciled {
8524            Ok(result) => result,
8525            Err(message) => {
8526                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8527            }
8528        };
8529        if !preview {
8530            if let Some(ledger) = &self.activity {
8531                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8532                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8533            }
8534            if let Err(code) = self.configure_activity(activity_config).await {
8535                warn!(
8536                    code,
8537                    "activity retention could not be applied during rescan"
8538                );
8539            }
8540            self.capability_evaluator
8541                .configure(configured_capabilities, reserved_capabilities);
8542            self.capability_evaluator.wake_deadline_loop();
8543            self.refresh_capability_requirements();
8544        }
8545        let mut result = result;
8546        result.restart_required = restart_required;
8547        result.capability_warnings = preview_capability_warnings;
8548        let response = ClientControlResponse::SupervisorRescan { result };
8549        Ok(vec![control_response_body_frame(
8550            &frame,
8551            &response,
8552            "ClientControlResponse::SupervisorRescan",
8553        )?])
8554    }
8555
8556    async fn handle_supervisor_release_reserved(
8557        &self,
8558        frame: Frame,
8559        module_id: String,
8560    ) -> Result<Vec<Frame>, RouterError> {
8561        let Some(context) = self.rescan.clone() else {
8562            return Ok(vec![control_error_frame(
8563                &frame,
8564                "release_unavailable",
8565                "reserved-id release requires a daemon started with a reloadable config path",
8566            )?]);
8567        };
8568        let operation_lock = self.supervisor.operation_lock();
8569        let _operation_guard = operation_lock.lock().await;
8570        let approved = if let Some(owner) = &self.config_runtime {
8571            // Observe the file as a proposal, but decide membership solely from
8572            // approved bytes. A proposed re-add must not retain a removed id.
8573            match owner
8574                .on_blocking(|owner| {
8575                    owner.observe_file_proposal()?;
8576                    owner.approved_daemon_configuration()
8577                })
8578                .await
8579            {
8580                Ok(config) => config,
8581                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8582            }
8583        } else {
8584            None
8585        };
8586        let loaded = if let Some(approved) = approved {
8587            Ok(Some(approved))
8588        } else {
8589            crate::daemon_config::load(&context.config_path)
8590        };
8591        let loaded = match loaded {
8592            Ok(Some(config)) => config,
8593            Ok(None) => {
8594                return Ok(vec![control_error_frame(
8595                    &frame,
8596                    "invalid_daemon_config",
8597                    format!(
8598                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8599                        context.config_path.display()
8600                    ),
8601                )?])
8602            }
8603            Err(err) => {
8604                return Ok(vec![control_error_frame(
8605                    &frame,
8606                    "invalid_daemon_config",
8607                    format!("unable to verify reserved-id release against daemon config: {err}"),
8608                )?])
8609            }
8610        };
8611        if loaded
8612            .modules
8613            .iter()
8614            .any(|configured| configured.module_id == module_id)
8615        {
8616            return Ok(vec![control_error_frame(
8617                &frame,
8618                "reserved_module_configured",
8619                format!(
8620                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8621                ),
8622            )?]);
8623        }
8624        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8625            return Ok(vec![control_error_frame(
8626                &frame,
8627                "reserved_gate_not_retained",
8628                format!(
8629                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8630                ),
8631            )?]);
8632        }
8633
8634        let response = ClientControlResponse::SupervisorAck {
8635            module_id,
8636            applied: true,
8637        };
8638        Ok(vec![control_response_body_frame(
8639            &frame,
8640            &response,
8641            "ClientControlResponse::SupervisorAck",
8642        )?])
8643    }
8644
8645    /// Compare the configured module set with the supervised one, changing
8646    /// nothing. The staged spec each supervised module holds is what the
8647    /// configured entry is compared with.
8648    fn plan_rescan(
8649        &self,
8650        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8651    ) -> Result<RescanPlan, String> {
8652        let mut current = BTreeMap::new();
8653        for module in self.supervisor.list() {
8654            let (spec, health) = module.configuration().map_err(|err| {
8655                format!(
8656                    "failed to read configuration for module_id '{}': {err}",
8657                    module.module_id()
8658                )
8659            })?;
8660            let enabled = module
8661                .status()
8662                .map_err(|err| {
8663                    format!(
8664                        "failed to read status for module_id '{}': {err}",
8665                        module.module_id()
8666                    )
8667                })?
8668                .enabled;
8669            current.insert(
8670                module.module_id().to_string(),
8671                (module, spec, health, enabled),
8672            );
8673        }
8674        let configured = configured_modules
8675            .into_iter()
8676            .map(|module| (module.module_id.clone(), module))
8677            .collect::<BTreeMap<_, _>>();
8678
8679        let added = configured
8680            .keys()
8681            .filter(|module_id| !current.contains_key(*module_id))
8682            .cloned()
8683            .collect::<Vec<_>>();
8684        let removed = current
8685            .keys()
8686            .filter(|module_id| !configured.contains_key(*module_id))
8687            .cloned()
8688            .collect::<Vec<_>>();
8689        let mut changed_pending_reload = Vec::new();
8690        let mut changed_pending = Vec::new();
8691        let mut configuration_changes = BTreeSet::new();
8692        let mut enabled_changes = BTreeSet::new();
8693        let mut unchanged = 0_u32;
8694        let publication = self
8695            .config_runtime
8696            .as_ref()
8697            .and_then(|owner| owner.polled_snapshot().ok());
8698
8699        for (module_id, configured_module) in &configured {
8700            let Some((module, current_spec, current_health, current_enabled)) =
8701                current.get(module_id)
8702            else {
8703                continue;
8704            };
8705            // Compare the whole launch spec so a future launch field cannot
8706            // accidentally become a live-only policy change. Health is stored
8707            // separately and applies live without replacing the process.
8708            let launch_changed = *current_spec != configured_module.module_spec();
8709            let configuration_changed =
8710                launch_changed || *current_health != configured_module.health;
8711            let pending = self.pending_module_fields(
8712                module,
8713                Some(configured_module),
8714                configuration_changed,
8715                Self::registration_channel_in_force(
8716                    publication
8717                        .as_ref()
8718                        .and_then(|view| view.registration_declaration(module_id))
8719                        .as_deref(),
8720                    publication
8721                        .as_ref()
8722                        .and_then(|view| match &view.approved_daemon {
8723                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8724                                config,
8725                                ..
8726                            } => config
8727                                .modules
8728                                .iter()
8729                                .find(|entry| entry.module_id == *module_id)
8730                                .map(|entry| entry.registration_channel),
8731                            _ => None,
8732                        }),
8733                ),
8734                publication.as_deref(),
8735            )?;
8736            let has_pending = !pending.is_empty();
8737            if has_pending {
8738                changed_pending.push(subc_control::SupervisorPendingModule {
8739                    module_id: module_id.clone(),
8740                    fields: pending
8741                        .into_iter()
8742                        .map(|mut field| {
8743                            field.value = None;
8744                            field
8745                        })
8746                        .collect(),
8747                });
8748            }
8749            // Applying a rescan also replaces the recorded config value, even
8750            // when an operator already put the runtime in the requested state.
8751            let enabled_changed = *current_enabled != configured_module.enabled
8752                || self
8753                    .capability_evaluator
8754                    .configured_enabled(module_id)
8755                    .is_some_and(|enabled| enabled != configured_module.enabled);
8756            if configuration_changed {
8757                configuration_changes.insert(module_id.clone());
8758            }
8759            if launch_changed {
8760                changed_pending_reload.push(module_id.clone());
8761            }
8762            if enabled_changed {
8763                enabled_changes.insert(module_id.clone());
8764            }
8765            if !configuration_changed && !enabled_changed && !has_pending {
8766                unchanged = unchanged.saturating_add(1);
8767            }
8768        }
8769        Ok(RescanPlan {
8770            current,
8771            configured,
8772            added,
8773            removed,
8774            changed_pending_reload,
8775            changed_pending,
8776            configuration_changes,
8777            enabled_changes,
8778            unchanged,
8779        })
8780    }
8781
8782    /// Reconcile the running module set against the configured one.
8783    ///
8784    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8785    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8786    /// deliberately shares this function with the executing path rather than
8787    /// computing the same diff somewhere else -- two implementations of one
8788    /// decision agree until they do not, and the whole value of a preview is that
8789    /// it describes the operation that will actually run.
8790    async fn reconcile_supervised_modules(
8791        &self,
8792        supervisor: &Supervisor,
8793        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8794        preview: bool,
8795        requester: Principal,
8796    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8797        let plan = self.plan_rescan(configured_modules)?;
8798
8799        // Everything above this point is pure computation over two snapshots.
8800        // Everything below MUTATES. The preview returns here so the boundary is a
8801        // single early return rather than a condition repeated at each mutation
8802        // site, where one missed guard would apply part of a change the caller was
8803        // told would not happen.
8804        if preview {
8805            return Ok((plan.preview_result(), Vec::new()));
8806        }
8807        let changed = plan
8808            .configuration_changes
8809            .union(&plan.enabled_changes)
8810            .cloned()
8811            .collect::<Vec<_>>();
8812        let RescanPlan {
8813            current,
8814            configured,
8815            added,
8816            removed,
8817            changed_pending_reload,
8818            changed_pending,
8819            configuration_changes,
8820            enabled_changes,
8821            unchanged,
8822        } = plan;
8823        // The staged generation moves before the first change rather than
8824        // after the last, so a rescan that fails partway still invalidates
8825        // every earlier `supervisor.rescan_checked` preview: part of its diff
8826        // may have run.
8827        if !(added.is_empty()
8828            && removed.is_empty()
8829            && configuration_changes.is_empty()
8830            && changed_pending.is_empty()
8831            && enabled_changes.is_empty())
8832        {
8833            if let Some(context) = &self.rescan {
8834                context
8835                    .generation
8836                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8837            }
8838        }
8839
8840        for module_id in &removed {
8841            let module = &current
8842                .get(module_id)
8843                .expect("removed module came from current supervisor state")
8844                .0;
8845            module
8846                .retire_requested(Some(requester.clone()))
8847                .await
8848                .map_err(|err| {
8849                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8850                })?;
8851            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8852            //
8853            // `handle_route_open` resolves an absent module in three steps:
8854            // registry, then supervisor status, then tombstone. Retiring first
8855            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8856            // went with the teardown above, the supervisor entry went with
8857            // `retire`, and the tombstone does not exist yet -- so a route.open
8858            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8859            // it") for a module that was deliberately removed and whose caller
8860            // should get `module_removed` (TERMINAL, carrying a removal age).
8861            //
8862            // Writing the tombstone first closes it: during the window the
8863            // supervisor entry still answers, so the caller gets
8864            // `target_unavailable` -- retryable, and TRUE, because the module
8865            // is mid-teardown. After both statements it is `module_removed`.
8866            // No instant remains where a removed module reads as one that
8867            // never existed.
8868            //
8869            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8870            // the absence of a test beside a fix invites deletion: these are
8871            // two sync statements with no await between them, so reaching the
8872            // window needs a second worker thread to land exactly between them
8873            // and there is no hook to force it. MEASURED: the 25 daemon_config
8874            // tests pass identically with the old order and the new one, so
8875            // the existing suite cannot see this and a green run is not
8876            // evidence either way. What the suite does hold is the
8877            // post-condition -- a removed module answers `module_removed` --
8878            // which this preserves.
8879            //
8880            // Found by an Athena panel reading the shipped tree against a
8881            // design note (2026-09-19), as the one concrete instance of that
8882            // note's class that survived contact with source. Direction is
8883            // benign: retryable where terminal was intended, never the reverse.
8884            self.supervisor.record_rescan_removal(module_id);
8885            self.supervisor.retire(module_id);
8886            self.route_outages.forget(module_id);
8887        }
8888
8889        for module_id in configured.keys() {
8890            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8891                continue;
8892            };
8893            let configured_module = configured
8894                .get(module_id)
8895                .expect("configured module id came from configured map");
8896            if configuration_changes.contains(module_id) {
8897                module
8898                    .update_configuration(
8899                        configured_module.module_spec(),
8900                        configured_module.health.clone(),
8901                        configured_module.drain_timeout_ms,
8902                    )
8903                    .await
8904                    .map_err(|err| {
8905                        format!(
8906                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8907                        )
8908                    })?;
8909            }
8910            // Config-only drift is applied by the evaluator's config update;
8911            // do not turn it into a runtime start or stop.
8912            if *current_enabled != configured_module.enabled {
8913                // A rescan that starts or stops a module applies an operator's
8914                // edit to the config, so the resulting outage was asked for.
8915                self.route_outages.mark_operator_action(module_id);
8916                module
8917                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8918                    .await
8919                    .map_err(|err| {
8920                        self.route_outages.operator_action_ended_unrefused(module_id);
8921                        format!(
8922                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8923                            configured_module.enabled
8924                        )
8925                    })?;
8926            }
8927        }
8928
8929        for module_id in &added {
8930            let configured_module = configured
8931                .get(module_id)
8932                .expect("added module id came from configured map");
8933            supervisor
8934                .supervise_configured_requested_async(
8935                    configured_module.module_spec(),
8936                    configured_module.enabled,
8937                    configured_module.health.clone(),
8938                    configured_module.drain_timeout_ms,
8939                    configured_module.restart,
8940                    configured_module.register_timeout,
8941                    Some(requester.clone()),
8942                )
8943                .await
8944                .map_err(|err| {
8945                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8946                })?;
8947        }
8948
8949        if let Some(context) = &self.rescan {
8950            let mut entries = context
8951                .module_entries
8952                .lock()
8953                .unwrap_or_else(|e| e.into_inner());
8954            entries.record(&configured, &added, &removed);
8955        }
8956
8957        Ok((
8958            SupervisorRescanResult {
8959                added,
8960                removed,
8961                changed_pending_reload,
8962                changed_pending,
8963                enabled_changes: enabled_changes.iter().cloned().collect(),
8964                unchanged,
8965                preview: false,
8966                // Filled by the caller, which is the only layer that can see the
8967                // previous config to diff against.
8968                restart_required: Vec::new(),
8969                capability_warnings: Vec::new(),
8970                module_actions: Vec::new(),
8971                earlier_pending: Vec::new(),
8972                expect: None,
8973            },
8974            changed,
8975        ))
8976    }
8977
8978    async fn handle_supervisor_set_enabled(
8979        &self,
8980        frame: Frame,
8981        module_id: String,
8982        enabled: bool,
8983        requester: Principal,
8984    ) -> Result<Vec<Frame>, RouterError> {
8985        let operation_lock = self.supervisor.operation_lock();
8986        let _operation_guard = operation_lock.lock().await;
8987        let Some(module) = self.supervisor.get(&module_id) else {
8988            return Ok(vec![control_error_frame(
8989                &frame,
8990                "unknown_module",
8991                format!("module_id '{module_id}' is not supervised"),
8992            )?]);
8993        };
8994
8995        // Enabling counts as well as disabling: a module an operator starts
8996        // is refused until it registers, and that wait was asked for.
8997        self.route_outages.mark_operator_action(&module_id);
8998        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
8999            Ok(applied) => applied,
9000            Err(err) => {
9001                self.route_outages
9002                    .operator_action_ended_unrefused(&module_id);
9003                return Ok(vec![control_error_frame(
9004                    &frame,
9005                    if err.is_config_gate_error() {
9006                        "config_gated"
9007                    } else {
9008                        "target_unavailable"
9009                    },
9010                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
9011                )?]);
9012            }
9013        };
9014        if !applied {
9015            // Already in the requested state: nothing was made unavailable,
9016            // so the mark must not outlive this request.
9017            self.route_outages
9018                .operator_action_ended_unrefused(&module_id);
9019        }
9020
9021        self.capability_evaluator.wake_deadline_loop();
9022        self.refresh_capability_requirements();
9023        let response = ClientControlResponse::SupervisorAck { module_id, applied };
9024        Ok(vec![control_response_body_frame(
9025            &frame,
9026            &response,
9027            "ClientControlResponse::SupervisorAck",
9028        )?])
9029    }
9030
9031    async fn handle_supervisor_health_probe(
9032        &self,
9033        ctx: &RouteCtx,
9034        frame: Frame,
9035        module_id: String,
9036    ) -> Result<Vec<Frame>, RouterError> {
9037        self.refresh_capability_requirements();
9038        let Some(registration) = self
9039            .registry
9040            .get_module(&module_id)
9041            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
9042        else {
9043            return Ok(vec![control_error_frame(
9044                &frame,
9045                "unknown_module",
9046                format!("module_id '{module_id}' is not registered"),
9047            )?]);
9048        };
9049
9050        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
9051        // named for it. Making `module_registration_grants_op` return false
9052        // unconditionally reddens five tests, and every one is named for something
9053        // else -- capability relay, probe/bind demultiplexing, supervision-only
9054        // probing. They exercise a successful advertisement check on the way to their
9055        // own subject.
9056        //
9057        // Real protection, fragile in a specific way: narrowing any of those tests to
9058        // focus on its stated subject would silently remove coverage nobody knows
9059        // they are carrying. Recorded here rather than as a sixth test, because the
9060        // useful fact is WHICH tests hold the guard up -- a new test would add
9061        // coverage without telling the next person what the existing ones quietly do.
9062        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
9063        {
9064            return Ok(vec![control_error_frame(
9065                &frame,
9066                "health_not_advertised",
9067                format!("module_id '{module_id}' did not advertise health.check"),
9068            )?]);
9069        }
9070
9071        self.observe_control_wait(
9072            ctx,
9073            Some(&registration.manifest.module_id),
9074            ops::SUPERVISOR_HEALTH_PROBE,
9075            async {
9076                let deadline = Instant::now() + self.health_probe_timeout;
9077                let pending = match self.forwarding.begin_module_control_rpc_for(
9078                    &module_id,
9079                    MODULE_CONTROL_OP_HEALTH_CHECK,
9080                    deadline,
9081                ) {
9082                    Ok(pending) => pending,
9083                    Err(err) => {
9084                        return Ok(vec![control_error_frame(
9085                            &frame,
9086                            forwarding_error_code(&err),
9087                            err.to_string(),
9088                        )?])
9089                    }
9090                };
9091
9092                let PendingModuleControlRpc {
9093                    endpoint,
9094                    module_sink,
9095                    negotiated_ver,
9096                    corr: probe_corr,
9097                    receiver,
9098                } = pending;
9099                let mut guard =
9100                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9101                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9102                    .map_err(|err| {
9103                        RouterError::backend(
9104                            0,
9105                            frame.header.corr,
9106                            format!("failed to encode health.check request: {err}"),
9107                        )
9108                    })?;
9109                let probe_frame = Frame::build_with_version(
9110                    negotiated_ver,
9111                    FrameType::Request,
9112                    control_flags(),
9113                    0,
9114                    0,
9115                    probe_corr,
9116                    probe_body,
9117                )
9118                .map_err(RouterError::FrameBuild)?;
9119
9120                // Queue admission and the reply share one deadline, so a module that
9121                // stops reading cannot park the requesting connection's reader forever.
9122                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9123                    Ok(Ok(())) => {}
9124                    Ok(Err(err)) => {
9125                        return Ok(vec![control_error_frame(
9126                            &frame,
9127                            "target_unavailable",
9128                            err.to_string(),
9129                        )?]);
9130                    }
9131                    Err(_) => {
9132                        return Ok(vec![control_error_frame(
9133                            &frame,
9134                            "module_timeout",
9135                            format!(
9136                                "module_id '{module_id}' did not answer health.check within {:?}",
9137                                self.health_probe_timeout
9138                            ),
9139                        )?]);
9140                    }
9141                }
9142
9143                match timeout_at(deadline, receiver).await {
9144                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9145                        Ok(vec![control_error_frame(
9146                            &frame,
9147                            "invalid_control_body",
9148                            "health.check returned an unexpected config response",
9149                        )?])
9150                    }
9151                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9152                        guard.disarm();
9153                        let Some(report) = response.health_report() else {
9154                            return Ok(vec![control_error_frame(
9155                                &frame,
9156                                "invalid_control_body",
9157                                "health.check RPC returned a non-health response",
9158                            )?]);
9159                        };
9160                        // Metrics go out whole here. The supervisor's cached snapshot
9161                        // caps this blob (see truncate_health_metrics), and this path
9162                        // exists precisely to answer without that cap -- so applying it
9163                        // here would leave no way to see what the cached view drops.
9164                        let HealthReport {
9165                            status,
9166                            detail,
9167                            metrics,
9168                        } = report;
9169                        let capability_detail = self
9170                            .capability_evaluator
9171                            .required_problem_detail(&module_id);
9172                        let response = ClientControlResponse::SupervisorHealthProbe {
9173                            module_id,
9174                            status,
9175                            detail: append_capability_problem_detail(detail, capability_detail),
9176                            metrics,
9177                        };
9178                        Ok(vec![control_response_body_frame(
9179                            &frame,
9180                            &response,
9181                            "ClientControlResponse::SupervisorHealthProbe",
9182                        )?])
9183                    }
9184                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9185                        guard.disarm();
9186                        // The module refused the health probe with its own body, so
9187                        // the refusal is relayed without the daemon-origin flag
9188                        // (bit 6): a client must not read it as the daemon's own
9189                        // refusal, which it may treat as never forwarded.
9190                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9191                    }
9192                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9193                        guard.disarm();
9194                        Ok(vec![control_error_frame(
9195                            &frame,
9196                            "target_unavailable",
9197                            message,
9198                        )?])
9199                    }
9200                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9201                        guard.disarm();
9202                        Ok(vec![control_error_frame(
9203                            &frame,
9204                            "invalid_control_body",
9205                            message,
9206                        )?])
9207                    }
9208                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9209                        guard.disarm();
9210                        Ok(vec![control_error_frame(
9211                            &frame,
9212                            "invalid_control_body",
9213                            format!("expected module-control op '{expected}', got '{actual}'"),
9214                        )?])
9215                    }
9216                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9217                        guard.disarm();
9218                        Ok(vec![control_error_frame(
9219                            &frame,
9220                            "module_timeout",
9221                            format!(
9222                                "module_id '{module_id}' answered health.check after {:?}",
9223                                self.health_probe_timeout
9224                            ),
9225                        )?])
9226                    }
9227                    Ok(Err(_)) => Ok(vec![control_error_frame(
9228                        &frame,
9229                        "target_unavailable",
9230                        "health.check waiter was canceled before the module responded",
9231                    )?]),
9232                    Err(_) => Ok(vec![control_error_frame(
9233                        &frame,
9234                        "module_timeout",
9235                        format!(
9236                            "module_id '{module_id}' did not answer health.check within {:?}",
9237                            self.health_probe_timeout
9238                        ),
9239                    )?]),
9240                }
9241            },
9242        )
9243        .await
9244    }
9245
9246    fn supervisor_status(
9247        &self,
9248        module_id: &str,
9249        corr: u64,
9250    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9251        self.supervisor
9252            .get(module_id)
9253            .map(|module| {
9254                let warming = module.is_warming_for_control("status").map_err(|err| {
9255                    RouterError::backend(
9256                        0,
9257                        corr,
9258                        format!(
9259                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9260                        ),
9261                    )
9262                })?;
9263                module.status_for_control("status").map_err(|err| {
9264                    RouterError::backend(
9265                        0,
9266                        corr,
9267                        format!(
9268                            "failed to read supervisor status for module_id '{module_id}': {err}"
9269                        ),
9270                    )
9271                }).map(|status| (status, warming))
9272            })
9273            .transpose()
9274    }
9275
9276    fn guard_module_control_op(
9277        &self,
9278        frame: &Frame,
9279        module_id: &str,
9280        op: &str,
9281    ) -> Result<Option<Frame>, RouterError> {
9282        if self.module_grants_op(module_id, op, frame.header.corr)? {
9283            return Ok(None);
9284        }
9285
9286        Ok(Some(control_error_frame(
9287            frame,
9288            "op_not_allowed",
9289            format!("module_id '{module_id}' did not grant control op '{op}'"),
9290        )?))
9291    }
9292
9293    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9294        self.registry
9295            .grants_control_op(module_id, op)
9296            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9297    }
9298
9299    fn handle_status_update(
9300        &self,
9301        endpoint: ModuleEndpointId,
9302        frame: Frame,
9303    ) -> Result<Vec<Frame>, RouterError> {
9304        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9305            Ok(update) => update,
9306            Err(err) => {
9307                // Forward-compat: a newer module may push a channel-0 op this subc
9308                // version doesn't know. The control contract says unknown push ops
9309                // are IGNORED, never answered with an error. Only a malformed body
9310                // for an op we DO know is a real error worth surfacing.
9311                if is_known_module_push_op(&frame.body) {
9312                    return Ok(vec![control_error_frame(
9313                        &frame,
9314                        "invalid_control_body",
9315                        format!("malformed module control push body: {err}"),
9316                    )?]);
9317                }
9318                return Ok(Vec::new());
9319            }
9320        };
9321
9322        match update {
9323            ModuleControlPush::RouteStatus {
9324                route_channel,
9325                route_epoch,
9326                status,
9327            } => {
9328                self.forwarding
9329                    .cache_status(endpoint, route_channel, route_epoch, status)
9330                    .map_err(RouterError::Forwarding)?;
9331            }
9332        }
9333        Ok(Vec::new())
9334    }
9335
9336    fn handle_route_poll(
9337        &self,
9338        ctx: &RouteCtx,
9339        frame: Frame,
9340        route_channel: u16,
9341        route_epoch: u32,
9342        kind: PollKind,
9343    ) -> Result<Vec<Frame>, RouterError> {
9344        let snapshot = self
9345            .forwarding
9346            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9347            .map_err(RouterError::Forwarding)?;
9348        let response = match (kind, snapshot) {
9349            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9350                ClientControlResponse::RoutePoll {
9351                    route_channel,
9352                    route_epoch,
9353                    status,
9354                    live: None,
9355                }
9356            }
9357            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9358                route_channel,
9359                route_epoch,
9360                status: None,
9361                live: None,
9362            },
9363            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9364                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9365                // is what makes reporting `true` correct rather than a
9366                // confident guess. `process_live` returns None only when the
9367                // module id has no supervisor snapshot at all -- an
9368                // externally-started module the daemon did not spawn -- and
9369                // for those the supervisor has no opinion to offer, ever. It
9370                // is never None for a supervised module in an unknown state:
9371                // a supervised module always has a snapshot, and the answer
9372                // comes from `state == Running && process_alive`.
9373                //
9374                // The route is Bound, so the module completed a HELLO on a
9375                // live connection; "the process this route points at is
9376                // running" is therefore attested by the binding rather than
9377                // assumed. Reporting `false` for an unsupervised module would
9378                // be the actual lie -- it would tell a client its healthy
9379                // route is dead because the daemon does not manage the
9380                // process.
9381                //
9382                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9383                // module whose liveness is genuinely unknown, e.g. a snapshot
9384                // that has not been populated yet -- THIS DEFAULT BECOMES
9385                // WRONG and must split: unsupervised stays true, unknown
9386                // becomes null so the client can tell the two apart. The
9387                // response field is already `Option<bool>`, so the wire can
9388                // carry that distinction today.
9389                let live = self
9390                    .process_liveness
9391                    .as_ref()
9392                    .and_then(|source| source.process_live(&module_id))
9393                    .unwrap_or(true);
9394                ClientControlResponse::RoutePoll {
9395                    route_channel,
9396                    route_epoch,
9397                    status: None,
9398                    live: Some(live),
9399                }
9400            }
9401            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9402                route_channel,
9403                route_epoch,
9404                status: None,
9405                live: Some(false),
9406            },
9407        };
9408
9409        Ok(vec![control_response_body_frame(
9410            &frame,
9411            &response,
9412            "ClientControlResponse::RoutePoll",
9413        )?])
9414    }
9415
9416    pub(crate) fn observe_module_control_completion(
9417        &self,
9418        completion: ModuleControlRpcCompletion,
9419    ) -> bool {
9420        match completion {
9421            ModuleControlRpcCompletion::Unknown => false,
9422            ModuleControlRpcCompletion::Settled => true,
9423            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9424                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9425                info!(
9426                    module_id = %module_id,
9427                    latency_ms,
9428                    "late health.check answer proves the module is alive"
9429                );
9430                match self
9431                    .supervisor
9432                    .record_late_health_answer(&module_id, latency_ms)
9433                {
9434                    Ok(true) => {}
9435                    Ok(false) => debug!(
9436                        module_id = %module_id,
9437                        latency_ms,
9438                        "late health.check answer has no active supervisor snapshot"
9439                    ),
9440                    Err(err) => warn!(
9441                        module_id = %module_id,
9442                        latency_ms,
9443                        error = %err,
9444                        "failed to record late health.check answer"
9445                    ),
9446                }
9447                true
9448            }
9449        }
9450    }
9451
9452    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9453    /// the module connection whose frame is being handled, or to the client that
9454    /// relay was opened for.
9455    ///
9456    /// This runs on the MODULE connection's frame handler, where returning `Err`
9457    /// ends that connection -- and a module connection carries every client's
9458    /// routes to that module, so ending it costs the whole fleet its tools.
9459    /// `ConnectionClosing` carries the id of the connection that is closing, and
9460    /// when that id is a CLIENT's, the condition is entirely about that one
9461    /// client's route.open. A client-scoped condition has no authority over a
9462    /// shared module connection, so it is logged and the single relay is dropped:
9463    /// the client is going away, and `complete_pending_relay` already removed the
9464    /// relay before failing, so there is nothing left to settle. Anything that
9465    /// relay still reserved is released by that client's own connection teardown,
9466    /// which is already under way -- that is what "closing" means.
9467    ///
9468    /// Every other failure is a statement about THIS connection and stays fatal:
9469    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9470    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9471    /// frames correctly.
9472    fn refuse_to_end_module_connection_for_a_client(
9473        &self,
9474        module_connection_id: ConnectionId,
9475        corr: u64,
9476        err: ForwardingError,
9477    ) -> Result<(), RouterError> {
9478        if let ForwardingError::ConnectionClosing { connection_id } = err {
9479            if connection_id != module_connection_id {
9480                warn!(
9481                    module_connection_id = module_connection_id.get(),
9482                    client_connection_id = connection_id.get(),
9483                    corr,
9484                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9485                );
9486                return Ok(());
9487            }
9488        }
9489        Err(RouterError::Forwarding(err))
9490    }
9491
9492    fn handle_module_relay_response(
9493        &self,
9494        connection_id: ConnectionId,
9495        frame: Frame,
9496    ) -> Result<Vec<Frame>, RouterError> {
9497        let mut secondary_error = None;
9498        let outcome = match frame.header.ty {
9499            FrameType::Response => match module_control_response_probe(&frame.body) {
9500                Ok(probe) if probe.op == "route.bind" => {
9501                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9502                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9503                            RouteBindRelayOutcome::Accepted
9504                        }
9505                        Ok(other) => {
9506                            let message =
9507                                format!("route.bind response carried unexpected body: {other:?}");
9508                            secondary_error = Some(control_error_frame(
9509                                &frame,
9510                                "invalid_control_body",
9511                                message.clone(),
9512                            )?);
9513                            RouteBindRelayOutcome::ModuleGone(message)
9514                        }
9515                        Err(err) => {
9516                            let message = format!("malformed route.bind response body: {err}");
9517                            secondary_error = Some(control_error_frame(
9518                                &frame,
9519                                "invalid_control_body",
9520                                message.clone(),
9521                            )?);
9522                            RouteBindRelayOutcome::ModuleGone(message)
9523                        }
9524                    }
9525                }
9526                Ok(probe) => {
9527                    let outcome = if matches!(
9528                        probe.op.as_str(),
9529                        "config.review" | "consent/v1" | "projects.enumerate"
9530                    ) {
9531                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9532                    } else {
9533                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9534                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9535                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9536                                "malformed {} response body: {err}",
9537                                probe.op
9538                            )),
9539                        }
9540                    };
9541                    let completion = self
9542                        .forwarding
9543                        .complete_module_control_rpc(
9544                            connection_id,
9545                            frame.header.corr,
9546                            Some(&probe.op),
9547                            outcome,
9548                        )
9549                        .map_err(RouterError::Forwarding)?;
9550                    if !self.observe_module_control_completion(completion) {
9551                        debug!(
9552                            connection_id = connection_id.get(),
9553                            corr = frame.header.corr,
9554                            op = %probe.op,
9555                            "dropping late or unknown module-control RPC response"
9556                        );
9557                    }
9558                    return Ok(Vec::new());
9559                }
9560                Err(err) => {
9561                    if let Some(expected_op) = self
9562                        .forwarding
9563                        .pending_module_control_op(connection_id, frame.header.corr)
9564                        .map_err(RouterError::Forwarding)?
9565                    {
9566                        let completion = self
9567                            .forwarding
9568                            .complete_module_control_rpc(
9569                                connection_id,
9570                                frame.header.corr,
9571                                None,
9572                                ModuleControlRpcOutcome::MalformedResponse(format!(
9573                                    "malformed {expected_op} response body: {err}"
9574                                )),
9575                            )
9576                            .map_err(RouterError::Forwarding)?;
9577                        if !self.observe_module_control_completion(completion) {
9578                            debug!(
9579                                connection_id = connection_id.get(),
9580                                corr = frame.header.corr,
9581                                "dropping late malformed module-control RPC response"
9582                            );
9583                        }
9584                        return Ok(Vec::new());
9585                    }
9586                    let message = format!("malformed route.bind response body: {err}");
9587                    secondary_error = Some(control_error_frame(
9588                        &frame,
9589                        "invalid_control_body",
9590                        message.clone(),
9591                    )?);
9592                    RouteBindRelayOutcome::ModuleGone(message)
9593                }
9594            },
9595            FrameType::Error => {
9596                if self
9597                    .forwarding
9598                    .pending_module_control_op(connection_id, frame.header.corr)
9599                    .map_err(RouterError::Forwarding)?
9600                    .is_some()
9601                {
9602                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9603                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9604                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9605                            "malformed module-control ERROR body: {err}"
9606                        )),
9607                    };
9608                    let completion = self
9609                        .forwarding
9610                        .complete_module_control_rpc(
9611                            connection_id,
9612                            frame.header.corr,
9613                            None,
9614                            outcome,
9615                        )
9616                        .map_err(RouterError::Forwarding)?;
9617                    if !self.observe_module_control_completion(completion) {
9618                        debug!(
9619                            connection_id = connection_id.get(),
9620                            corr = frame.header.corr,
9621                            "dropping late or unknown module-control RPC error"
9622                        );
9623                    }
9624                    return Ok(Vec::new());
9625                }
9626                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9627                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9628                    Err(err) => {
9629                        let message = format!("malformed route.bind ERROR body: {err}");
9630                        secondary_error = Some(control_error_frame(
9631                            &frame,
9632                            "invalid_control_body",
9633                            message.clone(),
9634                        )?);
9635                        RouteBindRelayOutcome::ModuleGone(message)
9636                    }
9637                }
9638            }
9639            ty => {
9640                return Ok(vec![control_error_frame(
9641                    &frame,
9642                    "unsupported_control_frame",
9643                    format!("unsupported module channel-0 frame {ty:?}"),
9644                )?])
9645            }
9646        };
9647
9648        let settled =
9649            self.forwarding
9650                .complete_pending_relay(connection_id, frame.header.corr, outcome);
9651        let completion = match settled {
9652            Ok(completion) => completion,
9653            Err(err) => {
9654                self.refuse_to_end_module_connection_for_a_client(
9655                    connection_id,
9656                    frame.header.corr,
9657                    err,
9658                )?;
9659                return Ok(secondary_error.into_iter().collect());
9660            }
9661        };
9662        if let Some(target) = completion.abandoned.as_ref() {
9663            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9664        }
9665        if !completion.settled {
9666            debug!(
9667                connection_id = connection_id.get(),
9668                corr = frame.header.corr,
9669                frame_type = ?frame.header.ty,
9670                "dropping late or unknown route.bind relay response"
9671            );
9672        }
9673        Ok(secondary_error.into_iter().collect())
9674    }
9675
9676    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9677        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9678        // GOODBYE ends the connection's logical session even when its socket
9679        // stays open. Use disconnect teardown so verdicts, client notices and
9680        // scope authority are released at the same lifecycle boundary.
9681        self.cleanup_connection_with_end_reason(
9682            connection_id,
9683            RegistrationEndReason::ExplicitGoodbye,
9684        )
9685        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9686        Ok(Vec::new())
9687    }
9688}
9689
9690impl Default for ControlHandler {
9691    fn default() -> Self {
9692        Self::new(Arc::new(Registry::default()))
9693    }
9694}
9695
9696impl crate::supervise::SwapPromotionObserver for ControlHandler {
9697    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9698        self.apply_registration_capabilities(registration);
9699    }
9700}
9701
9702fn append_capability_problem_detail(
9703    detail: Option<String>,
9704    capability_detail: Option<String>,
9705) -> Option<String> {
9706    match (detail, capability_detail) {
9707        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9708        (Some(detail), None) => Some(detail),
9709        (None, Some(capability_detail)) => Some(capability_detail),
9710        (None, None) => None,
9711    }
9712}
9713
9714fn subc_ops() -> Vec<String> {
9715    SUBC_CONTROL_OPS
9716        .iter()
9717        .map(|op| (*op).to_string())
9718        .collect()
9719}
9720
9721fn module_subc_ops() -> Vec<String> {
9722    SUBC_CONTROL_OPS
9723        .iter()
9724        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9725        .map(|op| (*op).to_string())
9726        .collect()
9727}
9728
9729#[cfg(test)]
9730fn module_baseline_control_ops() -> Vec<String> {
9731    MODULE_BASELINE_CONTROL_OPS
9732        .iter()
9733        .map(|op| (*op).to_string())
9734        .collect()
9735}
9736
9737fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9738    let mut seen = HashSet::new();
9739    let mut effective = Vec::new();
9740    for op in MODULE_BASELINE_CONTROL_OPS {
9741        if seen.insert((*op).to_string()) {
9742            effective.push((*op).to_string());
9743        }
9744    }
9745    for op in declared.unwrap_or_default() {
9746        if seen.insert(op.clone()) {
9747            effective.push(op);
9748        }
9749    }
9750    effective
9751}
9752
9753fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9754    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9755}
9756
9757fn target_module_id(target: &RouteTarget) -> &str {
9758    match target {
9759        RouteTarget::ToolProvider { module_id }
9760        | RouteTarget::ManagementSurface { module_id }
9761        | RouteTarget::InternalService { module_id, .. } => module_id,
9762    }
9763}
9764
9765fn target_has_required_role(
9766    target: &RouteTarget,
9767    roles: &[crate::registry::AdmissionRole],
9768) -> bool {
9769    use crate::registry::AdmissionRole;
9770    roles.iter().any(|role| match (target, role) {
9771        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9772        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9773        (
9774            RouteTarget::InternalService { service_id, .. },
9775            AdmissionRole::InternalService(provided),
9776        ) => service_id == provided,
9777        _ => false,
9778    })
9779}
9780
9781fn is_routable_role(role: &ProviderRole) -> bool {
9782    matches!(
9783        role,
9784        ProviderRole::ToolProvider { .. }
9785            | ProviderRole::ManagementSurface { .. }
9786            | ProviderRole::InternalService { .. }
9787    )
9788}
9789
9790#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9791enum ControlRequestBodyError {
9792    UnknownOp,
9793    InvalidBody,
9794}
9795
9796#[derive(Debug, Deserialize)]
9797struct ControlOpProbe {
9798    op: String,
9799}
9800
9801fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9802    serde_json::from_slice(body).or_else(|original| {
9803        #[derive(Deserialize)]
9804        struct ConsentProbe {
9805            protocol: String,
9806        }
9807        match serde_json::from_slice::<ConsentProbe>(body) {
9808            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9809                Ok(ControlOpProbe { op: probe.protocol })
9810            }
9811            _ => Err(original),
9812        }
9813    })
9814}
9815
9816/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9817/// this set is treated as a forward-compat unknown and ignored rather than errored.
9818const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9819
9820fn is_known_module_push_op(body: &[u8]) -> bool {
9821    serde_json::from_slice::<ControlOpProbe>(body)
9822        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9823        .unwrap_or(false)
9824}
9825
9826fn is_known_module_request_op(body: &[u8]) -> bool {
9827    serde_json::from_slice::<ControlOpProbe>(body)
9828        .map(|probe| is_module_to_subc_op(&probe.op))
9829        .unwrap_or(false)
9830}
9831
9832fn is_module_to_subc_op(op: &str) -> bool {
9833    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9834}
9835
9836fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9837    debug!(
9838        op = %op,
9839        connection_id = connection_id.get(),
9840        corr,
9841        "control dispatch"
9842    );
9843}
9844
9845fn log_slow_control_dispatch(
9846    dispatch_started_at: Option<StdInstant>,
9847    op: &'static str,
9848    connection_id: ConnectionId,
9849    corr: u64,
9850    route_open_timings: Option<&RouteOpenTimings>,
9851) {
9852    let Some(dispatch_started_at) = dispatch_started_at else {
9853        return;
9854    };
9855    // Use the same monotonic clock as the phase timers and relay deadline.
9856    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9857    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9858        if let Some(timings) = route_open_timings {
9859            warn!(
9860                op = %op,
9861                connection_id = connection_id.get(),
9862                corr,
9863                elapsed_ms = elapsed.as_millis() as u64,
9864                module_id = ?timings.module_id,
9865                principal = %timings.principal,
9866                admission_ms = timings.admission.as_millis() as u64,
9867                project_root_ms = timings.project_root.as_millis() as u64,
9868                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9869                bind_send_ms = timings.bind_send.as_millis() as u64,
9870                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9871                "slow control dispatch"
9872            );
9873            return;
9874        }
9875        warn!(
9876            op = %op,
9877            connection_id = connection_id.get(),
9878            corr,
9879            elapsed_ms = elapsed.as_millis() as u64,
9880            "slow control dispatch"
9881        );
9882    }
9883}
9884
9885/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9886#[cfg(test)]
9887type TestCallerLookup =
9888    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9889
9890/// Every new client operation needs an explicit privilege decision here.
9891fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9892    request.privileged_operation()
9893}
9894
9895trait PrivilegedRequest {
9896    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9897}
9898
9899impl PrivilegedRequest for ClientControlRequest {
9900    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9901        let request = self;
9902        match request {
9903        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9904            Some(PrivilegedOperation::Restart { module_id })
9905        }
9906        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9907            Some(PrivilegedOperation::Swap { module_id })
9908        }
9909        ClientControlRequest::SupervisorReload { module_id } => {
9910            Some(PrivilegedOperation::Reload { module_id })
9911        }
9912        ClientControlRequest::SupervisorRescan { preview } => {
9913            if *preview {
9914                None
9915            } else {
9916                Some(PrivilegedOperation::Rescan)
9917            }
9918        }
9919        // Only the well-formed apply asks for approval. A preview changes
9920        // nothing, and any other combination is refused before it touches
9921        // anything, so prompting the operator for it would ask about a request
9922        // that cannot run.
9923        ClientControlRequest::SupervisorRescanChecked {
9924            preview,
9925            candidate,
9926            expect,
9927        } => (!*preview && candidate.is_none() && expect.is_some())
9928            .then_some(PrivilegedOperation::Rescan),
9929        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9930            Some(PrivilegedOperation::SetEnabled {
9931                module_id,
9932                enabled: *enabled,
9933            })
9934        }
9935        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9936            Some(PrivilegedOperation::ReleaseReserved { module_id })
9937        }
9938        ClientControlRequest::ServerDescribe {}
9939        // The announcement uses the same client admission as supervisor.restart,
9940        // but cannot stop anything itself and needs no operator confirmation.
9941        | ClientControlRequest::DaemonShutdownIntent { .. }
9942        | ClientControlRequest::CatalogList { .. }
9943        | ClientControlRequest::RouteOpen { .. }
9944        | ClientControlRequest::RoutePoll { .. }
9945        | ClientControlRequest::SupervisorList {}
9946        | ClientControlRequest::SupervisorHealth {}
9947        | ClientControlRequest::SupervisorHealthProbe { .. }
9948        | ClientControlRequest::SupervisorRoutes { .. }
9949        | ClientControlRequest::SupervisorProvenance { .. }
9950        | ClientControlRequest::SupervisorStderrTail { .. }
9951        | ClientControlRequest::SupervisorTerminals { .. }
9952        | ClientControlRequest::SupervisorSpawnSnapshot {}
9953        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9954    }
9955    }
9956}
9957
9958fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9959    match request {
9960        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9961        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9962        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
9963        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
9964        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
9965        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
9966        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
9967        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
9968        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
9969        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
9970        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
9971        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
9972        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
9973        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
9974        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
9975        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
9976        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
9977        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
9978        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
9979        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
9980        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
9981    }
9982}
9983
9984/// The caller of one `route.open`, as its `route.open refused` line names it.
9985///
9986/// A connection id alone cannot name a caller after the fact: ids restart at
9987/// every daemon restart, so the same number belongs to different modules
9988/// before and after one. These three fields are what the refused line needs
9989/// to be attributable on its own, and they are rendered with the same helpers
9990/// as the `route.open accepted` line so both directions grep alike.
9991struct RouteOpenCaller {
9992    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
9993    /// when the request presented a consumer identity whose launch nonce did
9994    /// not verify. The claimed module id is never printed as a principal.
9995    principal: String,
9996    /// `none` for an unscoped open; the admitted stamp's label once scope
9997    /// admission issued one; before that, the requested selector's label.
9998    scope: String,
9999    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
10000    /// because it is a string the caller chose.
10001    harness: String,
10002}
10003
10004impl RouteOpenCaller {
10005    fn new(
10006        principal: Option<&Principal>,
10007        scope: Option<&ScopeSelector>,
10008        identity: &BindIdentity,
10009    ) -> Self {
10010        Self {
10011            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
10012            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
10013            harness: bounded_log_text(&identity.harness),
10014        }
10015    }
10016
10017    /// For a refusal that has no parsed request at hand: names whatever the
10018    /// frame still says, and `unknown` where it says nothing parseable.
10019    fn unknown() -> Self {
10020        Self {
10021            principal: "unknown".to_string(),
10022            scope: "unknown".to_string(),
10023            harness: "unknown".to_string(),
10024        }
10025    }
10026}
10027
10028/// Longest client-chosen text (a scope ref, a harness) a route.open log line
10029/// prints before cutting it.
10030const MAX_LOGGED_TEXT_CHARS: usize = 64;
10031
10032/// `value` Debug-quoted, so control characters land escaped and cannot forge
10033/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
10034/// `…` inside the quotes so one request cannot flood the line.
10035fn bounded_log_text(value: &str) -> String {
10036    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
10037    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
10038        bounded.push('…');
10039    }
10040    format!("{bounded:?}")
10041}
10042
10043/// The `scope=` field of the `route.open accepted` line, from the stamp that
10044/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
10045/// so a ref holding control characters cannot forge a log line, and cut to 64
10046/// characters with a trailing `…` to bound the line. The bind proof and the
10047/// scope's attributes never appear.
10048fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
10049    use subc_protocol::scope::ScopeKind;
10050    let kind = match stamp.kind {
10051        ScopeKind::Head => "head",
10052        ScopeKind::Worker => "worker",
10053        ScopeKind::Ephemeral => "ephemeral",
10054        ScopeKind::Federated => "federated",
10055        _ => "unknown",
10056    };
10057    format!(
10058        "{kind}/{}/{}@{}",
10059        principal_label(&stamp.owner),
10060        bounded_log_text(&stamp.scope_ref),
10061        stamp.scope_epoch
10062    )
10063}
10064
10065/// The `scope=` field of a `route.open refused` line for an open refused
10066/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
10067/// The kind is not known yet, so the literal `requested` stands in its place.
10068/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
10069/// owner it has not been checked against the configured modules: a quoted
10070/// owner means the value was never validated. The bind proof never appears.
10071fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10072    let epoch = selector
10073        .scope_epoch
10074        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10075    format!(
10076        "requested/{}/{}@{epoch}",
10077        bounded_log_text(&principal_label(&selector.owner)),
10078        bounded_log_text(&selector.scope_ref),
10079    )
10080}
10081
10082fn principal_label(principal: &Principal) -> String {
10083    match principal {
10084        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10085        Principal::Direct => "direct".to_string(),
10086        other => format!("{other:?}"),
10087    }
10088}
10089
10090fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10091    match request {
10092        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10093        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10094            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10095        }
10096        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10097        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10098        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10099        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10100        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10101            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10102        }
10103        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10104        _ => "unsupported",
10105    }
10106}
10107
10108fn parse_client_control_request(
10109    body: &[u8],
10110) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10111    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10112        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10113            Ok(probe)
10114                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10115                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10116            {
10117                ControlRequestBodyError::InvalidBody
10118            }
10119            Ok(_) => ControlRequestBodyError::UnknownOp,
10120            Err(_) => ControlRequestBodyError::InvalidBody,
10121        };
10122        (err, classification)
10123    })
10124}
10125
10126fn parse_module_control_request_from_module(
10127    body: &[u8],
10128) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10129    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10130        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10131            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10132            Ok(_) => ControlRequestBodyError::UnknownOp,
10133            Err(_) => ControlRequestBodyError::InvalidBody,
10134        };
10135        (err, classification)
10136    })
10137}
10138
10139#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10140enum ProviderRoleKind {
10141    ToolProvider,
10142    PipelineStage,
10143    ManagementSurface,
10144    InternalService,
10145}
10146
10147fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10148    match role {
10149        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10150        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10151        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10152        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10153    }
10154}
10155
10156fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10157    roles.iter().map(provider_role_kind).collect()
10158}
10159
10160/// Most refused scope records named individually in the log per sync; the
10161/// `refused` count on the accepted line is always complete.
10162const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10163
10164/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10165#[derive(Debug, Default, PartialEq, Eq)]
10166struct ScopeOutcomeCounts {
10167    created: usize,
10168    replaced: usize,
10169    updated: usize,
10170    unchanged: usize,
10171    refused: usize,
10172}
10173
10174impl ScopeOutcomeCounts {
10175    fn of(results: &[ScopeRecordResult]) -> Self {
10176        let mut counts = Self::default();
10177        for result in results {
10178            let slot = match result.outcome {
10179                ScopeRecordOutcome::Created => &mut counts.created,
10180                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10181                ScopeRecordOutcome::Updated => &mut counts.updated,
10182                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10183                ScopeRecordOutcome::Refused => &mut counts.refused,
10184            };
10185            *slot += 1;
10186        }
10187        counts
10188    }
10189}
10190
10191#[cfg(test)]
10192mod scope_outcome_count_tests {
10193    use super::*;
10194
10195    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10196        ScopeRecordResult {
10197            scope_ref: "r".to_string(),
10198            scope_epoch: 1,
10199            outcome,
10200            code: None,
10201            message: None,
10202            version: None,
10203            parent_state: None,
10204        }
10205    }
10206
10207    /// Each outcome lands in its own count, so a refused record can never be
10208    /// hidden inside the total the log already printed.
10209    #[test]
10210    fn every_outcome_is_counted_in_its_own_field() {
10211        let results = [
10212            result(ScopeRecordOutcome::Created),
10213            result(ScopeRecordOutcome::Created),
10214            result(ScopeRecordOutcome::Replaced),
10215            result(ScopeRecordOutcome::Updated),
10216            result(ScopeRecordOutcome::Unchanged),
10217            result(ScopeRecordOutcome::Refused),
10218            result(ScopeRecordOutcome::Refused),
10219            result(ScopeRecordOutcome::Refused),
10220        ];
10221        assert_eq!(
10222            ScopeOutcomeCounts::of(&results),
10223            ScopeOutcomeCounts {
10224                created: 2,
10225                replaced: 1,
10226                updated: 1,
10227                unchanged: 1,
10228                refused: 3,
10229            }
10230        );
10231    }
10232}
10233
10234/// Return whether a catalog change can create a newly violating live route.
10235/// Removing an attested claim is intentionally excluded: it makes fewer routes
10236/// forbidden and therefore must leave the existing route census untouched.
10237fn capability_census_trigger(
10238    old: Option<&CapabilityDeclarations>,
10239    new: Option<&CapabilityDeclarations>,
10240) -> bool {
10241    let old_provides = old
10242        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10243        .unwrap_or_default();
10244    let old_denies = old
10245        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10246        .unwrap_or_default();
10247    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10248        provides: Vec::new(),
10249        requires: Vec::new(),
10250        must_never_reach: Vec::new(),
10251    });
10252
10253    new.provides
10254        .iter()
10255        .any(|capability| !old_provides.contains(capability))
10256        || new
10257            .must_never_reach
10258            .iter()
10259            .any(|capability| !old_denies.contains(capability))
10260}
10261
10262fn catalog_update_frozen_field_message(
10263    registered: &ModuleManifest,
10264    provides: &[ProviderRole],
10265) -> Option<String> {
10266    let old_has_provides = !registered.provides.is_empty();
10267    let new_has_provides = !provides.is_empty();
10268    if old_has_provides != new_has_provides {
10269        return Some(format!(
10270            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10271            registered.module_id
10272        ));
10273    }
10274
10275    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10276        return Some(format!(
10277            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10278            registered.module_id
10279        ));
10280    }
10281
10282    let registered_concurrency = manifest_concurrency(registered);
10283    let mut candidate = registered.clone();
10284    candidate.provides = provides.to_vec();
10285    let candidate_concurrency = manifest_concurrency(&candidate);
10286    if candidate_concurrency != registered_concurrency {
10287        return Some(format!(
10288            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10289            registered.module_id, registered_concurrency, candidate_concurrency
10290        ));
10291    }
10292
10293    // control_ops live beside the manifest in the HELLO body, not inside
10294    // ModuleManifest, so a provides-only catalog.update cannot change them.
10295    None
10296}
10297
10298fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10299    manifest.provides.iter().any(is_routable_role)
10300}
10301
10302/// Returns the routable-provider concurrency subc should enforce for this manifest.
10303///
10304/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10305/// InternalService has no role-specific concurrency field, so it retains the
10306/// existing ModuleManaged default for backward compatibility.
10307fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10308    manifest
10309        .provides
10310        .iter()
10311        .find_map(|provider| match provider {
10312            ProviderRole::ToolProvider { concurrency, .. }
10313            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10314            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10315        })
10316        .unwrap_or(Concurrency::ModuleManaged)
10317}
10318
10319/// True when the manifest carries a ManagementSurface role whose concurrency
10320/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10321/// bytes because the typed manifest deliberately erases that distinction: the
10322/// default exists for wire compatibility, and this probe exists so the default
10323/// stays observable. Any parse irregularity returns false -- the caller only
10324/// logs, and a malformed body already failed registration upstream.
10325fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10326    let has_management_surface = manifest
10327        .provides
10328        .iter()
10329        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10330    if !has_management_surface {
10331        return false;
10332    }
10333    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10334        return false;
10335    };
10336    let Some(provides) = raw
10337        .get("manifest")
10338        .and_then(|manifest| manifest.get("provides"))
10339        .and_then(serde_json::Value::as_array)
10340    else {
10341        return false;
10342    };
10343    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10344    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10345    // against the management_surface_manifest_without_concurrency golden, not
10346    // recalled (the externally-tagged guess was this function's first bug).
10347    provides.iter().any(|role| {
10348        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10349            && role.get("concurrency").is_none()
10350    })
10351}
10352
10353fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10354    if peer_version != PROTOCOL_VERSION {
10355        return Err(format!(
10356            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10357        ));
10358    }
10359    Ok(PROTOCOL_VERSION)
10360}
10361
10362fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10363    Frame::build_with_version(
10364        response_version(frame),
10365        FrameType::Pong,
10366        frame.header.flags,
10367        0,
10368        0,
10369        frame.header.corr,
10370        Vec::new(),
10371    )
10372    .map_err(RouterError::FrameBuild)
10373}
10374
10375pub(crate) fn control_error_frame(
10376    frame: &Frame,
10377    code: &'static str,
10378    message: impl Into<String>,
10379) -> Result<Frame, RouterError> {
10380    control_error_body_frame(
10381        frame,
10382        ErrorBody {
10383            code: code.to_string(),
10384            message: message.into(),
10385            detail: None,
10386        },
10387    )
10388}
10389
10390/// A channel-0 ERROR for a refusal the daemon decided itself: every
10391/// route.open refusal, the drain `module_reloading` and scope-change/end
10392/// bodies, spawn-subscription and supervisor refusals. Carries the
10393/// daemon-origin bit, which is what lets a client treat `module_reloading`
10394/// as proof that its request never reached a module. Response, push,
10395/// goodbye and relay-request frames keep the plain control flags in their
10396/// own builders.
10397pub(crate) fn control_error_body_frame(
10398    frame: &Frame,
10399    error: ErrorBody,
10400) -> Result<Frame, RouterError> {
10401    control_error_frame_with_flags(frame, error, daemon_error_flags())
10402}
10403
10404/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10405/// refused route.bind answered as a route.open refusal, or a refused
10406/// module-control RPC. Plain control flags — the code and message are
10407/// module-chosen, so the frame must not claim daemon authorship, even when
10408/// the module picks a daemon code like `module_reloading`.
10409fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10410    control_error_frame_with_flags(frame, error, control_flags())
10411}
10412
10413fn control_error_frame_with_flags(
10414    frame: &Frame,
10415    error: ErrorBody,
10416    flags: Flags,
10417) -> Result<Frame, RouterError> {
10418    let body = serde_json::to_vec(&error).map_err(|err| {
10419        RouterError::backend(
10420            0,
10421            frame.header.corr,
10422            format!("failed to encode control ERROR: {err}"),
10423        )
10424    })?;
10425
10426    Frame::build_with_version(
10427        response_version(frame),
10428        FrameType::Error,
10429        flags,
10430        0,
10431        0,
10432        frame.header.corr,
10433        body,
10434    )
10435    .map_err(RouterError::FrameBuild)
10436}
10437
10438pub(crate) fn control_response_body_frame<T: Serialize>(
10439    frame: &Frame,
10440    reply: &T,
10441    label: &'static str,
10442) -> Result<Frame, RouterError> {
10443    let body = serde_json::to_vec(reply).map_err(|err| {
10444        RouterError::backend(
10445            0,
10446            frame.header.corr,
10447            format!("failed to encode {label}: {err}"),
10448        )
10449    })?;
10450
10451    Frame::build_with_version(
10452        response_version(frame),
10453        FrameType::Response,
10454        control_flags(),
10455        0,
10456        0,
10457        frame.header.corr,
10458        body,
10459    )
10460    .map_err(RouterError::FrameBuild)
10461}
10462
10463/// Map a forwarding failure to the wire code a client sees.
10464///
10465/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10466/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10467/// chosen here decides whether a caller retries or gives up.
10468///
10469/// That makes attribution the load-bearing property, not merely having a code. A
10470/// permanent fault published as a retryable one produces a fleet-wide retry storm
10471/// against something that can never recover; a transient fault published as
10472/// permanent gives up on work that would have succeeded. Both look correct in a
10473/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10474/// the mapping per variant rather than merely asserting that some code exists.
10475///
10476/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10477/// two codes on the same side of the boundary passes it. Measured rather than
10478/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10479/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10480/// a test named for something else that happens to assert the string.
10481///
10482/// That accidental coverage is deliberately left alone rather than promoted to a
10483/// named test, because it guards a property this function does not promise.
10484/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10485/// specific code within a class, so identity is free to change and only the
10486/// partition is a contract. Splitting it out would assert a guarantee nothing
10487/// depends on — and a suite that promises more than the code does is the harder
10488/// thing to correct later, because the next reader cannot tell which assertions
10489/// are load-bearing.
10490///
10491/// Pin identity here the moment a consumer branches on a specific code.
10492/// The spawn a HELLO would register as and the provider declarations it
10493/// requests, carried from the HELLO's checks to the point the registry
10494/// accepts it.
10495struct HelloAuthority {
10496    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10497    requested: ProviderDeclarations,
10498    /// Whether admitting this HELLO froze the spawn's requested declarations,
10499    /// so a refusal after admission undoes that freeze and no other.
10500    froze: std::sync::atomic::AtomicBool,
10501}
10502
10503fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10504    match err {
10505        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10506        ForwardingError::NoModuleConnection => "target_unavailable",
10507        ForwardingError::ModuleReloading { .. } => "module_reloading",
10508        ForwardingError::ClientRouteChannelExhausted { .. }
10509        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10510        ForwardingError::StaleModuleEndpoint
10511        | ForwardingError::UnknownReservation { .. }
10512        | ForwardingError::ConnectionClosing { .. }
10513        | ForwardingError::ClientEgressClosed { .. }
10514        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10515        // Only a swap candidate's registration can produce this, and it means
10516        // exactly what a second active HELLO for a live id means.
10517        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10518        ForwardingError::RelayCorrelationExhausted
10519        | ForwardingError::RouteOpenBuild(_)
10520        | ForwardingError::Poisoned => "forwarding_error",
10521    }
10522}
10523
10524fn response_version(frame: &Frame) -> u8 {
10525    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10526        frame.header.ver
10527    } else {
10528        PROTOCOL_VERSION
10529    }
10530}
10531
10532pub(crate) fn control_flags() -> Flags {
10533    Flags::new(false, Priority::Passive, false)
10534}
10535
10536/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10537/// channel. The target is the module (a client never saw the route), so this
10538/// takes the module path: delivered late rather than dropped when the module's
10539/// queue is momentarily full, and never closing its connection.
10540fn send_goodbye_target_best_effort(
10541    counters: &DaemonCounters,
10542    target: &GoodbyeTarget,
10543    context: &'static str,
10544) {
10545    let Ok(frame) = Frame::build_with_version(
10546        target.negotiated_ver,
10547        FrameType::Goodbye,
10548        control_flags(),
10549        target.channel,
10550        target.epoch,
10551        0,
10552        Vec::new(),
10553    ) else {
10554        return;
10555    };
10556    crate::forwarding::send_module_route_goodbye(
10557        counters,
10558        &target.sink,
10559        frame,
10560        target.module_id.as_deref(),
10561        context,
10562    );
10563}
10564
10565fn route_close_reason_for_opener(
10566    reason: RouteCloseReason,
10567    accepts_close_reasons: Option<&[String]>,
10568) -> RouteCloseReason {
10569    if reason == RouteCloseReason::AuthorityChanged
10570        && !accepts_close_reasons
10571            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10572    {
10573        // Older readers forbid reopening for unknown reasons. Reload already
10574        // permits reopening and, like an authority change, requires a new bind.
10575        RouteCloseReason::Reload
10576    } else {
10577        reason
10578    }
10579}
10580
10581pub(crate) fn send_route_control_pushes(
10582    forwarding: &ForwardingTable,
10583    routes: Vec<EndpointRoute>,
10584    push: ClientControlPush,
10585) {
10586    let reason = match &push {
10587        ClientControlPush::RouteClosing { reason, .. }
10588        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10589    };
10590    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10591    for route in routes {
10592        let recipient_reason =
10593            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10594        let target = route.goodbye_target;
10595        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10596            existing.connection_id == target.connection_id && *reason == recipient_reason
10597        }) {
10598            debug_assert_eq!(
10599                existing.negotiated_ver, target.negotiated_ver,
10600                "one connection cannot negotiate multiple frame versions"
10601            );
10602            if !channels.contains(&target.channel) {
10603                channels.push(target.channel);
10604            }
10605            continue;
10606        }
10607        let channel = target.channel;
10608        targets.push((target, recipient_reason, vec![channel]));
10609    }
10610    for (target, recipient_reason, mut channels) in targets {
10611        channels.sort_unstable();
10612        let mut push = push.clone();
10613        match &mut push {
10614            ClientControlPush::RouteClosing {
10615                channels: covered,
10616                reason,
10617                ..
10618            }
10619            | ClientControlPush::RouteClosed {
10620                channels: covered,
10621                reason,
10622                ..
10623            } => {
10624                *covered = channels;
10625                *reason = recipient_reason;
10626            }
10627        }
10628        let body = match serde_json::to_vec(&push) {
10629            Ok(body) => body,
10630            Err(err) => {
10631                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10632                continue;
10633            }
10634        };
10635        let frame = match Frame::build_with_version(
10636            target.negotiated_ver,
10637            FrameType::Push,
10638            control_flags(),
10639            0,
10640            0,
10641            0,
10642            body.clone(),
10643        ) {
10644            Ok(frame) => frame,
10645            Err(err) => {
10646                warn!(
10647                    route_channel = target.channel,
10648                    error = %err,
10649                    "failed to build route lifecycle control PUSH frame"
10650                );
10651                continue;
10652            }
10653        };
10654        if let Err(err) = target.sink.try_send(frame) {
10655            if target.close_on_delivery_failure() {
10656                warn!(
10657                    target_connection_id = target.connection_id.get(),
10658                    route_channel = target.channel,
10659                    error = %err,
10660                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10661                );
10662                let _ = forwarding.escalate_client_delivery_failure(
10663                    target.connection_id,
10664                    target.channel,
10665                    target.epoch,
10666                    CloseReason::new(
10667                        "route_lifecycle_push_delivery_failed",
10668                        format!(
10669                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10670                            target.channel
10671                        ),
10672                    ),
10673                    crate::forwarding::UndeliveredFrame {
10674                        module_id: target.module_id.as_deref(),
10675                        sink: &target.sink,
10676                    },
10677                );
10678            }
10679        }
10680    }
10681}
10682
10683#[cfg(test)]
10684mod tests {
10685    include!("control/agent_commands_tests.rs");
10686    include!("control/supervisor_health_vectors_tests.rs");
10687    include!("control/resource_revision_tests.rs");
10688    include!("control/route_open_recovery_tests.rs");
10689    #[tokio::test]
10690    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10691        let registry = Arc::new(Registry::default());
10692        let handler = ControlHandler::new(registry);
10693        assert_eq!(
10694            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10695            None
10696        );
10697        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10698        hello_via_sink(
10699            &handler,
10700            &ctx,
10701            &mut rx,
10702            hello_frame("daemon", PROTOCOL_VERSION, 1),
10703        )
10704        .await;
10705        assert_eq!(
10706            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10707            Some("daemon".into())
10708        );
10709        assert_eq!(
10710            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10711            None
10712        );
10713        assert_eq!(
10714            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10715            None,
10716            "a registered module is not necessarily supervised"
10717        );
10718        assert_eq!(
10719            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10720            None,
10721            "aggregate provenance has no single target"
10722        );
10723        assert_eq!(
10724            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10725            None
10726        );
10727    }
10728
10729    mod peer_manifest {
10730        include!("peer_manifest_tests.rs");
10731    }
10732    mod catalog_declarations {
10733        include!("control/catalog_tests.rs");
10734    }
10735    mod activity_read {
10736        include!("activity_read_tests.rs");
10737    }
10738
10739    mod lifecycle_activity {
10740        include!("control_lifecycle_tests.rs");
10741    }
10742    #[cfg(unix)]
10743    #[tokio::test]
10744    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10745        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10746        let path = dir.join("subc.jsonc");
10747        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10748            "program":"/bin/sleep","args":["60"],"protocol":"none",
10749            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10750        }}}).to_string()).unwrap();
10751        let mut configured = crate::daemon_config::load(&path)
10752            .unwrap()
10753            .unwrap()
10754            .modules
10755            .pop()
10756            .unwrap();
10757        let registry = std::sync::Arc::new(crate::Registry::default());
10758        let handle = crate::SupervisorHandle::new();
10759        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10760            .with_handle(handle.clone());
10761        let module = supervisor
10762            .supervise_configured_with_health(
10763                configured.module_spec(),
10764                true,
10765                configured.health.clone(),
10766                None,
10767                configured.restart,
10768            )
10769            .unwrap();
10770        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10771        let before = module.status().unwrap().pid;
10772        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10773        configured.health.cadence = std::time::Duration::from_secs(3600);
10774        let health_only = handler
10775            .reconcile_supervised_modules(
10776                &supervisor,
10777                vec![configured.clone()],
10778                false,
10779                Principal::Direct,
10780            )
10781            .await
10782            .unwrap();
10783        assert!(
10784            health_only.0.changed_pending_reload.is_empty(),
10785            "health policy is already applied live"
10786        );
10787        assert_eq!(module.status().unwrap().pid, before);
10788        assert_eq!(
10789            module.configuration().unwrap().1.http,
10790            configured.health.http
10791        );
10792        configured.args = vec!["61".into()];
10793        let launch = handler
10794            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10795            .await
10796            .unwrap();
10797        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10798        assert_eq!(
10799            module.status().unwrap().pid,
10800            before,
10801            "a launch edit is stored until reload"
10802        );
10803        module.drain().await.unwrap();
10804    }
10805    use cortexkit_test_support::ScratchDir;
10806    use std::{
10807        collections::BTreeMap,
10808        fmt,
10809        path::PathBuf,
10810        sync::{Arc, Mutex},
10811        time::Duration,
10812    };
10813
10814    use serde_json::{json, Value};
10815    use subc_protocol::{
10816        manifest::{
10817            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10818            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10819        },
10820        session::HealthStatus,
10821        FrameType,
10822    };
10823
10824    use super::*;
10825    use crate::{
10826        forwarding::{DataRoute, DataRouteState},
10827        registry::ChannelState,
10828        router::FrameSink,
10829        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10830        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10831        RouteCtx, Router,
10832    };
10833    use tokio::{
10834        sync::mpsc,
10835        time::{sleep, Instant},
10836    };
10837    use tracing::{
10838        field::{Field, Visit},
10839        Event, Subscriber,
10840    };
10841    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10842
10843    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10844    ///
10845    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10846    /// is only populated for `tests/*.rs` integration test binaries -- this file
10847    /// compiles as part of the library target, which gets neither. The binary
10848    /// lives in the profile folder this test was built into,
10849    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10850    /// from the test's own path.
10851    ///
10852    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10853    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10854    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10855    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10856    /// `NotFound`, which reads as a broken test rather than an unbuilt
10857    /// dependency -- so state the cause and the remedy instead. Deliberately a
10858    /// panic and not a silent skip: a test that quietly passes when it could not
10859    /// run is worse than one that fails, because it reports health it never
10860    /// verified.
10861    fn fake_aft_stub_path() -> PathBuf {
10862        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10863        assert!(
10864            path.exists(),
10865            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10866             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10867            path.display()
10868        );
10869        path
10870    }
10871
10872    /// Whether clients retry `code` in place: the predicate itself, never a copy
10873    /// of its set. A copied list breaks silently when a code is added to or
10874    /// removed from the real one, and a stale copy here would let exactly the
10875    /// failure this test exists to catch pass.
10876    fn client_retries(code: &str) -> bool {
10877        subc_protocol::error_codes::is_retryable_route_open(code)
10878    }
10879
10880    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10881    /// of failure is worse than publishing none. A permanent fault dressed as
10882    /// retryable makes every client in the fleet retry forever against something
10883    /// that cannot recover; a transient fault dressed as permanent abandons work
10884    /// that would have succeeded.
10885    ///
10886    /// Asserting "a code exists" cannot catch either, because the string is free
10887    /// to say anything. This enumerates every variant and pins which side of the
10888    /// retry boundary it lands on, so a new variant must be classified here
10889    /// deliberately rather than inheriting whichever arm it was appended to.
10890    #[test]
10891    fn retryability_of_forwarding_codes_matches_the_failure() {
10892        // Transient by nature: the target is booting, reloading, or its endpoint
10893        // was swapped mid-flight. Retrying is how these resolve.
10894        let transient = [
10895            ForwardingError::NoModuleConnection,
10896            ForwardingError::ModuleReloading {
10897                module_id: "m".into(),
10898            },
10899            ForwardingError::StaleModuleEndpoint,
10900            ForwardingError::UnknownReservation {
10901                client_channel: 1,
10902                module_channel: 1,
10903            },
10904            ForwardingError::ConnectionClosing {
10905                connection_id: ConnectionId::new(1),
10906            },
10907            ForwardingError::ClientEgressClosed {
10908                connection_id: ConnectionId::new(1),
10909            },
10910            ForwardingError::ModuleEgressUnavailable {
10911                connection_id: ConnectionId::new(1),
10912            },
10913        ];
10914        for err in transient {
10915            let code = forwarding_error_code(&err);
10916            assert!(
10917                client_retries(code),
10918                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10919            );
10920        }
10921
10922        // Not fixed by retrying. Channel and correlation exhaustion need the
10923        // caller to close routes, and a poisoned lock is a daemon that cannot
10924        // recover at all — the worst thing to advertise as retryable, since every
10925        // client would storm a daemon that will never answer.
10926        let permanent = [
10927            ForwardingError::ConnectionRoleConflict {
10928                connection_id: ConnectionId::new(1),
10929            },
10930            ForwardingError::ClientRouteChannelExhausted {
10931                connection_id: ConnectionId::new(1),
10932            },
10933            ForwardingError::ModuleRouteChannelExhausted {
10934                endpoint: ModuleEndpointId {
10935                    connection_id: ConnectionId::new(1),
10936                    generation: 1,
10937                },
10938            },
10939            ForwardingError::RelayCorrelationExhausted,
10940            ForwardingError::RouteOpenBuild("x".into()),
10941            ForwardingError::Poisoned,
10942        ];
10943        for err in permanent {
10944            let code = forwarding_error_code(&err);
10945            assert!(
10946                !client_retries(code),
10947                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10948            );
10949        }
10950    }
10951
10952    /// The principal is the daemon's answer to "who is calling", and modules
10953    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10954    /// plexus gates connector invocation. So a stamp is an authorization input in
10955    /// another process, not a label — and both possible answers SUCCEED, which is
10956    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10957    /// first-party capability to something that never proved it; a supervised one
10958    /// stamped `Direct` silently strips a module of capability it is entitled to.
10959    ///
10960    /// Neither shows up in a test that only checks the bind succeeded. Before this
10961    /// test the only coverage was accidental —
10962    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
10963    /// stamped principal on its way past, so narrowing that wire-shape test to its
10964    /// stated subject would have deleted the last assertion on this value. It
10965    /// still asserts the stamp, which is now redundancy rather than the only
10966    /// guard: both fail under the same mutation, and this one names the reason.
10967    /// SCOPE: this handler's supervisor has spawned nothing, so
10968    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
10969    /// is unreachable here. Both assertions below are refusals, and a mutant that
10970    /// refuses everything would satisfy them.
10971    ///
10972    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
10973    /// spawns a supervised consumer, reads its live nonce, and asserts the module
10974    /// observed `principal.kind == "reserved"` carrying that module_id — verified
10975    /// at source rather than assumed, since a citation is a claim about another
10976    /// file and ages like one. Recorded because a harness that structurally
10977    /// cannot reach an arm reports "none" for that arm identically to one that
10978    /// covers it and found nothing.
10979    #[tokio::test]
10980    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
10981        let handler = ControlHandler::default();
10982        let frame =
10983            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
10984
10985        // Absent consumer_identity is the ordinary case: a human at a terminal, or
10986        // any process holding the connection file. Nothing was proved, so nothing
10987        // may be granted beyond the unattested floor.
10988        let stamped = handler
10989            .route_open_principal(ConnectionId::new(1), &frame, None)
10990            .unwrap()
10991            .unwrap();
10992        assert_eq!(
10993            stamped,
10994            Principal::Direct,
10995            "a caller that proved nothing must not be stamped as a supervised module"
10996        );
10997
10998        // A claimed module_id with a nonce no supervised child was given is a
10999        // forgery attempt, not a weaker caller: it must be REFUSED rather than
11000        // quietly demoted to Direct, or an impersonation attempt looks identical
11001        // to an ordinary unattested connection.
11002        let forged = handler
11003            .route_open_principal(
11004                ConnectionId::new(1),
11005                &frame,
11006                Some(ConsumerIdentity {
11007                    module_id: "aft".to_string(),
11008                    launch_nonce: "not-a-real-nonce".to_string(),
11009                }),
11010            )
11011            .unwrap();
11012        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
11013        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
11014    }
11015
11016    /// The test above hands `route_open_principal` an identity it built itself,
11017    /// which proves the stamping rule and nothing about where the identity comes
11018    /// from. The real producer is a wire body, and the two are joined by a serde
11019    /// field name that nothing else asserts.
11020    ///
11021    /// That join fails quietly in one specific way: an unrecognised key is simply
11022    /// absent after parsing, so a renamed or misspelled `consumer_identity`
11023    /// yields `None` and every supervised module silently drops to `Direct`.
11024    /// Capability-wise that is the safe direction, but it surfaces far from its
11025    /// cause — as a module mysteriously refused bash — and it would pass every
11026    /// test that builds its own input.
11027    ///
11028    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
11029    /// would break every client the moment the daemon gains a field, trading a
11030    /// quiet demotion for a hard refusal on additive change. Asserting the join
11031    /// instead means a rename breaks a test here rather than the fleet.
11032    #[test]
11033    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
11034        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"}}"#;
11035        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
11036        let ClientControlRequest::RouteOpen {
11037            consumer_identity, ..
11038        } = parsed
11039        else {
11040            panic!("route.open body must parse as RouteOpen");
11041        };
11042        assert_eq!(
11043            consumer_identity,
11044            Some(ConsumerIdentity {
11045                module_id: "aft".to_string(),
11046                launch_nonce: "n".to_string(),
11047            }),
11048            "the wire field name must reach the value route_open_principal reads"
11049        );
11050    }
11051
11052    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
11053        ModuleManifest::builder(module_id, "0.1.0")
11054            .protocol_ver(protocol_ver)
11055            .provides(vec![ProviderRole::ToolProvider {
11056                tools: vec![Tool {
11057                    name: "read".to_string(),
11058                    description: None,
11059                    execution_mode: ExecutionMode::Pure,
11060                    schema: json!({"type": "object"}),
11061                }],
11062                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
11063                concurrency: Concurrency::ModuleManaged,
11064                emits_push: true,
11065                sub_supervises: true,
11066            }])
11067            .build()
11068    }
11069
11070    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11071        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11072    }
11073
11074    fn hello_frame_with_control_ops(
11075        module_id: &str,
11076        protocol_ver: u8,
11077        corr: u64,
11078        control_ops: Option<Vec<String>>,
11079    ) -> Frame {
11080        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11081    }
11082
11083    fn hello_frame_with_nonce(
11084        module_id: &str,
11085        protocol_ver: u8,
11086        corr: u64,
11087        launch_nonce: Option<&str>,
11088    ) -> Frame {
11089        hello_frame_full(
11090            module_id,
11091            protocol_ver,
11092            corr,
11093            None,
11094            launch_nonce.map(ToOwned::to_owned),
11095        )
11096    }
11097
11098    fn hello_frame_full(
11099        module_id: &str,
11100        protocol_ver: u8,
11101        corr: u64,
11102        control_ops: Option<Vec<String>>,
11103        launch_nonce: Option<String>,
11104    ) -> Frame {
11105        let body = serde_json::to_vec(&ModuleHelloBody {
11106            manifest: manifest(module_id, protocol_ver),
11107            protocol_ver,
11108            control_ops,
11109            launch_nonce,
11110        })
11111        .unwrap();
11112        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11113    }
11114
11115    fn hello_frame_with_rich_ui(
11116        module_id: &str,
11117        protocol_ver: u8,
11118        corr: u64,
11119        launch_nonce: Option<&str>,
11120        rich_ui: Value,
11121    ) -> Frame {
11122        let mut body = serde_json::to_value(ModuleHelloBody {
11123            manifest: manifest(module_id, protocol_ver),
11124            protocol_ver,
11125            control_ops: None,
11126            launch_nonce: launch_nonce.map(str::to_string),
11127        })
11128        .unwrap();
11129        body["manifest"]["rich_ui"] = rich_ui;
11130        Frame::build(
11131            FrameType::Hello,
11132            control_flags(),
11133            0,
11134            0,
11135            corr,
11136            serde_json::to_vec(&body).unwrap(),
11137        )
11138        .unwrap()
11139    }
11140
11141    fn non_routable_hello_frame_with_control_ops(
11142        module_id: &str,
11143        corr: u64,
11144        control_ops: Option<Vec<String>>,
11145    ) -> Frame {
11146        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11147        manifest.provides.clear();
11148        let body = serde_json::to_vec(&ModuleHelloBody {
11149            manifest,
11150            protocol_ver: PROTOCOL_VERSION,
11151            control_ops,
11152            launch_nonce: None,
11153        })
11154        .unwrap();
11155        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11156    }
11157
11158    fn capability_grammar_hello_frame(
11159        capabilities: Value,
11160        runtime_computed: Option<Value>,
11161        corr: u64,
11162    ) -> Frame {
11163        let mut body = serde_json::to_value(ModuleHelloBody {
11164            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11165            protocol_ver: PROTOCOL_VERSION,
11166            control_ops: None,
11167            launch_nonce: None,
11168        })
11169        .expect("HELLO body serializes");
11170        body["manifest"]["capabilities"] = capabilities;
11171        if let Some(runtime_computed) = runtime_computed {
11172            body["runtime_computed"] = runtime_computed;
11173        }
11174        Frame::build(
11175            FrameType::Hello,
11176            control_flags(),
11177            0,
11178            0,
11179            corr,
11180            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11181        )
11182        .expect("HELLO frame builds")
11183    }
11184
11185    fn channel_request(channel: u16, corr: u64) -> Frame {
11186        Frame::build(
11187            FrameType::Request,
11188            Flags::new(true, Priority::Interactive, false),
11189            channel,
11190            0,
11191            corr,
11192            b"opaque".to_vec(),
11193        )
11194        .unwrap()
11195    }
11196
11197    fn route_ctx(
11198        connection_id: ConnectionId,
11199    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11200        let (tx, rx) = mpsc::channel(8);
11201        (
11202            RouteCtx {
11203                connection_id,
11204                egress: FrameSink::new(tx),
11205            },
11206            rx,
11207        )
11208    }
11209
11210    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11211        serde_json::from_slice(&frame.body).unwrap()
11212    }
11213
11214    /// Register a module over a connection that has a sink and return the
11215    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11216    /// module's own sink rather than returning it as a reply, so the ack is
11217    /// taken off `rx` here and whatever the test reads next is what followed it.
11218    async fn hello_via_sink(
11219        handler: &ControlHandler,
11220        ctx: &RouteCtx,
11221        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11222        hello: Frame,
11223    ) -> Frame {
11224        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11225        assert!(
11226            replies.is_empty(),
11227            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11228        );
11229        let ack = rx
11230            .try_recv()
11231            .expect("HELLO_ACK is queued on the module sink")
11232            .frame;
11233        assert_eq!(ack.header.ty, FrameType::HelloAck);
11234        ack
11235    }
11236
11237    fn parse_error(frame: &Frame) -> Value {
11238        serde_json::from_slice(&frame.body).unwrap()
11239    }
11240
11241    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11242        serde_json::from_slice(&frame.body).unwrap()
11243    }
11244
11245    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11246        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11247            route_channel,
11248            route_epoch: 0,
11249            kind,
11250        })
11251        .unwrap();
11252        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11253    }
11254
11255    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11256        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11257            module_id: module_id.to_string(),
11258        })
11259        .unwrap();
11260        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11261    }
11262
11263    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11264        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11265    }
11266
11267    // Exercise retired opener fields without putting them back in BindIdentity.
11268    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11269        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11270        let mut frame = route_open_frame(corr, module_id, root);
11271        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11272        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11273        frame.body = serde_json::to_vec(&body).unwrap();
11274        frame
11275    }
11276
11277    fn route_open_frame_with_consumer_capabilities(
11278        corr: u64,
11279        module_id: &str,
11280        _project_root: ScratchDir,
11281        consumer_capabilities: Option<Vec<String>>,
11282    ) -> Frame {
11283        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11284            busy_refusals: None,
11285            target: RouteTarget::ToolProvider {
11286                module_id: module_id.to_string(),
11287            },
11288            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11289            consumer_identity: None,
11290            consumer_capabilities,
11291            role_versions: None,
11292            admission_facts: None,
11293            scope: None,
11294        })
11295        .unwrap();
11296        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11297    }
11298
11299    fn route_open_frame_with_role_versions(
11300        corr: u64,
11301        module_id: &str,
11302        _project_root: ScratchDir,
11303        role_versions: Option<BTreeMap<String, String>>,
11304    ) -> Frame {
11305        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11306            busy_refusals: None,
11307            target: RouteTarget::ToolProvider {
11308                module_id: module_id.to_string(),
11309            },
11310            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11311            consumer_identity: None,
11312            consumer_capabilities: None,
11313            role_versions,
11314            admission_facts: None,
11315            scope: None,
11316        })
11317        .unwrap();
11318        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11319    }
11320
11321    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11322        entries
11323            .iter()
11324            .map(|(role, version)| (role.to_string(), version.to_string()))
11325            .collect()
11326    }
11327
11328    fn route_open_frame_with_admission_facts(
11329        corr: u64,
11330        module_id: &str,
11331        _project_root: ScratchDir,
11332        consumer_identity: Option<subc_control::ConsumerIdentity>,
11333        facts: Option<Value>,
11334    ) -> Frame {
11335        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11336            busy_refusals: None,
11337            target: RouteTarget::ToolProvider {
11338                module_id: module_id.to_string(),
11339            },
11340            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11341            consumer_identity,
11342            consumer_capabilities: None,
11343            role_versions: None,
11344            admission_facts: facts,
11345            scope: None,
11346        })
11347        .unwrap();
11348        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11349    }
11350
11351    #[derive(Clone, Default)]
11352    struct EventCapture {
11353        events: Arc<Mutex<Vec<CapturedEvent>>>,
11354    }
11355
11356    #[derive(Clone, Debug)]
11357    struct CapturedEvent {
11358        target: String,
11359        level: tracing::Level,
11360        fields: BTreeMap<String, String>,
11361    }
11362
11363    impl EventCapture {
11364        fn events(&self) -> Vec<CapturedEvent> {
11365            self.events.lock().unwrap().clone()
11366        }
11367    }
11368
11369    impl<S> Layer<S> for EventCapture
11370    where
11371        S: Subscriber,
11372    {
11373        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11374            let mut visitor = EventFieldVisitor::default();
11375            event.record(&mut visitor);
11376            self.events.lock().unwrap().push(CapturedEvent {
11377                target: event.metadata().target().to_string(),
11378                level: *event.metadata().level(),
11379                fields: visitor.fields,
11380            });
11381        }
11382    }
11383
11384    #[derive(Default)]
11385    struct EventFieldVisitor {
11386        fields: BTreeMap<String, String>,
11387    }
11388
11389    impl Visit for EventFieldVisitor {
11390        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11391            self.fields
11392                .insert(field.name().to_string(), format!("{value:?}"));
11393        }
11394    }
11395
11396    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11397        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11398            status,
11399            detail: Some("warming".to_string()),
11400            metrics: Some(json!({"queue_depth": 3})),
11401        })
11402        .unwrap();
11403        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11404    }
11405
11406    fn route_bind_ack(corr: u64) -> Frame {
11407        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11408        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11409    }
11410
11411    fn unique_project_root(label: &str) -> ScratchDir {
11412        ScratchDir::new(label)
11413    }
11414
11415    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11416        match parse_route_poll(frame) {
11417            ClientControlResponse::RoutePoll {
11418                status: None,
11419                live: Some(live),
11420                ..
11421            } => assert_eq!(live, expected_live),
11422            other => panic!("unexpected route.poll response: {other:?}"),
11423        }
11424    }
11425
11426    fn bind_liveness_route(
11427        registry: &Registry,
11428        forwarding: &ForwardingTable,
11429        module_id: &str,
11430    ) -> (RouteCtx, u16, u32) {
11431        let module_connection = ConnectionId::new(101);
11432        let client_connection = ConnectionId::new(202);
11433        let registration = registry
11434            .register_with_control_ops(
11435                manifest(module_id, PROTOCOL_VERSION),
11436                PROTOCOL_VERSION,
11437                module_connection,
11438                module_baseline_control_ops(),
11439            )
11440            .unwrap();
11441        let (module_tx, _module_rx) = mpsc::channel(8);
11442        let endpoint = forwarding
11443            .register_module_connection(
11444                module_connection,
11445                module_id.to_string(),
11446                PROTOCOL_VERSION,
11447                manifest_concurrency(&registration.manifest),
11448                FrameSink::new(module_tx),
11449            )
11450            .unwrap();
11451        let (client_ctx, _client_rx) = route_ctx(client_connection);
11452        let pending = forwarding
11453            .begin_route_bind_relay_for_test(
11454                client_connection,
11455                client_ctx.egress.clone(),
11456                1,
11457                module_id,
11458            )
11459            .unwrap();
11460        assert_eq!(pending.endpoint, endpoint);
11461        let route_channel = pending.client_channel;
11462        let route_epoch = pending.client_epoch;
11463        forwarding
11464            .complete_pending_relay(
11465                module_connection,
11466                pending.corr,
11467                RouteBindRelayOutcome::Accepted,
11468            )
11469            .unwrap();
11470        (client_ctx, route_channel, route_epoch)
11471    }
11472
11473    struct FakeProcessLiveness {
11474        live: Option<bool>,
11475    }
11476
11477    impl ModuleProcessLiveness for FakeProcessLiveness {
11478        fn process_live(&self, _module_id: &str) -> Option<bool> {
11479            self.live
11480        }
11481    }
11482
11483    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11484    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11485    {
11486        let registry = Arc::new(Registry::default());
11487        let supervisor_handle = SupervisorHandle::new();
11488        let supervisor = Supervisor::new_for_test(
11489            Arc::clone(&registry),
11490            RestartPolicy::new(1, Duration::from_millis(10)),
11491        )
11492        .with_handle(supervisor_handle.clone());
11493        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11494        let module = supervisor
11495            .spawn(ModuleSpec {
11496                script: None,
11497                carry_containment: false,
11498                module_id: "stderr-tail-wire".to_string(),
11499                program: fake_aft_stub_path(),
11500                args: Vec::new(),
11501                env: vec![
11502                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11503                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11504                ],
11505                reserved: false,
11506                reserved_prefixes: Vec::new(),
11507                protocol: ModuleProtocol::Subc,
11508                overlap: Default::default(),
11509            })
11510            .unwrap();
11511
11512        let deadline = Instant::now() + Duration::from_secs(5);
11513        loop {
11514            let tail = module.stderr_tail(None, None);
11515            if tail
11516                .entries
11517                .iter()
11518                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11519                && tail.entries.iter().any(|entry| {
11520                    matches!(
11521                        entry,
11522                        TailEntry::Line {
11523                            truncated: true,
11524                            ..
11525                        }
11526                    )
11527                })
11528            {
11529                break;
11530            }
11531            assert!(
11532                Instant::now() < deadline,
11533                "module did not produce a truncated line and restart boundary: {tail:?}"
11534            );
11535            sleep(Duration::from_millis(10)).await;
11536        }
11537
11538        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11539        let request = ClientControlRequest::SupervisorStderrTail {
11540            module_id: "stderr-tail-wire".to_string(),
11541            max_lines: None,
11542            max_bytes: None,
11543        };
11544        let frame = Frame::build(
11545            FrameType::Request,
11546            control_flags(),
11547            0,
11548            0,
11549            1,
11550            serde_json::to_vec(&request).unwrap(),
11551        )
11552        .unwrap();
11553        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11554        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11555        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11556            serde_json::from_slice(&responses[0].body).unwrap()
11557        else {
11558            panic!("expected supervisor.stderr_tail response");
11559        };
11560
11561        assert!(
11562            tail.entries
11563                .iter()
11564                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11565            "the control response lost the restart boundary"
11566        );
11567        let Some(StderrTailEntry::Line {
11568            text,
11569            truncated,
11570            at_ms,
11571        }) = tail.entries.iter().find(|entry| {
11572            matches!(
11573                entry,
11574                StderrTailEntry::Line {
11575                    truncated: true,
11576                    ..
11577                }
11578            )
11579        })
11580        else {
11581            panic!("the control response lost the truncated line");
11582        };
11583        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11584        assert!(*truncated);
11585        assert!(
11586            at_ms.is_some(),
11587            "the control response lost the line's capture time"
11588        );
11589    }
11590
11591    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11592    /// read done on the worker thread would stall every other task until it
11593    /// finished; the read must run off the worker so this test's own task keeps
11594    /// running while the read is paused.
11595    #[tokio::test(flavor = "current_thread")]
11596    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11597        let dir = ScratchDir::new("terminals-off-worker");
11598        let journal_path = dir.join("terminals.jsonl");
11599        let registry = Arc::new(Registry::default());
11600        let supervisor_handle = SupervisorHandle::new();
11601        let supervisor =
11602            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11603                .with_handle(supervisor_handle.clone())
11604                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11605        let module = supervisor
11606            .spawn(ModuleSpec {
11607                script: None,
11608                carry_containment: false,
11609                module_id: "terminal-off-worker".to_string(),
11610                program: fake_aft_stub_path(),
11611                args: Vec::new(),
11612                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11613                reserved: false,
11614                reserved_prefixes: Vec::new(),
11615                protocol: ModuleProtocol::Subc,
11616                overlap: Default::default(),
11617            })
11618            .unwrap();
11619        let deadline = Instant::now() + Duration::from_secs(5);
11620        while module.terminal_history().entries.len() != 2 {
11621            assert!(Instant::now() < deadline, "module did not record two exits");
11622            sleep(Duration::from_millis(10)).await;
11623        }
11624
11625        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11626        let handler =
11627            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11628        let frame = Frame::build(
11629            FrameType::Request,
11630            control_flags(),
11631            0,
11632            0,
11633            1,
11634            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11635                module_id: "terminal-off-worker".to_string(),
11636            })
11637            .unwrap(),
11638        )
11639        .unwrap();
11640        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11641        let spawned_at = std::time::Instant::now();
11642        let read = tokio::spawn({
11643            let handler = Arc::clone(&handler);
11644            async move { handler.handle_control_frame(&ctx, frame).await }
11645        });
11646        // Waiting for the pause from a blocking thread keeps this task pending,
11647        // so the runtime's single worker is free to run the read task.
11648        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11649            .await
11650            .unwrap()
11651            .expect("the history read reached its pause");
11652        let elapsed = spawned_at.elapsed();
11653        assert!(
11654            elapsed < Duration::from_secs(2) && !read.is_finished(),
11655            "this task could not run while the history read was paused \
11656             (resumed after {elapsed:?}, read finished: {})",
11657            read.is_finished()
11658        );
11659
11660        drop(release);
11661        let responses = read.await.unwrap().unwrap();
11662        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11663        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11664            panic!("expected supervisor.terminals response");
11665        };
11666        assert_eq!(terminals.entries.len(), 2);
11667        assert_eq!(terminals.journal_skipped_lines, 0);
11668        assert_eq!(terminals.journal_read_errors, 0);
11669    }
11670
11671    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11672    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11673        let registry = Arc::new(Registry::default());
11674        let supervisor_handle = SupervisorHandle::new();
11675        let supervisor =
11676            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11677                .with_handle(supervisor_handle.clone());
11678        let module = supervisor
11679            .spawn(ModuleSpec {
11680                script: None,
11681                carry_containment: false,
11682                module_id: "terminal-golden".to_string(),
11683                program: fake_aft_stub_path(),
11684                args: Vec::new(),
11685                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11686                reserved: false,
11687                reserved_prefixes: Vec::new(),
11688                protocol: ModuleProtocol::Subc,
11689                overlap: Default::default(),
11690            })
11691            .unwrap();
11692
11693        let deadline = Instant::now() + Duration::from_secs(5);
11694        while module.terminal_history().entries.len() != 2 {
11695            assert!(
11696                Instant::now() < deadline,
11697                "module did not retain two terminal exits: {:?}",
11698                module.terminal_history()
11699            );
11700            sleep(Duration::from_millis(10)).await;
11701        }
11702
11703        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11704        let request = ClientControlRequest::SupervisorTerminals {
11705            module_id: "terminal-golden".to_string(),
11706        };
11707        let frame = Frame::build(
11708            FrameType::Request,
11709            control_flags(),
11710            0,
11711            0,
11712            1,
11713            serde_json::to_vec(&request).unwrap(),
11714        )
11715        .unwrap();
11716        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11717        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11718        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11719        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11720            panic!("expected supervisor.terminals response");
11721        };
11722        assert_eq!(terminals.entries.len(), 2);
11723        assert_eq!(terminals.dropped, 0);
11724
11725        let mut rendered = serde_json::to_value(response).unwrap();
11726        // Wall-clock fields are the observation contract, but not stable fixture
11727        // bytes; normalize only them after the real handler has shaped the response.
11728        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11729        for (index, entry) in rendered["entries"]
11730            .as_array_mut()
11731            .expect("terminal response entries array")
11732            .iter_mut()
11733            .enumerate()
11734        {
11735            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11736        }
11737
11738        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11739            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11740        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11741        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11742            std::fs::write(&golden_path, &serialized).unwrap();
11743        }
11744        let expected: Value =
11745            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11746        assert_eq!(rendered, expected);
11747    }
11748
11749    #[test]
11750    fn hello_registers_manifest_and_returns_ack() {
11751        let registry = Arc::new(Registry::default());
11752        let handler = ControlHandler::new(Arc::clone(&registry));
11753        let conn = ConnectionId::new(1);
11754
11755        let responses = handler
11756            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11757            .unwrap();
11758
11759        assert_eq!(responses.len(), 1);
11760        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11761        assert_eq!(responses[0].header.channel, 0);
11762        assert_eq!(responses[0].header.corr, 7);
11763        let ack = parse_ack(&responses[0]);
11764        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11765        assert!(ack
11766            .subc_capabilities
11767            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11768        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11769        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11770        assert!(ack
11771            .subc_ops
11772            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11773        assert!(ack
11774            .subc_ops
11775            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11776        assert!(ack
11777            .subc_ops
11778            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11779
11780        let registration = registry.get_module("aft").unwrap().unwrap();
11781        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11782        assert_eq!(registration.state, ChannelState::Active);
11783        assert_eq!(registration.connection_id, conn);
11784        assert_eq!(registration.control_ops, module_baseline_control_ops());
11785        assert!(registration.manifest.display_name.is_none());
11786    }
11787
11788    #[test]
11789    fn hello_display_name_refuses_invalid_manifest_by_field() {
11790        let registry = Arc::new(Registry::default());
11791        let handler = ControlHandler::new(Arc::clone(&registry));
11792        for (index, invalid) in [
11793            json!(""),
11794            json!("a".repeat(41)),
11795            json!(" Routing"),
11796            json!("a\nb"),
11797            json!("a\u{202e}b"),
11798            json!(7),
11799        ]
11800        .into_iter()
11801        .enumerate()
11802        {
11803            let module_id = format!("bad-display-name-{index}");
11804            let mut body = serde_json::to_value(ModuleHelloBody {
11805                manifest: manifest(&module_id, PROTOCOL_VERSION),
11806                protocol_ver: PROTOCOL_VERSION,
11807                control_ops: None,
11808                launch_nonce: None,
11809            })
11810            .unwrap();
11811            body["manifest"]["display_name"] = invalid;
11812            let hello = Frame::build(
11813                FrameType::Hello,
11814                control_flags(),
11815                0,
11816                0,
11817                7,
11818                serde_json::to_vec(&body).unwrap(),
11819            )
11820            .unwrap();
11821            let response = handler
11822                .handle_control(ConnectionId::new(100 + index as u64), hello)
11823                .unwrap();
11824            assert_eq!(response[0].header.ty, FrameType::Error);
11825            let error = parse_error(&response[0]);
11826            assert_eq!(error["code"], "invalid_manifest");
11827            assert!(error["message"].as_str().unwrap().contains("display_name"));
11828            assert!(registry.get_module(&module_id).unwrap().is_none());
11829        }
11830    }
11831
11832    #[test]
11833    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11834        let invalid_identifiers = [
11835            ("case_change", "credentials-Provider/v1"),
11836            ("leading_zero", "credentials-provider/v01"),
11837            ("trailing_hyphen", "credentials-provider-/v1"),
11838            ("consecutive_hyphens", "credentials--provider/v1"),
11839            ("uppercase", "Credentials-provider/v1"),
11840            ("missing_v", "credentials-provider/1"),
11841            ("whitespace", "credentials provider/v1"),
11842            ("zero_version", "credentials-provider/v0"),
11843            ("out_of_range_version", "credentials-provider/v4294967296"),
11844            (
11845                "overlength_name",
11846                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11847            ),
11848        ];
11849        let mut cases = invalid_identifiers
11850            .into_iter()
11851            .map(|(name, identifier)| {
11852                (
11853                    format!("identifier_{name}"),
11854                    "capabilities.provides[0]".to_string(),
11855                    identifier.to_string(),
11856                    json!({ "provides": [identifier] }),
11857                    None,
11858                )
11859            })
11860            .collect::<Vec<_>>();
11861        cases.extend([
11862            (
11863                "unknown_need".to_string(),
11864                "capabilities.requires[0].need".to_string(),
11865                "deferred".to_string(),
11866                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11867                None,
11868            ),
11869            (
11870                "duplicate_provides".to_string(),
11871                "capabilities.provides[1]".to_string(),
11872                "credentials-provider/v1".to_string(),
11873                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11874                None,
11875            ),
11876            (
11877                "duplicate_must_never_reach".to_string(),
11878                "capabilities.must_never_reach[1]".to_string(),
11879                "credentials-provider/v1".to_string(),
11880                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11881                None,
11882            ),
11883            (
11884                "duplicate_requires_same_need".to_string(),
11885                "capabilities.requires[1]".to_string(),
11886                "credentials-provider/v1".to_string(),
11887                json!({ "requires": [
11888                    { "capability": "credentials-provider/v1", "need": "required" },
11889                    { "capability": "credentials-provider/v1", "need": "required" }
11890                ] }),
11891                None,
11892            ),
11893            (
11894                "duplicate_requires_conflicting_need".to_string(),
11895                "capabilities.requires[1]".to_string(),
11896                "credentials-provider/v1".to_string(),
11897                json!({ "requires": [
11898                    { "capability": "credentials-provider/v1", "need": "required" },
11899                    { "capability": "credentials-provider/v1", "need": "optional" }
11900                ] }),
11901                None,
11902            ),
11903            (
11904                "capabilities_root_pointer".to_string(),
11905                "runtime_computed[0]".to_string(),
11906                "/capabilities".to_string(),
11907                json!({}),
11908                Some(json!(["/capabilities"])),
11909            ),
11910            (
11911                "capabilities_descendant_pointer".to_string(),
11912                "runtime_computed[0]".to_string(),
11913                "/capabilities/provides".to_string(),
11914                json!({}),
11915                Some(json!(["/capabilities/provides"])),
11916            ),
11917            (
11918                "malformed_pointer_without_leading_slash".to_string(),
11919                "runtime_computed[0]".to_string(),
11920                "capabilities".to_string(),
11921                json!({}),
11922                Some(json!(["capabilities"])),
11923            ),
11924            (
11925                "malformed_pointer_escape".to_string(),
11926                "runtime_computed[0]".to_string(),
11927                "/roles/~2/tools".to_string(),
11928                json!({}),
11929                Some(json!(["/roles/~2/tools"])),
11930            ),
11931            (
11932                "unknown_capabilities_field".to_string(),
11933                "capabilities.future".to_string(),
11934                "<array>".to_string(),
11935                json!({ "future": [] }),
11936                None,
11937            ),
11938        ]);
11939
11940        for (index, (name, field, value, capabilities, runtime_computed)) in
11941            cases.into_iter().enumerate()
11942        {
11943            let registry = Arc::new(Registry::default());
11944            let handler = ControlHandler::new(Arc::clone(&registry));
11945            let response = handler
11946                .handle_control(
11947                    ConnectionId::new((index + 1) as u64),
11948                    capability_grammar_hello_frame(
11949                        capabilities,
11950                        runtime_computed,
11951                        index as u64 + 1,
11952                    ),
11953                )
11954                .expect("invalid HELLO returns a refusal");
11955
11956            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11957            let error = parse_error(&response[0]);
11958            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11959            let message = error["message"]
11960                .as_str()
11961                .expect("error message is a string");
11962            assert!(
11963                message.contains(&field),
11964                "{name}: field missing from {message}"
11965            );
11966            assert!(
11967                message.contains(&value),
11968                "{name}: value missing from {message}"
11969            );
11970            assert_eq!(
11971                registry
11972                    .active_registration_count()
11973                    .expect("registry reads"),
11974                0,
11975                "{name}: refused HELLO must not create a catalog entry"
11976            );
11977        }
11978    }
11979
11980    #[test]
11981    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
11982        let registry = Arc::new(Registry::default());
11983        let handler = ControlHandler::new(Arc::clone(&registry));
11984        let capabilities = json!({
11985            "provides": ["credentials-provider/v1"],
11986            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
11987            "must_never_reach": ["federation-transport/v1"]
11988        });
11989        let response = handler
11990            .handle_control(
11991                ConnectionId::new(99),
11992                capability_grammar_hello_frame(
11993                    capabilities.clone(),
11994                    Some(json!(["/roles/0/tools"])),
11995                    99,
11996                ),
11997            )
11998            .expect("valid HELLO registers");
11999        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12000
12001        let request = Frame::build(
12002            FrameType::Request,
12003            control_flags(),
12004            0,
12005            0,
12006            100,
12007            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12008                .expect("catalog request serializes"),
12009        )
12010        .expect("catalog request frame builds");
12011        let response = handler
12012            .handle_catalog_list(request, None)
12013            .expect("catalog list succeeds");
12014        let ClientControlResponse::CatalogList { modules, .. } =
12015            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
12016        else {
12017            panic!("catalog request must return catalog.list");
12018        };
12019        assert_eq!(modules.len(), 1);
12020        assert_eq!(
12021            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
12022            capabilities
12023        );
12024    }
12025
12026    #[test]
12027    fn catalog_list_mirrors_management_operation_description() {
12028        let registry = Arc::new(Registry::default());
12029        let handler = ControlHandler::new(Arc::clone(&registry));
12030        let description = "List managed records and return their identifiers and metadata.";
12031        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
12032        manifest.provides = vec![ProviderRole::ManagementSurface {
12033            operations: vec![ManagementOperation {
12034                name: "records.list".to_string(),
12035                kind: ManagementOperationKind::Query,
12036                description: Some(description.to_string()),
12037            }],
12038            config_schema: json!({"type": "object"}),
12039            observability: vec![ObservabilitySurface {
12040                name: "records.stats".to_string(),
12041                kind: ObservabilityKind::Snapshot,
12042            }],
12043            identity_scope: vec![IdentityScope::Project],
12044            concurrency: Concurrency::ModuleManaged,
12045        }];
12046        registry
12047            .register_with_control_ops(
12048                manifest,
12049                PROTOCOL_VERSION,
12050                ConnectionId::new(99),
12051                Vec::new(),
12052            )
12053            .expect("described management manifest registers");
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 })
12062                .expect("catalog request serializes"),
12063        )
12064        .expect("catalog request frame builds");
12065        let response = handler
12066            .handle_catalog_list(request, None)
12067            .expect("catalog list succeeds");
12068        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12069        assert_eq!(
12070            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12071            "catalog.list must preserve the declared operation description verbatim"
12072        );
12073    }
12074
12075    #[test]
12076    fn catalog_list_mirrors_registered_operation_delivery() {
12077        let registry = Arc::new(Registry::default());
12078        let handler = ControlHandler::new(Arc::clone(&registry));
12079        let delivery =
12080            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12081        let mut body = serde_json::to_value(ModuleHelloBody {
12082            manifest: manifest("watch-management", PROTOCOL_VERSION),
12083            protocol_ver: PROTOCOL_VERSION,
12084            control_ops: None,
12085            launch_nonce: None,
12086        })
12087        .unwrap();
12088        body["manifest"]["provides"] = json!([{
12089            "role": "management_surface",
12090            "operations": [
12091                {"name": "status", "kind": "query"},
12092                {"name": "future", "kind": "query"},
12093                {"name": "reset", "kind": "mutate"}
12094            ],
12095            "config_schema": {}, "observability": [], "identity_scope": []
12096        }]);
12097        body["manifest"]["operation_delivery"] = delivery.clone();
12098        let hello = Frame::build(
12099            FrameType::Hello,
12100            control_flags(),
12101            0,
12102            0,
12103            99,
12104            serde_json::to_vec(&body).unwrap(),
12105        )
12106        .unwrap();
12107        let response = handler
12108            .handle_control(ConnectionId::new(99), hello)
12109            .unwrap();
12110        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12111
12112        let (_, registrations) = registry.list_modules().unwrap();
12113        let registered = &registrations[0].manifest;
12114        assert!(registered.is_watch_operation("status"));
12115        assert!(!registered.is_watch_operation("future"));
12116        assert!(!registered.is_watch_operation("reset"));
12117        assert!(!registered.is_watch_operation("missing"));
12118
12119        let request = Frame::build(
12120            FrameType::Request,
12121            control_flags(),
12122            0,
12123            0,
12124            100,
12125            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12126        )
12127        .unwrap();
12128        let response = handler.handle_catalog_list(request, None).unwrap();
12129        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12130        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12131        let ClientControlResponse::CatalogList { modules, .. } =
12132            serde_json::from_slice(&response[0].body).unwrap()
12133        else {
12134            panic!("expected catalog.list");
12135        };
12136        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12137    }
12138
12139    #[test]
12140    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12141        let registry = Arc::new(Registry::default());
12142        let supervisor = SupervisorHandle::new();
12143        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12144        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12145        let descriptor = json!({
12146            "schema": "ckios.richui.manifest/1",
12147            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12148            "bytes": 4096,
12149            "chunks": 4
12150        });
12151        let connection = ConnectionId::new(201);
12152        let hello = handler
12153            .handle_control(
12154                connection,
12155                hello_frame_with_rich_ui(
12156                    "vault",
12157                    PROTOCOL_VERSION,
12158                    201,
12159                    Some("the-real-nonce"),
12160                    descriptor.clone(),
12161                ),
12162            )
12163            .unwrap();
12164        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12165
12166        let request =
12167            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12168        let provides = registry
12169            .get_module_by_connection(connection)
12170            .unwrap()
12171            .unwrap()
12172            .manifest
12173            .provides;
12174        handler
12175            .handle_catalog_update(connection, request, provides, None, Some(false))
12176            .unwrap();
12177
12178        let request = Frame::build(
12179            FrameType::Request,
12180            control_flags(),
12181            0,
12182            0,
12183            203,
12184            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12185        )
12186        .unwrap();
12187        let response = handler.handle_catalog_list(request, None).unwrap();
12188        let ClientControlResponse::CatalogList { modules, .. } =
12189            serde_json::from_slice(&response[0].body).unwrap()
12190        else {
12191            panic!("expected catalog.list");
12192        };
12193        assert_eq!(
12194            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12195            descriptor
12196        );
12197        assert!(modules[0].nonce_verified);
12198    }
12199
12200    fn hello_with_role_declarations(declarations: Value) -> Frame {
12201        let mut body = serde_json::to_value(ModuleHelloBody {
12202            manifest: manifest("role-test", PROTOCOL_VERSION),
12203            protocol_ver: PROTOCOL_VERSION,
12204            control_ops: None,
12205            launch_nonce: None,
12206        })
12207        .unwrap();
12208        body["manifest"]["role_declarations"] = declarations;
12209        Frame::build(
12210            FrameType::Hello,
12211            control_flags(),
12212            0,
12213            0,
12214            301,
12215            serde_json::to_vec(&body).unwrap(),
12216        )
12217        .unwrap()
12218    }
12219
12220    fn update_role_declarations_frame(declarations: Value) -> Frame {
12221        Frame::build(
12222            FrameType::Request,
12223            control_flags(),
12224            0,
12225            0,
12226            303,
12227            serde_json::to_vec(&json!({
12228                "op": "catalog.update_role_declarations",
12229                "role_declarations": declarations,
12230            }))
12231            .unwrap(),
12232        )
12233        .unwrap()
12234    }
12235
12236    #[tokio::test]
12237    async fn role_declarations_update_replaces_then_clears_catalog() {
12238        let registry = Arc::new(Registry::default());
12239        let handler = ControlHandler::new(Arc::clone(&registry));
12240        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12241        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12242        hello_via_sink(
12243            &handler,
12244            &ctx,
12245            &mut rx,
12246            hello_with_role_declarations(initial.clone()),
12247        )
12248        .await;
12249        assert_eq!(
12250            role_declarations_catalog(&handler).0["role_declarations"],
12251            initial
12252        );
12253        let before = registry.get_module("role-test").unwrap().unwrap();
12254        for declarations in [
12255            json!({"media-provider/v1": {"engines": ["new"]}}),
12256            json!({}),
12257        ] {
12258            let response = handler
12259                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12260                .await
12261                .unwrap();
12262            assert_eq!(response[0].header.ty, FrameType::Response);
12263            assert_eq!(
12264                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12265                json!({"op": "catalog.update_role_declarations"})
12266            );
12267            let (raw, entry) = role_declarations_catalog(&handler);
12268            assert_eq!(
12269                serde_json::to_value(entry.role_declarations).unwrap(),
12270                declarations
12271            );
12272            if declarations.as_object().unwrap().is_empty() {
12273                assert!(raw.get("role_declarations").is_none());
12274            } else {
12275                assert_eq!(raw["role_declarations"], declarations);
12276            }
12277            let after = registry.get_module("role-test").unwrap().unwrap();
12278            let mut expected = before.manifest.clone();
12279            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12280            assert_eq!(after.manifest, expected);
12281            assert_eq!(after.ready, before.ready);
12282        }
12283    }
12284
12285    #[tokio::test]
12286    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12287        let registry = Arc::new(Registry::default());
12288        let handler = ControlHandler::new(registry);
12289        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12290        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12291        hello_via_sink(
12292            &handler,
12293            &ctx,
12294            &mut rx,
12295            hello_with_role_declarations(initial.clone()),
12296        )
12297        .await;
12298        for (invalid, reason) in [
12299            (json!(null), "role_declarations must be an object"),
12300            (json!([]), "role_declarations must be an object"),
12301            (
12302                json!({"bad key": {}}),
12303                "role_declarations key must use capability-name grammar",
12304            ),
12305            (
12306                json!({"media-provider/v1": []}),
12307                "role_declarations values must be objects",
12308            ),
12309            (
12310                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12311                "role_declarations exceeds 16384 compact JSON bytes",
12312            ),
12313        ] {
12314            let response = handler
12315                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12316                .await
12317                .unwrap();
12318            let error = parse_error(&response[0]);
12319            assert_eq!(error["code"], "invalid_role_declarations");
12320            assert_eq!(error["message"], reason);
12321            assert_eq!(
12322                role_declarations_catalog(&handler).0["role_declarations"],
12323                initial
12324            );
12325        }
12326    }
12327
12328    #[tokio::test]
12329    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12330        let registry = Arc::new(Registry::default());
12331        let handler = ControlHandler::new(Arc::clone(&registry));
12332        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12333        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12334        hello_via_sink(
12335            &handler,
12336            &owner,
12337            &mut owner_rx,
12338            hello_with_role_declarations(initial.clone()),
12339        )
12340        .await;
12341        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12342        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12343        let response = handler
12344            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12345            .await
12346            .unwrap();
12347        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12348        hello_via_sink(
12349            &handler,
12350            &other,
12351            &mut other_rx,
12352            hello_frame("other", PROTOCOL_VERSION, 304),
12353        )
12354        .await;
12355        let response = handler
12356            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12357            .await
12358            .unwrap();
12359        assert_eq!(response[0].header.ty, FrameType::Response);
12360        assert_eq!(
12361            serde_json::to_value(
12362                registry
12363                    .get_module("role-test")
12364                    .unwrap()
12365                    .unwrap()
12366                    .manifest
12367                    .role_declarations
12368            )
12369            .unwrap(),
12370            initial
12371        );
12372        assert_eq!(
12373            serde_json::to_value(
12374                registry
12375                    .get_module("other")
12376                    .unwrap()
12377                    .unwrap()
12378                    .manifest
12379                    .role_declarations
12380            )
12381            .unwrap(),
12382            replacement
12383        );
12384    }
12385
12386    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12387        let request = Frame::build(
12388            FrameType::Request,
12389            control_flags(),
12390            0,
12391            0,
12392            302,
12393            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12394        )
12395        .unwrap();
12396        let response = handler.handle_catalog_list(request, None).unwrap();
12397        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12398        let ClientControlResponse::CatalogList { mut modules, .. } =
12399            serde_json::from_slice(&response[0].body).unwrap()
12400        else {
12401            panic!("expected catalog.list");
12402        };
12403        (raw["modules"][0].clone(), modules.remove(0))
12404    }
12405
12406    #[test]
12407    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12408        let registry = Arc::new(Registry::default());
12409        let handler = ControlHandler::new(Arc::clone(&registry));
12410        let declarations = json!({
12411            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12412            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12413        });
12414        let connection = ConnectionId::new(301);
12415        let response = handler
12416            .handle_control(
12417                connection,
12418                hello_with_role_declarations(declarations.clone()),
12419            )
12420            .unwrap();
12421        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12422        let registered = registry
12423            .get_module_by_connection(connection)
12424            .unwrap()
12425            .unwrap()
12426            .manifest;
12427        // Compared as JSON values, not bytes: object key order is not part of
12428        // the relay's promise, and workspace builds unify serde_json's
12429        // preserve_order feature, which changes the order a literal keeps.
12430        assert_eq!(
12431            serde_json::to_value(&registered.role_declarations).unwrap(),
12432            declarations
12433        );
12434        let (raw, entry) = role_declarations_catalog(&handler);
12435        assert_eq!(raw["role_declarations"], declarations);
12436        assert_eq!(entry.role_declarations, registered.role_declarations);
12437
12438        let request =
12439            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12440        handler
12441            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12442            .unwrap();
12443        let (raw, entry) = role_declarations_catalog(&handler);
12444        assert_eq!(raw["role_declarations"], declarations);
12445        assert_eq!(entry.role_declarations, registered.role_declarations);
12446    }
12447
12448    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12449        let registry = Arc::new(Registry::default());
12450        let handler = ControlHandler::new(Arc::clone(&registry));
12451        let capture = EventCapture::default();
12452        let _subscriber =
12453            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12454        let response = handler
12455            .handle_control(
12456                ConnectionId::new(301),
12457                hello_with_role_declarations(declarations),
12458            )
12459            .unwrap();
12460        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12461        assert!(registry
12462            .get_module_by_connection(ConnectionId::new(301))
12463            .unwrap()
12464            .unwrap()
12465            .manifest
12466            .role_declarations
12467            .is_empty());
12468        let (raw, entry) = role_declarations_catalog(&handler);
12469        assert!(raw.get("role_declarations").is_none());
12470        assert!(entry.role_declarations.is_empty());
12471        let warnings: Vec<_> = capture
12472            .events()
12473            .into_iter()
12474            .filter(|event| {
12475                event.fields.get("message").map(String::as_str)
12476                    == Some("dropping whole role_declarations map from HELLO")
12477            })
12478            .collect();
12479        assert_eq!(warnings.len(), 1);
12480        assert_eq!(warnings[0].level, tracing::Level::WARN);
12481        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12482        assert_eq!(warnings[0].fields["reason"], reason);
12483    }
12484
12485    #[test]
12486    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12487        for value in [
12488            json!(null),
12489            json!(false),
12490            json!(0),
12491            json!("opaque"),
12492            json!([]),
12493        ] {
12494            assert_hello_drops_role_declarations_with_warning(
12495                json!({"routing/v1": {}, "broken/v1": value}),
12496                "role_declarations values must be objects",
12497            );
12498        }
12499        assert_hello_drops_role_declarations_with_warning(
12500            json!([]),
12501            "role_declarations must be an object",
12502        );
12503    }
12504
12505    #[test]
12506    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12507        assert_hello_drops_role_declarations_with_warning(
12508            json!({"routing/v1": {}, "bad key": {}}),
12509            "role_declarations key must use capability-name grammar",
12510        );
12511    }
12512
12513    #[test]
12514    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12515        assert_hello_drops_role_declarations_with_warning(
12516            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12517            "role_declarations exceeds 16384 compact JSON bytes",
12518        );
12519    }
12520
12521    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12522        let mut body = serde_json::to_value(ModuleHelloBody {
12523            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12524            protocol_ver: PROTOCOL_VERSION,
12525            control_ops: None,
12526            launch_nonce: None,
12527        })
12528        .unwrap();
12529        body["manifest"]["provides"] = json!([{
12530            "role": "management_surface",
12531            "operations": [
12532                {"name": "diagnostics.findings", "kind": "query"},
12533                {"name": "reset", "kind": "mutate"}
12534            ],
12535            "config_schema": {}, "observability": [], "identity_scope": []
12536        }]);
12537        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12538        if let Some(flow_operations) = flow_operations {
12539            body["manifest"]["flow_operations"] = flow_operations;
12540        }
12541        Frame::build(
12542            FrameType::Hello,
12543            control_flags(),
12544            0,
12545            0,
12546            401,
12547            serde_json::to_vec(&body).unwrap(),
12548        )
12549        .unwrap()
12550    }
12551
12552    #[test]
12553    fn catalog_list_mirrors_flow_operations_unchanged() {
12554        // Order is kept as declared (not sorted) and an empty list stays an
12555        // affirmative "none", distinct from an absent declaration.
12556        for (capability, flow_operations) in [
12557            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12558            ("call-modes/v1", json!(["diagnostics.findings"])),
12559            ("flow-scopes/v1", json!([])),
12560        ] {
12561            let registry = Arc::new(Registry::default());
12562            let handler = ControlHandler::new(Arc::clone(&registry));
12563            let connection = ConnectionId::new(401);
12564            let response = handler
12565                .handle_control(
12566                    connection,
12567                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12568                )
12569                .unwrap();
12570            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12571            let registered = registry
12572                .get_module_by_connection(connection)
12573                .unwrap()
12574                .unwrap()
12575                .manifest;
12576            assert_eq!(
12577                serde_json::to_value(&registered.flow_operations).unwrap(),
12578                flow_operations
12579            );
12580            let (raw, entry) = role_declarations_catalog(&handler);
12581            assert_eq!(raw["flow_operations"], flow_operations);
12582            assert_eq!(entry.flow_operations, registered.flow_operations);
12583        }
12584
12585        let registry = Arc::new(Registry::default());
12586        let handler = ControlHandler::new(Arc::clone(&registry));
12587        let response = handler
12588            .handle_control(
12589                ConnectionId::new(401),
12590                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12591            )
12592            .unwrap();
12593        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12594        let (raw, entry) = role_declarations_catalog(&handler);
12595        assert!(raw.get("flow_operations").is_none());
12596        assert_eq!(entry.flow_operations, None);
12597    }
12598
12599    #[test]
12600    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12601        let oversized: serde_json::Map<String, Value> = (0..257)
12602            .map(|n| (format!("tool:t{n}"), json!(true)))
12603            .collect();
12604        for (capabilities, map, valid) in [
12605            (
12606                json!(["scope-federated/v1"]),
12607                json!({"tool:read":true,"management:reset":true}),
12608                true,
12609            ),
12610            (json!(["scope-federated/v1"]), json!({}), true),
12611            (json!([]), json!({"tool:read":true}), false),
12612            (
12613                json!(["scope-federated/v1"]),
12614                json!({"tool:valid":true,"tool:bad":false}),
12615                false,
12616            ),
12617            (
12618                json!(["scope-federated/v1"]),
12619                json!({"tool:valid":true,"management:missing":true}),
12620                false,
12621            ),
12622            (
12623                json!(["scope-federated/v1"]),
12624                Value::Object(oversized),
12625                false,
12626            ),
12627        ] {
12628            let capture = EventCapture::default();
12629            let _subscriber = tracing::subscriber::set_default(
12630                tracing_subscriber::registry().with(capture.clone()),
12631            );
12632            let registry = Arc::new(Registry::default());
12633            let handler = ControlHandler::new(Arc::clone(&registry));
12634            let hello = hello_with_flow_operations(capabilities, None);
12635            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12636            body["manifest"]["operation_deferral"] = map.clone();
12637            let hello = Frame::build(
12638                FrameType::Hello,
12639                control_flags(),
12640                0,
12641                0,
12642                401,
12643                serde_json::to_vec(&body).unwrap(),
12644            )
12645            .unwrap();
12646            let response = handler
12647                .handle_control(ConnectionId::new(401), hello)
12648                .unwrap();
12649            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12650            let (raw, entry) = role_declarations_catalog(&handler);
12651            if valid {
12652                assert_eq!(raw["operation_deferral"], map);
12653                assert_eq!(
12654                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12655                    map
12656                );
12657            } else {
12658                assert!(entry.operation_deferral.is_none());
12659                assert!(raw.get("operation_deferral").is_none());
12660                assert_eq!(
12661                    capture
12662                        .events()
12663                        .iter()
12664                        .filter(|event| event.fields.get("message").map(String::as_str)
12665                            == Some("dropping operation_deferral from HELLO"))
12666                        .count(),
12667                    1
12668                );
12669            }
12670        }
12671    }
12672
12673    fn assert_hello_drops_flow_operations_with_warning(
12674        capabilities: Value,
12675        flow_operations: Value,
12676        reason: &str,
12677    ) {
12678        let registry = Arc::new(Registry::default());
12679        let handler = ControlHandler::new(Arc::clone(&registry));
12680        let capture = EventCapture::default();
12681        let _subscriber =
12682            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12683        let response = handler
12684            .handle_control(
12685                ConnectionId::new(401),
12686                hello_with_flow_operations(capabilities, Some(flow_operations)),
12687            )
12688            .unwrap();
12689        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12690        let registered = registry
12691            .get_module_by_connection(ConnectionId::new(401))
12692            .unwrap()
12693            .expect("the module still registers")
12694            .manifest;
12695        assert_eq!(registered.module_id, "flow-ops");
12696        assert_eq!(registered.flow_operations, None);
12697        let (raw, entry) = role_declarations_catalog(&handler);
12698        assert_eq!(raw["module_id"], "flow-ops");
12699        assert!(raw.get("flow_operations").is_none());
12700        assert_eq!(entry.flow_operations, None);
12701        let warnings: Vec<_> = capture
12702            .events()
12703            .into_iter()
12704            .filter(|event| {
12705                event.fields.get("message").map(String::as_str)
12706                    == Some("dropping flow_operations from HELLO")
12707            })
12708            .collect();
12709        assert_eq!(warnings.len(), 1);
12710        assert_eq!(warnings[0].level, tracing::Level::WARN);
12711        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12712        assert_eq!(warnings[0].fields["reason"], reason);
12713    }
12714
12715    #[test]
12716    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12717        assert_hello_drops_flow_operations_with_warning(
12718            json!(["flow-scopes/v1"]),
12719            json!(["diagnostics.findings", "missing"]),
12720            "flow_operations names 'missing', which is not a declared management operation",
12721        );
12722    }
12723
12724    #[test]
12725    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12726        assert_hello_drops_flow_operations_with_warning(
12727            json!([]),
12728            json!(["diagnostics.findings"]),
12729            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12730        );
12731        // A run-only capability does not admit flows either.
12732        assert_hello_drops_flow_operations_with_warning(
12733            json!(["agent-run-scopes/v1"]),
12734            json!([]),
12735            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12736        );
12737    }
12738
12739    #[test]
12740    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12741        assert_hello_drops_flow_operations_with_warning(
12742            json!(["flow-scopes/v1"]),
12743            json!(["reset", "reset"]),
12744            "flow_operations names 'reset' more than once",
12745        );
12746        assert_hello_drops_flow_operations_with_warning(
12747            json!(["flow-scopes/v1"]),
12748            json!(vec!["reset"; 257]),
12749            "flow_operations lists 257 names, more than 256",
12750        );
12751        assert_hello_drops_flow_operations_with_warning(
12752            json!(["flow-scopes/v1"]),
12753            json!("reset"),
12754            "flow_operations must be an array of operation names",
12755        );
12756    }
12757
12758    #[test]
12759    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12760        let registry = Arc::new(Registry::default());
12761        let handler = ControlHandler::new(registry.clone());
12762        let descriptor = json!({
12763            "schema": "ckios.richui.manifest/1",
12764            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12765            "bytes": 128,
12766            "chunks": 2
12767        });
12768        let malformed = [
12769            ("schema", json!("")),
12770            ("schema", json!("a".repeat(65))),
12771            ("schema", json!("Bad schema")),
12772            (
12773                "manifest_digest",
12774                json!(format!("sha256:{}", "A".repeat(64))),
12775            ),
12776            ("manifest_digest", json!("sha256:abc")),
12777            ("bytes", json!(0)),
12778            ("bytes", json!(16_777_217)),
12779            ("bytes", json!("128")),
12780            ("chunks", json!(0)),
12781            ("chunks", json!(1025)),
12782            ("chunks", json!("2")),
12783        ];
12784        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12785            let mut invalid = descriptor.clone();
12786            invalid[field] = invalid_value;
12787            let response = handler
12788                .handle_control(
12789                    ConnectionId::new(210 + index as u64),
12790                    hello_frame_with_rich_ui(
12791                        &format!("bad-rich-ui-{index}"),
12792                        PROTOCOL_VERSION,
12793                        210 + index as u64,
12794                        None,
12795                        invalid,
12796                    ),
12797                )
12798                .unwrap();
12799            assert_eq!(response[0].header.ty, FrameType::Error);
12800            let error = parse_error(&response[0]);
12801            assert_eq!(error["code"], "invalid_manifest");
12802            assert!(error["message"]
12803                .as_str()
12804                .unwrap()
12805                .contains(&format!("rich_ui.{field}")));
12806            assert!(registry
12807                .get_module(&format!("bad-rich-ui-{index}"))
12808                .unwrap()
12809                .is_none());
12810        }
12811    }
12812
12813    #[test]
12814    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12815        let registry = Arc::new(Registry::default());
12816        let handler = ControlHandler::new(Arc::clone(&registry));
12817        let connection = ConnectionId::new(219);
12818        registry
12819            .register_with_control_ops(
12820                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12821                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12822                        "bad schema",
12823                        format!("sha256:{}", "a".repeat(64)),
12824                        128,
12825                        2,
12826                    )))
12827                    .build(),
12828                PROTOCOL_VERSION,
12829                connection,
12830                Vec::new(),
12831            )
12832            .unwrap();
12833        let request =
12834            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12835        let response = handler
12836            .handle_catalog_update(connection, request, Vec::new(), None, None)
12837            .unwrap();
12838        assert_eq!(response[0].header.ty, FrameType::Error);
12839        let error = parse_error(&response[0]);
12840        assert_eq!(error["code"], "invalid_manifest");
12841        assert!(error["message"]
12842            .as_str()
12843            .unwrap()
12844            .contains("rich_ui.schema"));
12845    }
12846
12847    #[test]
12848    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12849        let registry = Arc::new(Registry::default());
12850        let supervisor = SupervisorHandle::new();
12851        supervisor.open_swap("provider", "candidate-nonce".to_string());
12852        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12853        let connection = ConnectionId::new(218);
12854        let hello = handler
12855            .handle_control(
12856                connection,
12857                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12858            )
12859            .unwrap();
12860        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12861        assert!(registry.list_modules().unwrap().1.is_empty());
12862
12863        registry.promote_candidate("provider").unwrap().unwrap();
12864        let request = Frame::build(
12865            FrameType::Request,
12866            control_flags(),
12867            0,
12868            0,
12869            219,
12870            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12871        )
12872        .unwrap();
12873        let response = handler.handle_catalog_list(request, None).unwrap();
12874        let ClientControlResponse::CatalogList { modules, .. } =
12875            serde_json::from_slice(&response[0].body).unwrap()
12876        else {
12877            panic!("expected catalog.list");
12878        };
12879        assert_eq!(modules.len(), 1);
12880        assert!(modules[0].nonce_verified);
12881    }
12882
12883    #[test]
12884    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12885        for provenance_json in [
12886            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12887            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12888        ] {
12889            let registry = Arc::new(Registry::default());
12890            let handler = ControlHandler::new(registry);
12891            let hello = Frame::build(
12892                FrameType::Hello,
12893                control_flags(),
12894                0,
12895                0,
12896                220,
12897                serde_json::to_vec(&ModuleHelloBody {
12898                    manifest: ModuleManifest::builder("built", "0.1.0")
12899                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12900                        .build(),
12901                    protocol_ver: PROTOCOL_VERSION,
12902                    control_ops: None,
12903                    launch_nonce: None,
12904                })
12905                .unwrap(),
12906            )
12907            .unwrap();
12908            assert_eq!(
12909                handler
12910                    .handle_control(ConnectionId::new(220), hello)
12911                    .unwrap()[0]
12912                    .header
12913                    .ty,
12914                FrameType::HelloAck
12915            );
12916            let request = Frame::build(
12917                FrameType::Request,
12918                control_flags(),
12919                0,
12920                0,
12921                221,
12922                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12923            )
12924            .unwrap();
12925            let response = handler.handle_catalog_list(request, None).unwrap();
12926            let ClientControlResponse::CatalogList { modules, .. } =
12927                serde_json::from_slice(&response[0].body).unwrap()
12928            else {
12929                panic!("expected catalog.list");
12930            };
12931            assert_eq!(modules.len(), 1);
12932            assert_eq!(
12933                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12934                format!(
12935                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12936                )
12937                .as_bytes()
12938            );
12939        }
12940    }
12941
12942    #[test]
12943    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12944        let registry = Arc::new(Registry::default());
12945        let handler = ControlHandler::new(Arc::clone(&registry));
12946        let hello = Frame::build(
12947            FrameType::Hello,
12948            control_flags(),
12949            0,
12950            0,
12951            220,
12952            serde_json::to_vec(&ModuleHelloBody {
12953                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12954                protocol_ver: PROTOCOL_VERSION,
12955                control_ops: None,
12956                launch_nonce: Some("unverified".to_string()),
12957            })
12958            .unwrap(),
12959        )
12960        .unwrap();
12961        assert_eq!(
12962            handler
12963                .handle_control(ConnectionId::new(220), hello)
12964                .unwrap()[0]
12965                .header
12966                .ty,
12967            FrameType::HelloAck
12968        );
12969        let request = Frame::build(
12970            FrameType::Request,
12971            control_flags(),
12972            0,
12973            0,
12974            221,
12975            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12976        )
12977        .unwrap();
12978        let response = handler.handle_catalog_list(request, None).unwrap();
12979        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
12980        assert!(wire["modules"][0].get("provenance").is_none());
12981        let ClientControlResponse::CatalogList { modules, .. } =
12982            serde_json::from_slice(&response[0].body).unwrap()
12983        else {
12984            panic!("expected catalog.list");
12985        };
12986        assert_eq!(
12987            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12988            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
12989        );
12990        assert!(!modules[0].nonce_verified);
12991        assert!(modules[0].provenance.is_none());
12992    }
12993
12994    // Preserve the legacy-field byte pins while discovery adds optional facts.
12995    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
12996        assert_eq!(entry.first_party, Some(false));
12997        entry.incarnation = None;
12998        entry.spawn = None;
12999        entry.first_party = None;
13000        entry.origin = None;
13001        entry.requested_declarations_digest = None;
13002        entry.approved_declarations_digest = None;
13003        entry
13004    }
13005
13006    #[test]
13007    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
13008        let registry = Arc::new(Registry::default());
13009        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13010            [("vault".to_string(), true), ("squatter".to_string(), true)],
13011            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13012        );
13013        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
13014        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13015            provides: vec!["credentials-provider/v1".to_string()],
13016            requires: Vec::new(),
13017            must_never_reach: Vec::new(),
13018        });
13019        let frame = Frame::build(
13020            FrameType::Hello,
13021            control_flags(),
13022            0,
13023            0,
13024            77,
13025            serde_json::to_vec(&ModuleHelloBody {
13026                manifest: squatter,
13027                protocol_ver: PROTOCOL_VERSION,
13028                control_ops: None,
13029                launch_nonce: None,
13030            })
13031            .expect("HELLO serializes"),
13032        )
13033        .expect("HELLO frame builds");
13034        let response = handler
13035            .handle_control(ConnectionId::new(77), frame)
13036            .expect("reserved claim receives a typed refusal");
13037        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13038        assert_eq!(
13039            registry
13040                .active_registration_count()
13041                .expect("registry reads"),
13042            0,
13043            "a reserved capability refusal must not leave a catalog entry"
13044        );
13045    }
13046
13047    #[test]
13048    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
13049        for settlement in ["timeout", "inconclusive", "drop"] {
13050            let breakers = RouteBindBreakers::default();
13051            let RouteBindAdmission::Admitted {
13052                guard: mut old,
13053                probe: false,
13054            } = breakers.admit("prov")
13055            else {
13056                panic!("ordinary relay admitted")
13057            };
13058            let RouteBindAdmission::Admitted {
13059                guard: mut opener, ..
13060            } = breakers.admit("prov")
13061            else {
13062                panic!("second relay admitted")
13063            };
13064            assert!(
13065                !opener
13066                    .record_timeout(1, Duration::ZERO)
13067                    .unwrap()
13068                    .reopened_after_probe
13069            );
13070            let RouteBindAdmission::Admitted {
13071                guard: mut probe,
13072                probe: true,
13073            } = breakers.admit("prov")
13074            else {
13075                panic!("one cooldown probe admitted")
13076            };
13077            match settlement {
13078                "timeout" => assert!(
13079                    !old.record_timeout(1, Duration::ZERO)
13080                        .unwrap()
13081                        .reopened_after_probe
13082                ),
13083                "inconclusive" => old.record_inconclusive(),
13084                "drop" => drop(old),
13085                _ => unreachable!(),
13086            }
13087            assert!(
13088                matches!(
13089                    breakers.admit("prov"),
13090                    RouteBindAdmission::Refused {
13091                        probe_in_flight: true,
13092                        ..
13093                    }
13094                ),
13095                "{settlement} of a pre-open relay cannot release the real probe"
13096            );
13097            assert!(
13098                probe
13099                    .record_timeout(1, Duration::ZERO)
13100                    .unwrap()
13101                    .reopened_after_probe
13102            );
13103            assert!(matches!(
13104                breakers.admit("prov"),
13105                RouteBindAdmission::Admitted { probe: true, .. }
13106            ));
13107        }
13108        let breakers = RouteBindBreakers::default();
13109        let admit = || match breakers.admit("prov") {
13110            RouteBindAdmission::Admitted { guard, .. } => guard,
13111            _ => panic!("relay admitted"),
13112        };
13113        admit().record_timeout(1, Duration::ZERO);
13114        let mut old_probe = admit();
13115        breakers.reset_for_new_module_connection("prov");
13116        admit().record_timeout(1, Duration::ZERO);
13117        let _new_probe = admit();
13118        old_probe.record_inconclusive();
13119        assert!(matches!(
13120            breakers.admit("prov"),
13121            RouteBindAdmission::Refused {
13122                probe_in_flight: true,
13123                ..
13124            }
13125        ));
13126    }
13127
13128    #[tokio::test]
13129    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13130        for candidate in [false, true] {
13131            let registry = Arc::new(Registry::default());
13132            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13133                [("vault".to_string(), true), ("squatter".to_string(), true)],
13134                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13135            );
13136            let conn = ConnectionId::new(77);
13137            let (ctx, mut rx) = route_ctx(conn);
13138            let initial = capability_manifest("squatter", &[], &[]);
13139            if candidate {
13140                registry
13141                    .register_candidate_with_control_ops(
13142                        initial.clone(),
13143                        PROTOCOL_VERSION,
13144                        conn,
13145                        module_baseline_control_ops(),
13146                    )
13147                    .unwrap();
13148                handler
13149                    .forwarding
13150                    .register_candidate_module_connection(
13151                        conn,
13152                        "squatter".to_string(),
13153                        PROTOCOL_VERSION,
13154                        manifest_concurrency(&initial),
13155                        ctx.egress.clone(),
13156                    )
13157                    .unwrap();
13158            } else {
13159                hello_via_sink(
13160                    &handler,
13161                    &ctx,
13162                    &mut rx,
13163                    hello_frame_with_manifest(initial.clone(), 1),
13164                )
13165                .await;
13166            }
13167            let response = handler
13168                .handle_control_frame(
13169                    &ctx,
13170                    catalog_update_with_capabilities_frame(
13171                        2,
13172                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13173                            .capabilities
13174                            .unwrap(),
13175                    ),
13176                )
13177                .await
13178                .unwrap();
13179            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13180            assert_eq!(
13181                registry
13182                    .get_module_by_connection(conn)
13183                    .unwrap()
13184                    .unwrap()
13185                    .manifest,
13186                initial
13187            );
13188        }
13189    }
13190
13191    #[test]
13192    #[cfg(not(feature = "dev-desktop-approval"))]
13193    fn server_describe_default_build_advertises_no_config_capability() {
13194        let assert_default = |handler: &ControlHandler| {
13195            let request = Frame::build(
13196                FrameType::Request,
13197                control_flags(),
13198                0,
13199                0,
13200                79,
13201                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13202            )
13203            .unwrap();
13204            let responses = handler.handle_server_describe(request).unwrap();
13205            assert_eq!(responses.len(), 1);
13206            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13207            assert_eq!(response["op"], "server.describe");
13208            let capabilities = response["capabilities"]
13209                .as_array()
13210                .expect("capability array");
13211            assert!(
13212                !capabilities.is_empty(),
13213                "exercise an actual describe response, not an empty fixture"
13214            );
13215            assert!(
13216                capabilities
13217                    .iter()
13218                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13219                "a default build must not announce configuration authority: {capabilities:?}"
13220            );
13221        };
13222        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13223        #[cfg(unix)]
13224        {
13225            // A local store does not prove that project-membership validation,
13226            // active-scope usage tracking and approved-program launch selection
13227            // are connected. Defaults must not advertise that authority.
13228            let (_rig, _owner, _supervisor, handler, _spec) =
13229                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13230                );
13231            assert_default(&handler);
13232        }
13233    }
13234
13235    #[test]
13236    fn server_describe_surfaces_required_capability_verdict_fields() {
13237        let registry = Arc::new(Registry::default());
13238        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13239            [
13240                ("consumer".to_string(), true),
13241                ("provider".to_string(), false),
13242            ],
13243            BTreeMap::new(),
13244        );
13245        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13246        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13247            provides: Vec::new(),
13248            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13249                capability: "credentials-provider/v1".to_string(),
13250                need: subc_protocol::manifest::CapabilityNeed::Required,
13251            }],
13252            must_never_reach: Vec::new(),
13253        });
13254        let hello = Frame::build(
13255            FrameType::Hello,
13256            control_flags(),
13257            0,
13258            0,
13259            78,
13260            serde_json::to_vec(&ModuleHelloBody {
13261                manifest: consumer,
13262                protocol_ver: PROTOCOL_VERSION,
13263                control_ops: None,
13264                launch_nonce: None,
13265            })
13266            .expect("HELLO serializes"),
13267        )
13268        .expect("HELLO frame builds");
13269        handler
13270            .handle_control(ConnectionId::new(78), hello)
13271            .expect("consumer registers");
13272        let describe = Frame::build(
13273            FrameType::Request,
13274            control_flags(),
13275            0,
13276            0,
13277            79,
13278            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13279                .expect("request serializes"),
13280        )
13281        .expect("describe frame builds");
13282        let response = handler
13283            .handle_server_describe(describe)
13284            .expect("server.describe succeeds");
13285        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13286        let requirement = &rendered["capability_requirements"][0];
13287        assert_eq!(requirement["consumer"], "consumer");
13288        assert_eq!(requirement["verdict"], "never_provided");
13289        assert_eq!(requirement["episode_seq"], 1);
13290        assert_eq!(requirement["config_satisfiable"], false);
13291        assert_eq!(requirement["runtime_available"], false);
13292        assert!(requirement["detail"]
13293            .as_str()
13294            .expect("detail string")
13295            .contains("credentials-provider/v1"));
13296    }
13297
13298    /// Register a consumer that requires `project-identity/v1` and the provider
13299    /// of it, optionally mark daemon shutdown as begun, then deregister the
13300    /// provider as its connection closes. Returns the `capability.requirement`
13301    /// events that deregistration logged and the verdict the evaluator then
13302    /// holds for the requirement (the one `route.open` refusals read).
13303    fn deregister_required_provider(
13304        daemon_shutdown_begun: bool,
13305    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13306        const CAPABILITY: &str = "project-identity/v1";
13307        let registry = Arc::new(Registry::default());
13308        let daemon_shutdown = DaemonShutdownFlag::default();
13309        let handler = ControlHandler::new(Arc::clone(&registry))
13310            .with_capability_config(
13311                [
13312                    ("consumer".to_string(), true),
13313                    ("provider".to_string(), true),
13314                ],
13315                BTreeMap::new(),
13316            )
13317            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13318        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13319        consumer.capabilities = Some(CapabilityDeclarations {
13320            provides: Vec::new(),
13321            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13322                capability: CAPABILITY.to_string(),
13323                need: subc_protocol::manifest::CapabilityNeed::Required,
13324            }],
13325            must_never_reach: Vec::new(),
13326        });
13327        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13328        let provider_conn = ConnectionId::new(182);
13329        for (conn, manifest, corr) in [
13330            (ConnectionId::new(181), consumer, 181),
13331            (provider_conn, provider, 182),
13332        ] {
13333            let hello = handler
13334                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13335                .expect("module registers");
13336            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13337        }
13338        assert_eq!(
13339            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13340            Some(CapabilityVerdict::Provided),
13341            "the registered provider must satisfy the requirement first"
13342        );
13343        if daemon_shutdown_begun {
13344            daemon_shutdown.set_for_test();
13345        }
13346
13347        let capture = EventCapture::default();
13348        let _subscriber =
13349            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13350        handler
13351            .cleanup_connection(provider_conn)
13352            .expect("provider deregisters");
13353        let events = capture
13354            .events()
13355            .into_iter()
13356            .filter(|event| {
13357                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13358            })
13359            .collect();
13360        (
13361            events,
13362            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13363        )
13364    }
13365
13366    #[test]
13367    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13368        let (events, verdict) = deregister_required_provider(true);
13369        assert_eq!(
13370            verdict,
13371            Some(CapabilityVerdict::NeverProvided),
13372            "shutdown must not change the verdict route.open refusals read"
13373        );
13374        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13375        let event = &events[0];
13376        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13377        assert_eq!(
13378            event.fields.get("cause").map(String::as_str),
13379            Some("\"daemon_shutdown\""),
13380            "{event:?}"
13381        );
13382        assert_eq!(
13383            event.fields.get("verdict").map(String::as_str),
13384            Some("\"never_provided\""),
13385            "{event:?}"
13386        );
13387    }
13388
13389    #[test]
13390    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13391        let (events, verdict) = deregister_required_provider(false);
13392        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13393        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13394        let event = &events[0];
13395        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13396        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13397        assert_eq!(
13398            event.fields.get("verdict").map(String::as_str),
13399            Some("\"never_provided\""),
13400            "{event:?}"
13401        );
13402    }
13403
13404    #[test]
13405    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13406        let registry = Arc::new(Registry::default());
13407        let handler = ControlHandler::new(Arc::clone(&registry));
13408        let hello = handler
13409            .handle_control(
13410                ConnectionId::new(101),
13411                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13412            )
13413            .expect("legacy HELLO registers");
13414        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13415
13416        let request = Frame::build(
13417            FrameType::Request,
13418            control_flags(),
13419            0,
13420            0,
13421            102,
13422            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13423                .expect("catalog request serializes"),
13424        )
13425        .expect("catalog request frame builds");
13426        let response = handler
13427            .handle_catalog_list(request, None)
13428            .expect("catalog list succeeds");
13429        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13430        assert!(
13431            body["modules"][0].get("capabilities").is_none(),
13432            "legacy manifest must retain an absent capabilities field on catalog.list"
13433        );
13434    }
13435
13436    #[test]
13437    fn hello_ack_omits_storage_when_no_storage_config() {
13438        let registry = Arc::new(Registry::default());
13439        let handler = ControlHandler::new(Arc::clone(&registry));
13440        let responses = handler
13441            .handle_control(
13442                ConnectionId::new(1),
13443                hello_frame("aft", PROTOCOL_VERSION, 7),
13444            )
13445            .unwrap();
13446        let ack = parse_ack(&responses[0]);
13447        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13448        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13449    }
13450
13451    #[tokio::test]
13452    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13453        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13454        let registry = Arc::new(Registry::default());
13455        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13456        let responses = handler
13457            .handle_control(
13458                ConnectionId::new(1),
13459                hello_frame("aft", PROTOCOL_VERSION, 7),
13460            )
13461            .unwrap();
13462        let ack = parse_ack(&responses[0]);
13463        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13464
13465        let described = handler
13466            .handle_control_frame(
13467                &route_ctx(ConnectionId::new(2)).0,
13468                Frame::build(
13469                    FrameType::Request,
13470                    control_flags(),
13471                    0,
13472                    0,
13473                    9,
13474                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13475                )
13476                .unwrap(),
13477            )
13478            .await
13479            .unwrap();
13480        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13481            serde_json::from_slice(&described[0].body).unwrap()
13482        else {
13483            panic!("server.describe answered with another shape");
13484        };
13485        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13486    }
13487
13488    #[test]
13489    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13490        // With a central sqlite storage policy, each registering module gets its
13491        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13492        let registry = Arc::new(Registry::default());
13493        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13494            crate::daemon_config::StorageConfig::Sqlite {
13495                data_home: std::path::PathBuf::from("/data"),
13496            },
13497        ));
13498
13499        let responses = handler
13500            .handle_control(
13501                ConnectionId::new(1),
13502                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13503            )
13504            .unwrap();
13505        let ack = parse_ack(&responses[0]);
13506        assert_eq!(
13507            ack.storage,
13508            Some(serde_json::json!({
13509                "module_id": "alfonso-routing",
13510                "storage_namespace": "default",
13511                "isolation": { "kind": "module" },
13512                "backend": {
13513                    "backend": "sqlite",
13514                    "path": "/data/cortexkit/alfonso-routing/store.db"
13515                }
13516            })),
13517            "the delivered descriptor is the module's own sqlite store path"
13518        );
13519    }
13520
13521    #[test]
13522    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13523        let registry = Arc::new(Registry::default());
13524        let handler = ControlHandler::new(Arc::clone(&registry));
13525        let conn = ConnectionId::new(1);
13526        let responses = handler
13527            .handle_control(
13528                conn,
13529                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13530            )
13531            .unwrap();
13532        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13533        let registration = registry.get_module("aft").unwrap().unwrap();
13534        assert_eq!(registration.control_ops, module_baseline_control_ops());
13535
13536        let frame =
13537            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13538        assert!(handler
13539            .guard_module_control_op(&frame, "aft", "route.bind")
13540            .unwrap()
13541            .is_none());
13542        let error = handler
13543            .guard_module_control_op(&frame, "aft", "test.synthetic")
13544            .unwrap()
13545            .expect("synthetic ungranted op should be rejected");
13546        assert_eq!(error.header.ty, FrameType::Error);
13547        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13548    }
13549
13550    #[test]
13551    fn hello_control_ops_some_adds_optional_grants() {
13552        let registry = Arc::new(Registry::default());
13553        let handler = ControlHandler::new(Arc::clone(&registry));
13554        handler
13555            .handle_control(
13556                ConnectionId::new(1),
13557                hello_frame_with_control_ops(
13558                    "aft",
13559                    PROTOCOL_VERSION,
13560                    7,
13561                    Some(vec![
13562                        "future.synthetic".to_string(),
13563                        "route.bind".to_string(),
13564                    ]),
13565                ),
13566            )
13567            .unwrap();
13568        let registration = registry.get_module("aft").unwrap().unwrap();
13569        assert_eq!(
13570            registration.control_ops,
13571            vec![
13572                "route.bind".to_string(),
13573                "route.status".to_string(),
13574                "future.synthetic".to_string(),
13575            ]
13576        );
13577        let frame =
13578            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13579        assert!(handler
13580            .guard_module_control_op(&frame, "aft", "future.synthetic")
13581            .unwrap()
13582            .is_none());
13583    }
13584
13585    #[tokio::test]
13586    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13587        let registry = Arc::new(Registry::default());
13588        let forwarding = Arc::new(ForwardingTable::default());
13589        let handler =
13590            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13591        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13592        hello_via_sink(
13593            &handler,
13594            &module_ctx,
13595            &mut module_rx,
13596            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13597        )
13598        .await;
13599
13600        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13601        let responses = handler
13602            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13603            .await
13604            .unwrap();
13605        assert_eq!(responses.len(), 1);
13606        assert_eq!(responses[0].header.ty, FrameType::Error);
13607        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13608        assert!(module_rx.try_recv().is_err());
13609    }
13610
13611    #[tokio::test]
13612    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13613        let registry = Arc::new(Registry::default());
13614        let forwarding = Arc::new(ForwardingTable::default());
13615        let handler =
13616            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13617        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13618        hello_via_sink(
13619            &handler,
13620            &module_ctx,
13621            &mut module_rx,
13622            hello_frame_with_control_ops(
13623                "aft",
13624                PROTOCOL_VERSION,
13625                7,
13626                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13627            ),
13628        )
13629        .await;
13630
13631        let project_root = unique_project_root("demux");
13632        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13633        let route_handler = handler.clone();
13634        let route_task = tokio::spawn(async move {
13635            route_handler
13636                .handle_control_frame(
13637                    &route_client_ctx,
13638                    route_open_frame(100, "aft", project_root),
13639                )
13640                .await
13641                .unwrap()
13642        });
13643        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13644            .await
13645            .unwrap()
13646            .unwrap();
13647        assert!(matches!(
13648            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13649            ModuleControlRequest::RouteBind { .. }
13650        ));
13651
13652        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13653        let health_handler = handler.clone();
13654        let health_task = tokio::spawn(async move {
13655            health_handler
13656                .handle_control_frame(
13657                    &health_client_ctx,
13658                    supervisor_health_probe_frame(101, "aft"),
13659                )
13660                .await
13661                .unwrap()
13662        });
13663        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13664            .await
13665            .unwrap()
13666            .unwrap();
13667        assert_eq!(
13668            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13669            ModuleControlRequest::HealthCheck {}
13670        );
13671
13672        handler
13673            .handle_control_frame(
13674                &module_ctx,
13675                health_response(health_frame.header.corr, HealthStatus::Degraded),
13676            )
13677            .await
13678            .unwrap();
13679        let health_response = health_task.await.unwrap();
13680        assert_eq!(health_response.len(), 1);
13681        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13682            ClientControlResponse::SupervisorHealthProbe {
13683                module_id,
13684                status,
13685                detail,
13686                metrics,
13687            } => {
13688                assert_eq!(module_id, "aft");
13689                assert_eq!(status, HealthStatus::Degraded);
13690                assert_eq!(detail.as_deref(), Some("warming"));
13691                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13692            }
13693            other => panic!("unexpected health response: {other:?}"),
13694        }
13695
13696        handler
13697            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13698            .await
13699            .unwrap();
13700        let route_response = route_task.await.unwrap();
13701        assert!(route_response.is_empty());
13702        let published = route_client_rx.recv().await.unwrap();
13703        assert!(matches!(
13704            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13705            ClientControlResponse::RouteOpen { .. }
13706        ));
13707    }
13708
13709    /// Start one `route.open` on `client_connection` and return its still-running
13710    /// handler task together with the `route.bind` the module received for it.
13711    /// The handler blocks until the module answers, so it has to run as a task
13712    /// while the test drives the module side.
13713    async fn relay_route_open(
13714        handler: &ControlHandler,
13715        client_connection: ConnectionId,
13716        client_egress: &FrameSink,
13717        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13718        corr: u64,
13719        module_id: &str,
13720        project_root_label: &str,
13721    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13722        let ctx = RouteCtx {
13723            connection_id: client_connection,
13724            egress: client_egress.clone(),
13725        };
13726        let handler = handler.clone();
13727        let project_root = unique_project_root(project_root_label);
13728        let module_id = module_id.to_string();
13729        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13730        let task = tokio::spawn(async move {
13731            let _guard = tracing::dispatcher::set_default(&dispatch);
13732            handler
13733                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13734                .await
13735                .unwrap()
13736        });
13737        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13738            .await
13739            .expect("module receives the relayed route.bind")
13740            .expect("module egress is open");
13741        (task, bind.frame)
13742    }
13743
13744    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13745        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13746            ModuleControlRequest::RouteBind {
13747                route_channel,
13748                epoch,
13749                ..
13750            } => (route_channel, epoch),
13751            other => panic!("expected a route.bind request, got {other:?}"),
13752        }
13753    }
13754
13755    fn published_route(frame: &Frame) -> (u16, u32) {
13756        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13757            ClientControlResponse::RouteOpen {
13758                route_channel,
13759                route_epoch,
13760                ..
13761            } => (route_channel, route_epoch),
13762            other => panic!("expected a route.open response, got {other:?}"),
13763        }
13764    }
13765
13766    /// Reproduction of a production outage. A client had `route.open`s in
13767    /// flight to a module and was already marked closing -- its egress had refused a
13768    /// module frame, so the daemon asked its connection to end -- while its sink
13769    /// was still open. When the module acked those binds, the daemon refused to
13770    /// commit a route for a closing client, and that refusal was returned from
13771    /// the MODULE connection's frame handler, where a router error that has no
13772    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13773    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13774    /// its tools for hours -- one client's teardown took down a connection
13775    /// carrying ~170 other routes.
13776    ///
13777    /// The window is opened here by calling the production path that opens it
13778    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13779    /// state that matters is "in `closing_connections`, sink still open, relay
13780    /// still pending", and it lasts only from the close request until the
13781    /// connection loop reacts to it; a socket-level test can flood a client into
13782    /// that escalation but cannot pin the module's ack inside the window. Closing
13783    /// the socket instead takes the other path entirely -- connection teardown
13784    /// removes the pending relay under the same lock, so the ack finds nothing.
13785    #[tokio::test]
13786    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13787        let registry = Arc::new(Registry::default());
13788        let forwarding = Arc::new(ForwardingTable::default());
13789        let handler =
13790            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13791
13792        let module_connection = ConnectionId::new(30);
13793        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13794        hello_via_sink(
13795            &handler,
13796            &module_ctx,
13797            &mut module_rx,
13798            hello_frame("aft", PROTOCOL_VERSION, 7),
13799        )
13800        .await;
13801
13802        let dying_client = ConnectionId::new(31);
13803        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13804
13805        // A published route on the dying client. The escalation below only marks
13806        // a connection closing for a route it has already published.
13807        let (first_task, first_bind) = relay_route_open(
13808            &handler,
13809            dying_client,
13810            &dying_ctx.egress,
13811            &mut module_rx,
13812            100,
13813            "aft",
13814            "closing-first",
13815        )
13816        .await;
13817        handler
13818            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13819            .await
13820            .unwrap();
13821        assert!(first_task.await.unwrap().is_empty());
13822        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13823
13824        // A second route.open from the same client, relayed and awaiting its ack.
13825        let (second_task, second_bind) = relay_route_open(
13826            &handler,
13827            dying_client,
13828            &dying_ctx.egress,
13829            &mut module_rx,
13830            101,
13831            "aft",
13832            "closing-second",
13833        )
13834        .await;
13835        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13836
13837        // The window: the client is closing, its sink is still open, and its
13838        // second bind is still pending.
13839        assert!(forwarding
13840            .escalate_client_delivery_failure(
13841                dying_client,
13842                first_channel,
13843                first_epoch,
13844                CloseReason::new(
13845                    "module_to_client_delivery_failed",
13846                    "client egress refused a module frame",
13847                ),
13848                crate::forwarding::UndeliveredFrame {
13849                    module_id: None,
13850                    sink: &dying_ctx.egress,
13851                },
13852            )
13853            .unwrap());
13854        assert!(!dying_ctx.egress.is_closed());
13855
13856        // The frame that used to end the module connection.
13857        let ack = handler
13858            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13859            .await;
13860        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13861        if module_loop_error.is_some() {
13862            // What the server's connection loop does with a router error that has
13863            // no ERROR-frame translation: end the connection, which releases the
13864            // module's registration and every route on it.
13865            handler.cleanup_connection(module_connection).unwrap();
13866        }
13867        // Read the module's next frame before opening the co-tenant's route, so
13868        // the GOODBYE assertion below is about THIS ack and not about later
13869        // traffic. `None` means the module was told nothing.
13870        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13871            .await
13872            .ok()
13873            .flatten();
13874
13875        // 1. The module connection is still registered.
13876        assert!(
13877            registry
13878                .get_module_by_connection(module_connection)
13879                .unwrap()
13880                .is_some(),
13881            "one client's closing connection ended the shared module connection: \
13882             {module_loop_error:?}"
13883        );
13884        // ...and still serving: another client can open and use a route on it.
13885        let cotenant = ConnectionId::new(32);
13886        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13887        let (cotenant_task, cotenant_bind) = relay_route_open(
13888            &handler,
13889            cotenant,
13890            &cotenant_ctx.egress,
13891            &mut module_rx,
13892            102,
13893            "aft",
13894            "closing-cotenant",
13895        )
13896        .await;
13897        handler
13898            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13899            .await
13900            .unwrap();
13901        assert!(cotenant_task.await.unwrap().is_empty());
13902        let (cotenant_channel, cotenant_epoch) =
13903            published_route(&cotenant_rx.recv().await.unwrap());
13904        assert!(matches!(
13905            forwarding
13906                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13907                .unwrap(),
13908            DataRoute::Client(DataRouteState::Bound(_))
13909        ));
13910
13911        // 2. The module was told to drop the binding it created for the route
13912        //    that will never be published.
13913        let goodbye = post_ack_module_frame
13914            .expect("module receives a GOODBYE for the abandoned route channel");
13915        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13916        assert_eq!(goodbye.header.channel, abandoned_channel);
13917        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13918
13919        // 3. The dying client received nothing: no route was ever published to
13920        //    it. Its route.open is answered as unavailable, which the connection
13921        //    loop would write to a socket that is already going away.
13922        assert!(dying_rx.try_recv().is_err());
13923        let second_response = second_task.await.unwrap();
13924        assert_eq!(second_response.len(), 1);
13925        assert_eq!(
13926            parse_error(&second_response[0])["code"],
13927            "target_unavailable"
13928        );
13929    }
13930
13931    /// One `catalog.list` as a client sees it: the generation and the listed
13932    /// module ids with their readiness.
13933    async fn catalog_snapshot(
13934        handler: &ControlHandler,
13935        client_ctx: &RouteCtx,
13936        corr: u64,
13937    ) -> (u64, Vec<(String, bool)>) {
13938        let body =
13939            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13940        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13941        let reply = handler
13942            .handle_control_frame(client_ctx, request)
13943            .await
13944            .unwrap()
13945            .pop()
13946            .unwrap();
13947        let ClientControlResponse::CatalogList {
13948            generation,
13949            modules,
13950            ..
13951        } = serde_json::from_slice(&reply.body).unwrap()
13952        else {
13953            panic!("not a catalog.list reply");
13954        };
13955        (
13956            generation,
13957            modules
13958                .into_iter()
13959                .map(|entry| (entry.module_id, entry.ready))
13960                .collect(),
13961        )
13962    }
13963
13964    /// A handler whose HELLO for module "aft" on connection 40 is parked
13965    /// between reserving its registry entry and installing its forwarding
13966    /// endpoint. Returns the handler, the two-party barrier (wait once to know
13967    /// the HELLO is parked, once more to release it), the HELLO's thread, and
13968    /// the module's context and receiver.
13969    fn hello_held_before_forwarding() -> (
13970        ControlHandler,
13971        Arc<std::sync::Barrier>,
13972        std::thread::JoinHandle<Vec<Frame>>,
13973        RouteCtx,
13974        mpsc::Receiver<crate::router::OutboundFrame>,
13975    ) {
13976        let hold = Arc::new(std::sync::Barrier::new(2));
13977        let handler = ControlHandler::with_forwarding(
13978            Arc::new(Registry::default()),
13979            Arc::new(ForwardingTable::default()),
13980        )
13981        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
13982        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
13983        let hello = {
13984            let handler = handler.clone();
13985            let module_ctx = module_ctx.clone();
13986            std::thread::spawn(move || {
13987                handler
13988                    .handle_hello(
13989                        module_ctx.connection_id,
13990                        Some(module_ctx.egress.clone()),
13991                        hello_frame("aft", PROTOCOL_VERSION, 7),
13992                    )
13993                    .unwrap()
13994            })
13995        };
13996        (handler, hold, hello, module_ctx, module_rx)
13997    }
13998
13999    /// If a lookup can acquire the registry while publication is parked, let
14000    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
14001    /// after the lookup has tried the lock. Both schedules avoid timing guesses
14002    /// and return the actual lookup result, including an unpublished snapshot
14003    /// when the publication lock is missing.
14004    fn lookup_during_hello_publication<T: Send + 'static>(
14005        registry: &Registry,
14006        hold: &std::sync::Barrier,
14007        lookup: impl FnOnce() -> T + Send + 'static,
14008    ) -> T {
14009        let attempted = registry.observe_next_lock_attempt();
14010        let reader = std::thread::spawn(lookup);
14011        if attempted.recv().unwrap() {
14012            let result = reader.join().unwrap();
14013            hold.wait();
14014            result
14015        } else {
14016            hold.wait();
14017            reader.join().unwrap()
14018        }
14019    }
14020
14021    #[test]
14022    fn catalog_read_after_hello_ack_waits_for_publication() {
14023        let registry = Arc::new(Registry::default());
14024        let hold = Arc::new(std::sync::Barrier::new(2));
14025        let mut handler = ControlHandler::with_forwarding(
14026            Arc::clone(&registry),
14027            Arc::new(ForwardingTable::default()),
14028        );
14029        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
14030        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14031        let hello = {
14032            let handler = handler.clone();
14033            std::thread::spawn(move || {
14034                handler
14035                    .handle_hello(
14036                        module_ctx.connection_id,
14037                        Some(module_ctx.egress),
14038                        hello_frame("aft", PROTOCOL_VERSION, 7),
14039                    )
14040                    .unwrap()
14041            })
14042        };
14043        hold.wait();
14044        assert_eq!(
14045            module_rx.try_recv().unwrap().frame.header.ty,
14046            FrameType::HelloAck
14047        );
14048        let replies = lookup_during_hello_publication(&registry, &hold, move || {
14049            // A different connection can issue catalog.list as soon as the
14050            // module has read its ACK, even while HELLO has not returned.
14051            let request = Frame::build(
14052                FrameType::Request,
14053                control_flags(),
14054                0,
14055                0,
14056                300,
14057                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
14058            )
14059            .unwrap();
14060            handler.handle_catalog_list(request, None).unwrap()
14061        });
14062        assert!(hello.join().unwrap().is_empty());
14063        let ClientControlResponse::CatalogList {
14064            generation,
14065            modules,
14066            ..
14067        } = serde_json::from_slice(&replies[0].body).unwrap()
14068        else {
14069            panic!("not a catalog.list reply");
14070        };
14071        assert_eq!(
14072            modules
14073                .iter()
14074                .map(|entry| entry.module_id.as_str())
14075                .collect::<Vec<_>>(),
14076            vec!["aft"]
14077        );
14078        assert_eq!(generation, 1);
14079    }
14080
14081    /// While a HELLO has reserved its registry entry but its forwarding
14082    /// endpoint is not installed yet, `route.open` to the module can only be
14083    /// refused. `catalog.list` must not list the module in that window: a
14084    /// client that opens a route as soon as it sees a module listed and ready
14085    /// would be refused for a module the daemon had just advertised. The
14086    /// refusal in the window stays the retryable `target_unavailable`, never
14087    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14088    /// Once the HELLO completes, the module is listed and a route to it opens.
14089    #[tokio::test]
14090    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14091        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14092        let client = ConnectionId::new(41);
14093        let (client_ctx, mut client_rx) = route_ctx(client);
14094
14095        hold.wait();
14096        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14097        assert!(handler.registry.get_module("aft").unwrap().is_some());
14098        assert!(!handler
14099            .forwarding
14100            .has_live_module_connection("aft")
14101            .unwrap());
14102        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14103        assert!(
14104            listed.is_empty(),
14105            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14106        );
14107        let refused = handler
14108            .handle_control_frame(
14109                &client_ctx,
14110                route_open_frame(301, "aft", unique_project_root("listed-window")),
14111            )
14112            .await
14113            .unwrap();
14114        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14115        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14116        let duplicate = handler
14117            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14118            .await
14119            .unwrap();
14120        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14121
14122        hold.wait();
14123        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14124        let ack = module_rx.try_recv().unwrap().frame;
14125        assert_eq!(ack.header.ty, FrameType::HelloAck);
14126        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14127        assert_eq!(listed, vec![("aft".to_string(), true)]);
14128
14129        let (open_task, bind) = relay_route_open(
14130            &handler,
14131            client,
14132            &client_ctx.egress,
14133            &mut module_rx,
14134            303,
14135            "aft",
14136            "listed-after",
14137        )
14138        .await;
14139        assert!(handler
14140            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14141            .await
14142            .unwrap()
14143            .is_empty());
14144        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14145        published_route(&client_rx.try_recv().unwrap().frame);
14146    }
14147
14148    /// A catalog watcher keys on the generation: when it changes, it re-reads
14149    /// the listing. So the generation must advance exactly when the module
14150    /// appears. If it advanced while the module was still hidden, a watcher
14151    /// would read the new generation without the module, and the module would
14152    /// later appear under that same generation with nothing telling the
14153    /// watcher to look again.
14154    #[tokio::test]
14155    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14156        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14157        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14158        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14159
14160        hold.wait();
14161        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14162        assert!(listed.is_empty());
14163        assert_eq!(
14164            during, before,
14165            "the generation moved while the module was not listed"
14166        );
14167
14168        hold.wait();
14169        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14170        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14171        assert_eq!(listed, vec![("aft".to_string(), true)]);
14172        assert_eq!(
14173            after,
14174            before + 1,
14175            "the module appeared without exactly one generation bump"
14176        );
14177    }
14178
14179    /// A HELLO whose forwarding endpoint cannot be installed (here the
14180    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14181    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14182    /// and the catalog generation where it was.
14183    #[tokio::test]
14184    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14185        let registry = Arc::new(Registry::default());
14186        let handler = ControlHandler::with_forwarding(
14187            Arc::clone(&registry),
14188            Arc::new(ForwardingTable::default()),
14189        );
14190        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14191        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14192        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14193        drop(module_rx);
14194
14195        let replies = handler
14196            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14197            .await
14198            .unwrap();
14199        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14200        assert!(registry.get_module("aft").unwrap().is_none());
14201        assert!(registry
14202            .get_module_by_connection(module_ctx.connection_id)
14203            .unwrap()
14204            .is_none());
14205        assert_eq!(
14206            catalog_snapshot(&handler, &client_ctx, 301).await,
14207            (before, Vec::new())
14208        );
14209    }
14210
14211    /// A handler whose `route.open` parks after queueing the route.bind and
14212    /// before marking it enqueued, with module "aft" registered on connection
14213    /// 40. Returns the two-party barrier that parks and releases it.
14214    async fn route_open_held_after_bind_send() -> (
14215        ControlHandler,
14216        Arc<tokio::sync::Barrier>,
14217        RouteCtx,
14218        mpsc::Receiver<crate::router::OutboundFrame>,
14219    ) {
14220        let hold = Arc::new(tokio::sync::Barrier::new(2));
14221        let handler = ControlHandler::with_forwarding(
14222            Arc::new(Registry::default()),
14223            Arc::new(ForwardingTable::default()),
14224        )
14225        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14226        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14227        hello_via_sink(
14228            &handler,
14229            &module_ctx,
14230            &mut module_rx,
14231            hello_frame("aft", PROTOCOL_VERSION, 7),
14232        )
14233        .await;
14234        (handler, hold, module_ctx, module_rx)
14235    }
14236
14237    /// A fast module acks the route.bind, and the reader commits the route,
14238    /// before `route.open` has marked the relay enqueued. The daemon used to
14239    /// read the missing relay as an abandoned bind and send the module a
14240    /// GOODBYE for the route it had just committed: the client was told its
14241    /// route was open, the module unbound the channel, and the client's first
14242    /// request was dropped on the module side as unbound.
14243    #[tokio::test]
14244    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14245        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14246        let client = ConnectionId::new(41);
14247        let (client_ctx, mut client_rx) = route_ctx(client);
14248
14249        let (open_task, bind) = relay_route_open(
14250            &handler,
14251            client,
14252            &client_ctx.egress,
14253            &mut module_rx,
14254            200,
14255            "aft",
14256            "acked-before-mark",
14257        )
14258        .await;
14259        let (module_channel, module_epoch) = route_bind_channel(&bind);
14260        // route.open is now parked between queueing the bind and marking it.
14261        hold.wait().await;
14262
14263        // The module answers inside that window, and the route commits.
14264        assert!(handler
14265            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14266            .await
14267            .unwrap()
14268            .is_empty());
14269        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14270
14271        hold.wait().await;
14272        assert!(
14273            open_task.await.unwrap().is_empty(),
14274            "route.open answers accepted"
14275        );
14276
14277        // Every frame route.open could have sent is already queued, because it
14278        // has returned; the module must have been sent nothing.
14279        match module_rx.try_recv() {
14280            Err(mpsc::error::TryRecvError::Empty) => {}
14281            Ok(outbound) => panic!(
14282                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14283                outbound.frame.header.ty,
14284                outbound.frame.header.channel,
14285                outbound.frame.header.epoch
14286            ),
14287            Err(err) => panic!("module egress closed: {err}"),
14288        }
14289
14290        // The client's first request on the route is the next thing the module
14291        // reads, on the binding it just created.
14292        let router = Router::with_control_handler(Arc::new(handler.clone()));
14293        let request = Frame::build(
14294            FrameType::Request,
14295            Flags::new(true, Priority::Interactive, false),
14296            client_channel,
14297            client_epoch,
14298            201,
14299            b"first request".to_vec(),
14300        )
14301        .unwrap();
14302        router
14303            .route_for_connection(&client_ctx, request)
14304            .await
14305            .unwrap();
14306        let delivered = module_rx.try_recv().unwrap().frame;
14307        assert_eq!(delivered.header.ty, FrameType::Request);
14308        assert_eq!(
14309            (delivered.header.channel, delivered.header.epoch),
14310            (module_channel, module_epoch)
14311        );
14312        assert_eq!(delivered.body, b"first request");
14313    }
14314
14315    /// The client goes away while `route.open` is still queueing the bind, so
14316    /// the relay is dropped with no module reply. The teardown cannot send the
14317    /// GOODBYE itself (it could reach the module ahead of the bind), so
14318    /// `route.open` must send it once the bind is queued; otherwise the module
14319    /// keeps a binding the daemon will never commit.
14320    #[tokio::test]
14321    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14322        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14323        let client = ConnectionId::new(42);
14324        let (client_ctx, _client_rx) = route_ctx(client);
14325
14326        let (open_task, bind) = relay_route_open(
14327            &handler,
14328            client,
14329            &client_ctx.egress,
14330            &mut module_rx,
14331            300,
14332            "aft",
14333            "released-before-mark",
14334        )
14335        .await;
14336        let (module_channel, module_epoch) = route_bind_channel(&bind);
14337        hold.wait().await;
14338
14339        handler.cleanup_connection(client).unwrap();
14340        assert!(
14341            module_rx.try_recv().is_err(),
14342            "client teardown must not GOODBYE a bind route.open is still queueing"
14343        );
14344
14345        hold.wait().await;
14346        let response = open_task.await.unwrap();
14347        assert_eq!(response.len(), 1);
14348        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14349
14350        let goodbye = module_rx
14351            .try_recv()
14352            .expect("module is told to drop the binding the daemon abandoned")
14353            .frame;
14354        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14355        assert_eq!(
14356            (goodbye.header.channel, goodbye.header.epoch),
14357            (module_channel, module_epoch)
14358        );
14359        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14360    }
14361
14362    /// The module acks inside the same window, but the client's egress closed
14363    /// first, so the reader refuses to commit. The ack proves the module holds
14364    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14365    /// send a second one.
14366    #[tokio::test]
14367    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14368        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14369        let client = ConnectionId::new(43);
14370        let (client_ctx, client_rx) = route_ctx(client);
14371
14372        let (open_task, bind) = relay_route_open(
14373            &handler,
14374            client,
14375            &client_ctx.egress,
14376            &mut module_rx,
14377            400,
14378            "aft",
14379            "gone-client-before-mark",
14380        )
14381        .await;
14382        let (module_channel, module_epoch) = route_bind_channel(&bind);
14383        hold.wait().await;
14384
14385        drop(client_rx);
14386        assert!(client_ctx.egress.is_closed());
14387        handler
14388            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14389            .await
14390            .unwrap();
14391
14392        hold.wait().await;
14393        let response = open_task.await.unwrap();
14394        assert_eq!(response.len(), 1);
14395        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14396
14397        let goodbye = module_rx
14398            .try_recv()
14399            .expect("module is told to drop the binding it acked")
14400            .frame;
14401        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14402        assert_eq!(
14403            (goodbye.header.channel, goodbye.header.epoch),
14404            (module_channel, module_epoch)
14405        );
14406        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14407        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14408    }
14409
14410    /// The fence at the module-loop boundary, stated as its own contract: which
14411    /// forwarding failures are allowed to end the module connection that is being
14412    /// served. A `ConnectionClosing` naming some client is about that client, and
14413    /// a module connection is shared; the same error naming the module's own
14414    /// connection is about this connection and must stay fatal, as must failures
14415    /// that are about the forwarding table itself.
14416    #[test]
14417    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14418        let handler = ControlHandler::default();
14419        let module_connection = ConnectionId::new(30);
14420        let client_connection = ConnectionId::new(31);
14421
14422        handler
14423            .refuse_to_end_module_connection_for_a_client(
14424                module_connection,
14425                77,
14426                ForwardingError::ConnectionClosing {
14427                    connection_id: client_connection,
14428                },
14429            )
14430            .expect("a closing client must never end the module connection");
14431
14432        assert!(matches!(
14433            handler.refuse_to_end_module_connection_for_a_client(
14434                module_connection,
14435                78,
14436                ForwardingError::ConnectionClosing {
14437                    connection_id: module_connection,
14438                },
14439            ),
14440            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14441                connection_id
14442            })) if connection_id == module_connection
14443        ));
14444        assert!(matches!(
14445            handler.refuse_to_end_module_connection_for_a_client(
14446                module_connection,
14447                79,
14448                ForwardingError::Poisoned,
14449            ),
14450            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14451        ));
14452        assert!(matches!(
14453            handler.refuse_to_end_module_connection_for_a_client(
14454                module_connection,
14455                80,
14456                ForwardingError::StaleModuleEndpoint,
14457            ),
14458            Err(RouterError::Forwarding(
14459                ForwardingError::StaleModuleEndpoint
14460            ))
14461        ));
14462    }
14463
14464    /// The spawn-attestation guard is what stops a connected module from claiming
14465    /// another module's identity and being stamped `Reserved` for it. Every other
14466    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14467    /// correct one is what the rest of the flow needs -- so the guard's rejection
14468    /// branch was never the subject of an assertion, only its acceptance branch.
14469    ///
14470    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14471    /// whole subc-core library suite green; only the forwarding integration tests
14472    /// notice, and they notice for unrelated reasons. This test exists so the
14473    /// refusal itself is asserted where the guard lives: it fails if the identity
14474    /// check stops refusing, which is the direction that matters, since a guard
14475    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14476    #[tokio::test]
14477    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14478        let registry = Arc::new(Registry::default());
14479        let forwarding = Arc::new(ForwardingTable::default());
14480        let supervisor = SupervisorHandle::new();
14481        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14482        let handler =
14483            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14484                .with_supervisor(supervisor);
14485
14486        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14487        hello_via_sink(
14488            &handler,
14489            &target_ctx,
14490            &mut target_rx,
14491            hello_frame("target", PROTOCOL_VERSION, 1),
14492        )
14493        .await;
14494
14495        // A real supervised module id presenting the wrong nonce. This is the
14496        // impersonation case: the attacker knows a privileged module_id, which is
14497        // public, and guesses at the nonce, which is not.
14498        let wrong_nonce = handler
14499            .handle_control_frame(
14500                &route_ctx(ConnectionId::new(91)).0,
14501                route_open_frame_with_admission_facts(
14502                    20,
14503                    "target",
14504                    unique_project_root("admission-facts"),
14505                    Some(subc_control::ConsumerIdentity {
14506                        module_id: "fed".to_string(),
14507                        launch_nonce: "not-the-real-nonce".to_string(),
14508                    }),
14509                    None,
14510                ),
14511            )
14512            .await
14513            .unwrap();
14514        assert_eq!(
14515            parse_error(&wrong_nonce[0])["code"],
14516            "bad_consumer_identity",
14517            "a mismatched launch nonce must be refused, not stamped Reserved"
14518        );
14519
14520        // A module id the supervisor never spawned at all, so no nonce exists to
14521        // compare against. An implementation that treats "no record" as "nothing
14522        // to check" fails open here while passing the case above.
14523        let never_spawned = handler
14524            .handle_control_frame(
14525                &route_ctx(ConnectionId::new(92)).0,
14526                route_open_frame_with_admission_facts(
14527                    21,
14528                    "target",
14529                    unique_project_root("admission-facts"),
14530                    Some(subc_control::ConsumerIdentity {
14531                        module_id: "never-spawned".to_string(),
14532                        launch_nonce: "any-nonce".to_string(),
14533                    }),
14534                    None,
14535                ),
14536            )
14537            .await
14538            .unwrap();
14539        assert_eq!(
14540            parse_error(&never_spawned[0])["code"],
14541            "bad_consumer_identity",
14542            "an unspawned module_id must be refused rather than accepted for lack of a record"
14543        );
14544    }
14545
14546    /// The refusal test above proves the guard says NO. Nothing proved it can say
14547    /// YES, and the difference is not academic: replacing the whole authorization
14548    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14549    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14550    /// library tests GREEN. The one that notices does so by HANGING, because it
14551    /// waits for a bind that can no longer happen.
14552    ///
14553    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14554    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14555    /// hangs too and gets blamed on the runner. So a total revocation of the
14556    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14557    /// to code.
14558    ///
14559    /// The bias is structural rather than accidental. A REFUSAL looks like a
14560    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14561    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14562    /// suite for that reason, and this one is the purest case in the daemon.
14563    ///
14564    /// This test asserts the EFFECT rather than the absence of an error: the module
14565    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14566    /// A guard that admitted nobody would produce no bind at all; one that admitted
14567    /// everybody would stamp the wrong principal, which the refusal test catches.
14568    #[tokio::test]
14569    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14570        let registry = Arc::new(Registry::default());
14571        let forwarding = Arc::new(ForwardingTable::default());
14572        let supervisor = SupervisorHandle::new();
14573        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14574        let handler =
14575            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14576                .with_supervisor(supervisor);
14577
14578        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14579        hello_via_sink(
14580            &handler,
14581            &target_ctx,
14582            &mut target_rx,
14583            hello_frame("target", PROTOCOL_VERSION, 1),
14584        )
14585        .await;
14586
14587        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14588        let route_handler = handler.clone();
14589        let route_task = tokio::spawn(async move {
14590            route_handler
14591                .handle_control_frame(
14592                    &client_ctx,
14593                    route_open_frame_with_admission_facts(
14594                        30,
14595                        "target",
14596                        unique_project_root("admission-facts"),
14597                        Some(subc_control::ConsumerIdentity {
14598                            module_id: "fed".to_string(),
14599                            launch_nonce: "fed-nonce".to_string(),
14600                        }),
14601                        None,
14602                    ),
14603                )
14604                .await
14605                .unwrap()
14606        });
14607
14608        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14609        // the very mutation it exists to catch -- a guard that admits nobody -- no
14610        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14611        // exact defect being fixed: a total revocation detected only as a stalled
14612        // suite, which reads as flakiness and invites a retry. An acceptance test
14613        // that waits for an effect must bound the wait, or a red becomes a hang.
14614        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14615            .await
14616            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14617            .expect("module control channel closed before route.bind");
14618        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14619        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14620            panic!("expected route.bind")
14621        };
14622        assert_eq!(
14623            principal,
14624            Some(Principal::Reserved {
14625                module_id: "fed".to_string()
14626            }),
14627            "a correctly attested consumer must be stamped Reserved for its own id"
14628        );
14629
14630        handler
14631            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14632            .await
14633            .unwrap();
14634        assert!(route_task.await.unwrap().is_empty());
14635        assert!(
14636            matches!(
14637                serde_json::from_slice::<ClientControlResponse>(
14638                    &client_rx.recv().await.unwrap().body
14639                )
14640                .unwrap(),
14641                ClientControlResponse::RouteOpen { .. }
14642            ),
14643            "the route must actually open, not merely avoid an error"
14644        );
14645    }
14646
14647    #[tokio::test(start_paused = true)]
14648    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14649        let registry = Arc::new(Registry::default());
14650        let forwarding = Arc::new(ForwardingTable::default());
14651        let supervisor = SupervisorHandle::new();
14652        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14653        let handler =
14654            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14655                .with_supervisor(supervisor);
14656
14657        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14658        hello_via_sink(
14659            &handler,
14660            &target_ctx,
14661            &mut target_rx,
14662            hello_frame("target", PROTOCOL_VERSION, 1),
14663        )
14664        .await;
14665
14666        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14667        let direct_handler = handler.clone();
14668        let direct_open = tokio::spawn(async move {
14669            direct_handler
14670                .handle_control_frame(
14671                    &direct_ctx,
14672                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14673                )
14674                .await
14675                .unwrap()
14676        });
14677        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14678            .await
14679            .expect("no direct route.bind within 5s")
14680            .expect("target control channel closed before direct route.bind");
14681        handler
14682            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14683            .await
14684            .unwrap();
14685        assert!(direct_open.await.unwrap().is_empty());
14686        let _ = direct_rx.recv().await.unwrap();
14687
14688        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14689        let reserved_handler = handler.clone();
14690        let reserved_open = tokio::spawn(async move {
14691            reserved_handler
14692                .handle_control_frame(
14693                    &reserved_ctx,
14694                    route_open_frame_with_admission_facts(
14695                        3,
14696                        "target",
14697                        unique_project_root("admission-facts"),
14698                        Some(ConsumerIdentity {
14699                            module_id: "fed".to_string(),
14700                            launch_nonce: "fed-nonce".to_string(),
14701                        }),
14702                        None,
14703                    ),
14704                )
14705                .await
14706                .unwrap()
14707        });
14708        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14709            .await
14710            .expect("no reserved route.bind within 5s")
14711            .expect("target control channel closed before reserved route.bind");
14712        handler
14713            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14714            .await
14715            .unwrap();
14716        assert!(reserved_open.await.unwrap().is_empty());
14717        let _ = reserved_rx.recv().await.unwrap();
14718
14719        forwarding
14720            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14721            .unwrap();
14722        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14723        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14724            module_id: Some("target".to_string()),
14725        })
14726        .unwrap();
14727        let census_frame =
14728            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14729        let response = handler
14730            .handle_control_frame(&census_ctx, census_frame)
14731            .await
14732            .unwrap()
14733            .pop()
14734            .unwrap();
14735        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14736        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14737        assert!(matches!(
14738            decoded,
14739            ClientControlResponse::SupervisorRoutes { .. }
14740        ));
14741        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14742        assert_eq!(routes.len(), 2);
14743        assert!(routes.iter().all(|route| route["draining"] == true));
14744        // The census carries WHY: the reason the drain was begun with, in the
14745        // route.closing vocabulary, on every draining route this drain marked.
14746        assert!(
14747            routes.iter().all(|route| route["drain_reason"] == "reload"),
14748            "draining routes must name the drain's reason: {routes:?}"
14749        );
14750        assert!(routes.iter().any(|route| {
14751            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14752        }));
14753        assert!(routes.iter().any(|route| {
14754            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14755        }));
14756
14757        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14758            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14759        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14760            std::fs::write(
14761                &golden_path,
14762                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14763            )
14764            .unwrap();
14765        }
14766        let expected: Value =
14767            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14768        assert_eq!(actual, expected);
14769    }
14770
14771    async fn query_live_roots(
14772        handler: &ControlHandler,
14773        module_ctx: &RouteCtx,
14774    ) -> ModuleControlResponseToModule {
14775        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14776        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14777        let response = handler
14778            .handle_control_frame(module_ctx, frame)
14779            .await
14780            .unwrap()
14781            .pop()
14782            .unwrap();
14783        serde_json::from_slice(&response.body).unwrap()
14784    }
14785
14786    #[tokio::test(start_paused = true)]
14787    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14788        let registry = Arc::new(Registry::default());
14789        let forwarding = Arc::new(ForwardingTable::default());
14790        let handler = ControlHandler::with_forwarding(registry, forwarding);
14791        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14792        hello_via_sink(
14793            &handler,
14794            &target_ctx,
14795            &mut target_rx,
14796            hello_frame("target", PROTOCOL_VERSION, 1),
14797        )
14798        .await;
14799        let root = unique_project_root("live-roots-known");
14800        let path = ProjectRootId::from_path_allowing_missing(root.path())
14801            .unwrap()
14802            .as_path()
14803            .to_path_buf();
14804        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14805        let open_handler = handler.clone();
14806        let opened = tokio::spawn(async move {
14807            open_handler
14808                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14809                .await
14810                .unwrap()
14811        });
14812        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14813            .await
14814            .unwrap()
14815            .unwrap();
14816        handler
14817            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14818            .await
14819            .unwrap();
14820        assert!(opened.await.unwrap().is_empty());
14821        let _ = client_rx.recv().await.unwrap();
14822
14823        let root = unique_project_root("live-roots-pending");
14824        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14825            .unwrap()
14826            .as_path()
14827            .to_path_buf();
14828        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14829        let open_handler = handler.clone();
14830        let pending = tokio::spawn(async move {
14831            open_handler
14832                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14833                .await
14834                .unwrap()
14835        });
14836        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14837            .await
14838            .unwrap()
14839            .unwrap();
14840        let actual = query_live_roots(&handler, &target_ctx).await;
14841        let ModuleControlResponseToModule::LiveRoots {
14842            roots,
14843            unknown_root_bindings,
14844            total_bindings,
14845        } = actual
14846        else {
14847            panic!("expected live roots")
14848        };
14849        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14850        assert_eq!(unknown_root_bindings, 0);
14851        assert_eq!(
14852            roots.len(),
14853            2,
14854            "root-known arm must retain each canonical root"
14855        );
14856        assert_eq!(
14857            total_bindings,
14858            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14859        );
14860        let counts = roots
14861            .iter()
14862            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14863            .collect::<Vec<_>>();
14864        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14865        expected.sort_by(|a, b| a.0.cmp(&b.0));
14866        assert_eq!(
14867            counts, expected,
14868            "roots must sort by path and count pending separately"
14869        );
14870        handler
14871            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14872            .await
14873            .unwrap();
14874        assert!(pending.await.unwrap().is_empty());
14875    }
14876
14877    #[tokio::test(start_paused = true)]
14878    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14879        let forwarding = Arc::new(ForwardingTable::default());
14880        let handler =
14881            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14882        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14883        hello_via_sink(
14884            &handler,
14885            &target_ctx,
14886            &mut target_rx,
14887            hello_frame("target", PROTOCOL_VERSION, 1),
14888        )
14889        .await;
14890        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14891        let pending = forwarding
14892            .begin_route_bind_relay_for_test(
14893                client_ctx.connection_id,
14894                client_ctx.egress.clone(),
14895                2,
14896                "target",
14897            )
14898            .unwrap();
14899        forwarding
14900            .complete_pending_relay(
14901                target_ctx.connection_id,
14902                pending.corr,
14903                RouteBindRelayOutcome::Accepted,
14904            )
14905            .unwrap();
14906        let actual = query_live_roots(&handler, &target_ctx).await;
14907        let ModuleControlResponseToModule::LiveRoots {
14908            roots,
14909            unknown_root_bindings,
14910            total_bindings,
14911        } = actual
14912        else {
14913            panic!("expected live roots")
14914        };
14915        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14916        assert_eq!(
14917            unknown_root_bindings, 1,
14918            "unknown-root arm must not read as no bindings"
14919        );
14920        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14921        assert_eq!(
14922            total_bindings,
14923            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14924        );
14925    }
14926
14927    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14928    /// so the ack has to be on its outbound queue before the module is
14929    /// routable. The connection loop writes a handler's replies only after the
14930    /// handler returns; this test stops in exactly that gap, runs a real
14931    /// route.open from another connection, and only then writes whatever the
14932    /// HELLO handler returned, the way the loop would. If the ack were still a
14933    /// reply, the route.bind request would reach the module first.
14934    #[tokio::test(start_paused = true)]
14935    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14936        let forwarding = Arc::new(ForwardingTable::default());
14937        let handler =
14938            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14939        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14940        let replies = handler
14941            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14942            .await
14943            .unwrap();
14944        let queued_by_hello = module_rx.len();
14945
14946        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14947        let open_handler = handler.clone();
14948        let open = tokio::spawn(async move {
14949            open_handler
14950                .handle_control_frame(
14951                    &client_ctx,
14952                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14953                )
14954                .await
14955                .unwrap()
14956        });
14957        // Let the route.open run until its route.bind is on the module's queue.
14958        let mut spins = 0;
14959        while module_rx.len() == queued_by_hello {
14960            spins += 1;
14961            assert!(spins < 10_000, "route.open never queued a route.bind");
14962            tokio::task::yield_now().await;
14963        }
14964
14965        // Now the connection loop's half: write the HELLO handler's replies.
14966        for reply in replies {
14967            module_ctx.egress.send(reply).await.unwrap();
14968        }
14969
14970        let first = module_rx.recv().await.unwrap().frame;
14971        assert_eq!(
14972            first.header.ty,
14973            FrameType::HelloAck,
14974            "the first frame a registering module reads must be its HELLO_ACK"
14975        );
14976        assert_eq!(first.header.corr, 7);
14977        let second = module_rx.recv().await.unwrap().frame;
14978        assert_eq!(second.header.ty, FrameType::Request);
14979        assert!(
14980            matches!(
14981                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
14982                ModuleControlRequest::RouteBind { .. }
14983            ),
14984            "the route.bind follows the ack"
14985        );
14986        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
14987
14988        handler
14989            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
14990            .await
14991            .unwrap();
14992        assert!(open.await.unwrap().is_empty());
14993        let _ = client_rx.recv().await.unwrap();
14994    }
14995
14996    #[tokio::test(start_paused = true)]
14997    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
14998        let handler = ControlHandler::with_forwarding(
14999            Arc::new(Registry::default()),
15000            Arc::new(ForwardingTable::default()),
15001        );
15002        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
15003        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
15004        hello_via_sink(
15005            &handler,
15006            &first_ctx,
15007            &mut first_rx,
15008            hello_frame("first", PROTOCOL_VERSION, 1),
15009        )
15010        .await;
15011        hello_via_sink(
15012            &handler,
15013            &second_ctx,
15014            &mut second_rx,
15015            hello_frame("second", PROTOCOL_VERSION, 2),
15016        )
15017        .await;
15018        let root = unique_project_root("second-only");
15019        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
15020        let cloned = handler.clone();
15021        let open = tokio::spawn(async move {
15022            cloned
15023                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
15024                .await
15025                .unwrap()
15026        });
15027        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
15028            .await
15029            .unwrap()
15030            .unwrap();
15031        let first = query_live_roots(&handler, &first_ctx).await;
15032        let second = query_live_roots(&handler, &second_ctx).await;
15033        assert!(
15034            matches!(
15035                first,
15036                ModuleControlResponseToModule::LiveRoots {
15037                    total_bindings: 0,
15038                    ..
15039                }
15040            ),
15041            "cross-module scope must not expose another module's roots"
15042        );
15043        assert!(
15044            matches!(
15045                second,
15046                ModuleControlResponseToModule::LiveRoots {
15047                    total_bindings: 1,
15048                    ..
15049                }
15050            ),
15051            "second module must see its pending route"
15052        );
15053        handler
15054            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
15055            .await
15056            .unwrap();
15057        assert!(open.await.unwrap().is_empty());
15058    }
15059
15060    #[tokio::test(start_paused = true)]
15061    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
15062        let handler = ControlHandler::with_forwarding(
15063            Arc::new(Registry::default()),
15064            Arc::new(ForwardingTable::default()),
15065        );
15066        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15067        hello_via_sink(
15068            &handler,
15069            &target_ctx,
15070            &mut target_rx,
15071            hello_frame("target", PROTOCOL_VERSION, 1),
15072        )
15073        .await;
15074        let actual = query_live_roots(&handler, &target_ctx).await;
15075        let ModuleControlResponseToModule::LiveRoots {
15076            roots,
15077            unknown_root_bindings,
15078            total_bindings,
15079        } = actual
15080        else {
15081            panic!("expected live roots")
15082        };
15083        assert!(roots.is_empty());
15084        assert_eq!(unknown_root_bindings, 0);
15085        assert_eq!(total_bindings, 0);
15086        assert_eq!(
15087            total_bindings,
15088            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15089        );
15090    }
15091
15092    /// Read the vendored fed corpus rather than hand-building a package.
15093    ///
15094    /// A hand-built object encodes what the test author believed the carrier
15095    /// emits. These vectors are what it actually emits, and one of them exists
15096    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15097    /// ignores additive unknown fields at the traversal emit terminus."
15098    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15099        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15100            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15101        let text = std::fs::read_to_string(&path)
15102            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15103        let vectors: Vec<(String, Value)> = text
15104            .lines()
15105            .filter(|line| !line.trim().is_empty())
15106            .map(|line| {
15107                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15108                let id = entry["corpus_id"]
15109                    .as_str()
15110                    .expect("every vector carries a corpus_id")
15111                    .to_string();
15112                (id, entry["package"].clone())
15113            })
15114            .collect();
15115        // Pin the count: a corpus that silently shrinks would take its coverage
15116        // with it, and a suite reading N-1 vectors reports the same clean pass
15117        // as one reading N.
15118        assert_eq!(
15119            vectors.len(),
15120            3,
15121            "vendored fed corpus changed size; re-sync from subc-federation"
15122        );
15123
15124        // Pin what makes the corpus DISCRIMINATING, not just present.
15125        //
15126        // The relay test below takes its expected value from the corpus, so the
15127        // corpus supplies the test's power to detect a lossy relay rather than
15128        // its correctness. A relay that dropped unrecognised fields would still
15129        // be caught -- but only by a package carrying fields it does not know.
15130        // Shrink every package to the handful of keys any implementation would
15131        // recognise and the test keeps passing over an input that can no longer
15132        // fail, which is the same clean green as a corpus that shrank away.
15133        //
15134        // So assert the precondition rather than duplicating the packages here:
15135        // at least one vector must carry a field beyond the small common set.
15136        // That is one claim to maintain instead of nine, and it fails loudly if
15137        // a re-sync ever flattens the corpus.
15138        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15139        let richest = vectors
15140            .iter()
15141            .filter_map(|(_, package)| package.as_object())
15142            .map(|object| {
15143                object
15144                    .keys()
15145                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15146                    .count()
15147            })
15148            .max()
15149            .unwrap_or(0);
15150        assert!(
15151            richest >= 2,
15152            "vendored corpus no longer carries a package with unmodelled fields, \
15153             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15154        );
15155
15156        vectors
15157    }
15158
15159    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15160    ///
15161    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15162    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15163    /// three-key object, so a relay that quietly dropped fields it did not
15164    /// recognise would satisfy it. These vectors carry nine keys including ones
15165    /// this crate has no type for, so a typed relay fails here and only here.
15166    #[tokio::test]
15167    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15168        for (corpus_id, package) in fed_admission_facts_vectors() {
15169            let registry = Arc::new(Registry::default());
15170            let forwarding = Arc::new(ForwardingTable::default());
15171            let supervisor = SupervisorHandle::new();
15172            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15173            let handler =
15174                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15175                    .with_supervisor(supervisor)
15176                    .with_admission_facts_config(
15177                        Some("fed".to_string()),
15178                        Some(vec!["target".to_string()]),
15179                    );
15180
15181            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15182            hello_via_sink(
15183                &handler,
15184                &target_ctx,
15185                &mut target_rx,
15186                hello_frame("target", PROTOCOL_VERSION, 1),
15187            )
15188            .await;
15189
15190            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15191            let route_handler = handler.clone();
15192            let expected = package.clone();
15193            let route_task = tokio::spawn(async move {
15194                route_handler
15195                    .handle_control_frame(
15196                        &client_ctx,
15197                        route_open_frame_with_admission_facts(
15198                            20,
15199                            "target",
15200                            unique_project_root("admission-facts"),
15201                            Some(subc_control::ConsumerIdentity {
15202                                module_id: "fed".to_string(),
15203                                launch_nonce: "fed-nonce".to_string(),
15204                            }),
15205                            Some(package),
15206                        ),
15207                    )
15208                    .await
15209                    .unwrap()
15210            });
15211
15212            let bind_frame = target_rx.recv().await.unwrap();
15213            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15214            let ModuleControlRequest::RouteBind {
15215                admission_facts, ..
15216            } = bind
15217            else {
15218                panic!("{corpus_id}: expected route.bind")
15219            };
15220            assert_eq!(
15221                admission_facts,
15222                Some(expected),
15223                "{corpus_id}: relay must not add, drop or reshape any field"
15224            );
15225
15226            handler
15227                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15228                .await
15229                .unwrap();
15230            route_task.await.unwrap();
15231        }
15232    }
15233
15234    #[tokio::test]
15235    async fn route_bind_never_relays_the_openers_build_class() {
15236        let registry = Arc::new(Registry::default());
15237        let forwarding = Arc::new(ForwardingTable::default());
15238        let handler =
15239            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15240        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15241        hello_via_sink(
15242            &handler,
15243            &target_ctx,
15244            &mut target_rx,
15245            hello_frame("target", PROTOCOL_VERSION, 1),
15246        )
15247        .await;
15248
15249        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15250        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15251        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15252            busy_refusals: None,
15253            target: RouteTarget::ToolProvider {
15254                module_id: "target".to_string(),
15255            },
15256            identity,
15257            consumer_identity: None,
15258            consumer_capabilities: None,
15259            role_versions: None,
15260            admission_facts: None,
15261            scope: None,
15262        })
15263        .unwrap();
15264        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15265
15266        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15267        let route_handler = handler.clone();
15268        let route_task = tokio::spawn(async move {
15269            route_handler
15270                .handle_control_frame(&client_ctx, open)
15271                .await
15272                .unwrap()
15273        });
15274        let bind_frame = target_rx.recv().await.unwrap();
15275        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15276        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15277            panic!("expected route.bind")
15278        };
15279        assert_eq!(
15280            identity.build_class, None,
15281            "route.bind carried the build class"
15282        );
15283        assert!(
15284            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15285            "the route.bind bytes still name build_class"
15286        );
15287        handler
15288            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15289            .await
15290            .unwrap();
15291        route_task.await.unwrap();
15292    }
15293
15294    #[tokio::test]
15295    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15296        let registry = Arc::new(Registry::default());
15297        let forwarding = Arc::new(ForwardingTable::default());
15298        let supervisor = SupervisorHandle::new();
15299        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15300        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15301        let handler =
15302            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15303                .with_supervisor(supervisor)
15304                .with_admission_facts_config(
15305                    Some("fed".to_string()),
15306                    Some(vec!["target".to_string()]),
15307                );
15308
15309        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15310        hello_via_sink(
15311            &handler,
15312            &target_ctx,
15313            &mut target_rx,
15314            hello_frame("target", PROTOCOL_VERSION, 1),
15315        )
15316        .await;
15317        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15318        hello_via_sink(
15319            &handler,
15320            &other_ctx,
15321            &mut other_rx,
15322            hello_frame("other", PROTOCOL_VERSION, 2),
15323        )
15324        .await;
15325
15326        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15327        let expected_facts = facts.clone();
15328        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15329        let route_handler = handler.clone();
15330        let route_task = tokio::spawn(async move {
15331            route_handler
15332                .handle_control_frame(
15333                    &client_ctx,
15334                    route_open_frame_with_admission_facts(
15335                        10,
15336                        "target",
15337                        unique_project_root("admission-facts"),
15338                        Some(subc_control::ConsumerIdentity {
15339                            module_id: "fed".to_string(),
15340                            launch_nonce: "fed-nonce".to_string(),
15341                        }),
15342                        Some(facts.clone()),
15343                    ),
15344                )
15345                .await
15346                .unwrap()
15347        });
15348        let bind_frame = target_rx.recv().await.unwrap();
15349        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15350        let ModuleControlRequest::RouteBind {
15351            admission_facts, ..
15352        } = bind
15353        else {
15354            panic!("expected route.bind")
15355        };
15356        assert_eq!(admission_facts, Some(expected_facts));
15357        handler
15358            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15359            .await
15360            .unwrap();
15361        assert!(route_task.await.unwrap().is_empty());
15362        assert!(matches!(
15363            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15364                .unwrap(),
15365            ClientControlResponse::RouteOpen { .. }
15366        ));
15367
15368        let direct = handler
15369            .handle_control_frame(
15370                &route_ctx(ConnectionId::new(73)).0,
15371                route_open_frame_with_admission_facts(
15372                    11,
15373                    "target",
15374                    unique_project_root("admission-facts"),
15375                    None,
15376                    Some(json!({"x": 1})),
15377                ),
15378            )
15379            .await
15380            .unwrap();
15381        assert_eq!(
15382            parse_error(&direct[0])["code"],
15383            "admission_facts_not_permitted"
15384        );
15385
15386        let different_reserved = handler
15387            .handle_control_frame(
15388                &route_ctx(ConnectionId::new(77)).0,
15389                route_open_frame_with_admission_facts(
15390                    15,
15391                    "target",
15392                    unique_project_root("admission-facts"),
15393                    Some(subc_control::ConsumerIdentity {
15394                        module_id: "other".to_string(),
15395                        launch_nonce: "other-nonce".to_string(),
15396                    }),
15397                    Some(json!({"x": 1})),
15398                ),
15399            )
15400            .await
15401            .unwrap();
15402        assert_eq!(
15403            parse_error(&different_reserved[0])["code"],
15404            "admission_facts_not_permitted"
15405        );
15406
15407        let other_target = handler
15408            .handle_control_frame(
15409                &route_ctx(ConnectionId::new(74)).0,
15410                route_open_frame_with_admission_facts(
15411                    12,
15412                    "other",
15413                    unique_project_root("admission-facts"),
15414                    Some(subc_control::ConsumerIdentity {
15415                        module_id: "fed".to_string(),
15416                        launch_nonce: "fed-nonce".to_string(),
15417                    }),
15418                    Some(json!({"x": 1})),
15419                ),
15420            )
15421            .await
15422            .unwrap();
15423        assert_eq!(
15424            parse_error(&other_target[0])["code"],
15425            "admission_facts_target_not_allowed"
15426        );
15427
15428        let nonexistent = handler
15429            .handle_control_frame(
15430                &route_ctx(ConnectionId::new(75)).0,
15431                route_open_frame_with_admission_facts(
15432                    13,
15433                    "missing",
15434                    unique_project_root("admission-facts"),
15435                    None,
15436                    Some(json!({"x": 1})),
15437                ),
15438            )
15439            .await
15440            .unwrap();
15441        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15442
15443        let described = handler
15444            .handle_control_frame(
15445                &route_ctx(ConnectionId::new(76)).0,
15446                Frame::build(
15447                    FrameType::Request,
15448                    control_flags(),
15449                    0,
15450                    0,
15451                    14,
15452                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15453                )
15454                .unwrap(),
15455            )
15456            .await
15457            .unwrap();
15458        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15459            serde_json::from_slice(&described[0].body).unwrap()
15460        else {
15461            panic!("expected server.describe response")
15462        };
15463        assert!(capabilities
15464            .iter()
15465            .any(|cap| cap == "admission_facts_relay_v1"));
15466    }
15467
15468    #[tokio::test]
15469    async fn admission_facts_without_configured_carrier_are_rejected() {
15470        let registry = Arc::new(Registry::default());
15471        let forwarding = Arc::new(ForwardingTable::default());
15472        let handler = ControlHandler::with_forwarding(registry, forwarding);
15473        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15474        hello_via_sink(
15475            &handler,
15476            &target_ctx,
15477            &mut target_rx,
15478            hello_frame("target", PROTOCOL_VERSION, 1),
15479        )
15480        .await;
15481
15482        let responses = handler
15483            .handle_control_frame(
15484                &route_ctx(ConnectionId::new(79)).0,
15485                route_open_frame_with_admission_facts(
15486                    16,
15487                    "target",
15488                    unique_project_root("admission-facts"),
15489                    None,
15490                    Some(json!({"x": 1})),
15491                ),
15492            )
15493            .await
15494            .unwrap();
15495        assert_eq!(
15496            parse_error(&responses[0])["code"],
15497            "admission_facts_not_permitted"
15498        );
15499    }
15500
15501    #[tokio::test]
15502    async fn route_open_relays_consumer_capabilities_verbatim() {
15503        let registry = Arc::new(Registry::default());
15504        let forwarding = Arc::new(ForwardingTable::default());
15505        let handler =
15506            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15507        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15508        hello_via_sink(
15509            &handler,
15510            &module_ctx,
15511            &mut module_rx,
15512            hello_frame("aft", PROTOCOL_VERSION, 7),
15513        )
15514        .await;
15515
15516        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15517        let expected_for_request = expected.clone();
15518        let project_root = unique_project_root("consumer-capabilities-present");
15519        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15520        let route_handler = handler.clone();
15521        let route_task = tokio::spawn(async move {
15522            route_handler
15523                .handle_control_frame(
15524                    &client_ctx,
15525                    route_open_frame_with_consumer_capabilities(
15526                        401,
15527                        "aft",
15528                        project_root,
15529                        Some(expected_for_request),
15530                    ),
15531                )
15532                .await
15533                .unwrap()
15534        });
15535        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15536            .await
15537            .unwrap()
15538            .unwrap();
15539        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15540        let ModuleControlRequest::RouteBind {
15541            consumer_capabilities,
15542            ..
15543        } = bind
15544        else {
15545            panic!("expected route.bind request, got {bind:?}");
15546        };
15547        assert_eq!(consumer_capabilities, Some(expected.clone()));
15548
15549        handler
15550            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15551            .await
15552            .unwrap();
15553        let route_response = route_task.await.unwrap();
15554        assert!(route_response.is_empty());
15555        let published = client_rx.recv().await.unwrap();
15556        assert!(matches!(
15557            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15558            ClientControlResponse::RouteOpen { .. }
15559        ));
15560    }
15561
15562    #[tokio::test]
15563    async fn route_open_without_consumer_capabilities_relays_none() {
15564        let registry = Arc::new(Registry::default());
15565        let forwarding = Arc::new(ForwardingTable::default());
15566        let handler =
15567            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15568        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15569        hello_via_sink(
15570            &handler,
15571            &module_ctx,
15572            &mut module_rx,
15573            hello_frame("aft", PROTOCOL_VERSION, 7),
15574        )
15575        .await;
15576
15577        let project_root = unique_project_root("consumer-capabilities-absent");
15578        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15579        let route_handler = handler.clone();
15580        let route_task = tokio::spawn(async move {
15581            route_handler
15582                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15583                .await
15584                .unwrap()
15585        });
15586        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15587            .await
15588            .unwrap()
15589            .unwrap();
15590        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15591        let ModuleControlRequest::RouteBind {
15592            consumer_capabilities,
15593            ..
15594        } = bind
15595        else {
15596            panic!("expected route.bind request, got {bind:?}");
15597        };
15598        assert_eq!(consumer_capabilities, None);
15599
15600        handler
15601            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15602            .await
15603            .unwrap();
15604        let route_response = route_task.await.unwrap();
15605        assert!(route_response.is_empty());
15606        let published = client_rx.recv().await.unwrap();
15607        assert!(matches!(
15608            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15609            ClientControlResponse::RouteOpen { .. }
15610        ));
15611    }
15612
15613    /// Opens a route to a freshly registered `aft` with `sent` as the
15614    /// route.open's role_versions, acks the bind, and returns the role_versions
15615    /// the module's bind carried.
15616    async fn bind_role_versions_for(
15617        sent: Option<BTreeMap<String, String>>,
15618        connection: u64,
15619    ) -> Option<BTreeMap<String, String>> {
15620        let registry = Arc::new(Registry::default());
15621        let forwarding = Arc::new(ForwardingTable::default());
15622        let handler =
15623            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15624        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15625        hello_via_sink(
15626            &handler,
15627            &module_ctx,
15628            &mut module_rx,
15629            hello_frame("aft", PROTOCOL_VERSION, 7),
15630        )
15631        .await;
15632        let project_root = unique_project_root("role-versions");
15633        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15634        let route_handler = handler.clone();
15635        let route_task = tokio::spawn(async move {
15636            route_handler
15637                .handle_control_frame(
15638                    &client_ctx,
15639                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15640                )
15641                .await
15642                .unwrap()
15643        });
15644        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15645            .await
15646            .expect("a well-formed route.open reaches the module as a bind")
15647            .unwrap();
15648        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15649        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15650            panic!("expected route.bind request, got {bind:?}");
15651        };
15652        handler
15653            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15654            .await
15655            .unwrap();
15656        assert!(route_task.await.unwrap().is_empty());
15657        let published = client_rx.recv().await.unwrap();
15658        assert!(matches!(
15659            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15660            ClientControlResponse::RouteOpen { .. }
15661        ));
15662        role_versions
15663    }
15664
15665    #[tokio::test]
15666    async fn route_open_relays_role_versions_verbatim() {
15667        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15668        assert_eq!(
15669            bind_role_versions_for(Some(sent.clone()), 141).await,
15670            Some(sent)
15671        );
15672    }
15673
15674    /// An empty map declares nothing, so the provider sees no field rather
15675    /// than an empty object it would have to treat as a second "none".
15676    #[tokio::test]
15677    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15678        assert_eq!(bind_role_versions_for(None, 143).await, None);
15679        assert_eq!(
15680            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15681            None
15682        );
15683    }
15684
15685    #[tokio::test]
15686    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15687        let registry = Arc::new(Registry::default());
15688        let forwarding = Arc::new(ForwardingTable::default());
15689        let handler =
15690            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15691        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15692        hello_via_sink(
15693            &handler,
15694            &module_ctx,
15695            &mut module_rx,
15696            hello_frame("aft", PROTOCOL_VERSION, 7),
15697        )
15698        .await;
15699
15700        let nine: BTreeMap<String, String> = (0..9)
15701            .map(|index| (format!("role-{index}"), "v1".to_string()))
15702            .collect();
15703        for (label, malformed) in [
15704            (
15705                "invalid role name",
15706                role_versions(&[("Tool_Provider", "v1")]),
15707            ),
15708            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15709            ("nine entries", nine),
15710        ] {
15711            // A refused open answers at once; one that reached the module
15712            // would wait for its bind ack and trip this timeout.
15713            let responses = tokio::time::timeout(
15714                Duration::from_secs(1),
15715                handler.handle_control_frame(
15716                    &route_ctx(ConnectionId::new(148)).0,
15717                    route_open_frame_with_role_versions(
15718                        404,
15719                        "aft",
15720                        unique_project_root("role-versions-malformed"),
15721                        Some(malformed),
15722                    ),
15723                ),
15724            )
15725            .await
15726            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15727            .unwrap();
15728            assert_eq!(responses.len(), 1, "{label}");
15729            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15730            let error = parse_error(&responses[0]);
15731            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15732            assert_eq!(
15733                error["detail"]["field"], "role_versions",
15734                "{label}: {error}"
15735            );
15736            assert!(
15737                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15738                "{label}: a malformed declaration is terminal"
15739            );
15740            assert!(
15741                module_rx.try_recv().is_err(),
15742                "{label}: the module must never see a bind"
15743            );
15744        }
15745    }
15746
15747    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15748    /// consumer can tell this daemon forwards the field from one that would
15749    /// drop it.
15750    #[tokio::test]
15751    async fn route_role_versions_capability_is_advertised() {
15752        let handler = ControlHandler::new(Arc::new(Registry::default()));
15753        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15754        let ack = hello_via_sink(
15755            &handler,
15756            &ctx,
15757            &mut rx,
15758            hello_frame("m", PROTOCOL_VERSION, 1),
15759        )
15760        .await;
15761        let ack = parse_ack(&ack);
15762        assert!(
15763            ack.subc_capabilities
15764                .iter()
15765                .any(|c| c == "route-role-versions/v1"),
15766            "{:?}",
15767            ack.subc_capabilities
15768        );
15769
15770        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15771        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15772        let reply = handler
15773            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15774            .await
15775            .unwrap()
15776            .pop()
15777            .unwrap();
15778        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15779            serde_json::from_slice(&reply.body).unwrap()
15780        else {
15781            panic!("not a server.describe reply");
15782        };
15783        assert!(
15784            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15785            "{capabilities:?}"
15786        );
15787    }
15788
15789    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15790    /// catalog entry without `events` (the module declares none) from a daemon
15791    /// that never reports declared events.
15792    #[tokio::test]
15793    async fn catalog_events_capability_is_advertised() {
15794        let handler = ControlHandler::new(Arc::new(Registry::default()));
15795        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15796        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15797        let reply = handler
15798            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
15799            .await
15800            .unwrap()
15801            .pop()
15802            .unwrap();
15803        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15804            serde_json::from_slice(&reply.body).unwrap()
15805        else {
15806            panic!("not a server.describe reply");
15807        };
15808        assert!(
15809            capabilities
15810                .iter()
15811                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
15812            "{capabilities:?}"
15813        );
15814    }
15815
15816    #[tokio::test]
15817    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15818        let handler = ControlHandler::new(Arc::new(Registry::default()));
15819        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15820        let ack = hello_via_sink(
15821            &handler,
15822            &module,
15823            &mut module_rx,
15824            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15825        )
15826        .await;
15827        let ack = parse_ack(&ack);
15828        assert!(
15829            ack.subc_capabilities
15830                .iter()
15831                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15832            "{:?}",
15833            ack.subc_capabilities
15834        );
15835        assert!(ack
15836            .subc_capabilities
15837            .iter()
15838            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15839
15840        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15841        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15842        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15843        let reply = handler
15844            .handle_control_frame(&client, frame)
15845            .await
15846            .unwrap()
15847            .pop()
15848            .unwrap();
15849        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15850            serde_json::from_slice(&reply.body).unwrap()
15851        else {
15852            panic!("not a server.describe reply");
15853        };
15854        assert!(
15855            capabilities
15856                .iter()
15857                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15858            "{capabilities:?}"
15859        );
15860        assert!(capabilities
15861            .iter()
15862            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15863    }
15864
15865    #[tokio::test]
15866    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15867        let handler = ControlHandler::new(Arc::new(Registry::default()));
15868        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15869        let ack = hello_via_sink(
15870            &handler,
15871            &module,
15872            &mut rx,
15873            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15874        )
15875        .await;
15876        assert!(parse_ack(&ack)
15877            .subc_capabilities
15878            .iter()
15879            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15880        assert!(parse_ack(&ack)
15881            .subc_capabilities
15882            .iter()
15883            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15884        assert!(parse_ack(&ack)
15885            .subc_capabilities
15886            .iter()
15887            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15888        let (client, _rx) = route_ctx(ConnectionId::new(157));
15889        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15890        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15891        let reply = handler
15892            .handle_control_frame(&client, frame)
15893            .await
15894            .unwrap()
15895            .pop()
15896            .unwrap();
15897        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15898            serde_json::from_slice(&reply.body).unwrap()
15899        else {
15900            panic!("server.describe reply")
15901        };
15902        assert!(capabilities
15903            .iter()
15904            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15905        assert!(capabilities
15906            .iter()
15907            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15908        assert!(capabilities
15909            .iter()
15910            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15911    }
15912
15913    #[tokio::test]
15914    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15915        let handler = ControlHandler::new(Arc::new(Registry::default()));
15916        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15917        let ack = hello_via_sink(
15918            &handler,
15919            &module,
15920            &mut rx,
15921            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15922        )
15923        .await;
15924        assert!(parse_ack(&ack)
15925            .subc_capabilities
15926            .iter()
15927            .any(|cap| cap == "scope-workdir/v1"));
15928        let (client, _rx) = route_ctx(ConnectionId::new(159));
15929        let frame = Frame::build(
15930            FrameType::Request,
15931            control_flags(),
15932            0,
15933            0,
15934            5,
15935            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15936        )
15937        .unwrap();
15938        let reply = handler
15939            .handle_control_frame(&client, frame)
15940            .await
15941            .unwrap()
15942            .remove(0);
15943        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15944            serde_json::from_slice(&reply.body).unwrap()
15945        else {
15946            panic!("server.describe reply")
15947        };
15948        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15949    }
15950
15951    #[tokio::test]
15952    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15953        let handler = ControlHandler::new(Arc::new(Registry::default()));
15954        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15955        let ack = hello_via_sink(
15956            &handler,
15957            &module,
15958            &mut rx,
15959            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15960        )
15961        .await;
15962        assert!(parse_ack(&ack)
15963            .subc_capabilities
15964            .iter()
15965            .any(|cap| cap == "worker-runs/v1"));
15966        let (client, _rx) = route_ctx(ConnectionId::new(161));
15967        let frame = Frame::build(
15968            FrameType::Request,
15969            control_flags(),
15970            0,
15971            0,
15972            5,
15973            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15974        )
15975        .unwrap();
15976        let reply = handler
15977            .handle_control_frame(&client, frame)
15978            .await
15979            .unwrap()
15980            .remove(0);
15981        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15982            serde_json::from_slice(&reply.body).unwrap()
15983        else {
15984            panic!("server.describe reply")
15985        };
15986        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
15987    }
15988
15989    #[tokio::test]
15990    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
15991        let handler = ControlHandler::new(Arc::new(Registry::default()));
15992        let (module, mut rx) = route_ctx(ConnectionId::new(154));
15993        let ack = hello_via_sink(
15994            &handler,
15995            &module,
15996            &mut rx,
15997            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
15998        )
15999        .await;
16000        assert!(parse_ack(&ack)
16001            .subc_capabilities
16002            .iter()
16003            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16004        let (client, _rx) = route_ctx(ConnectionId::new(155));
16005        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16006        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16007        let reply = handler
16008            .handle_control_frame(&client, frame)
16009            .await
16010            .unwrap()
16011            .pop()
16012            .unwrap();
16013        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16014            serde_json::from_slice(&reply.body).unwrap()
16015        else {
16016            panic!("not a server.describe reply")
16017        };
16018        assert!(capabilities
16019            .iter()
16020            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16021    }
16022
16023    #[tokio::test]
16024    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
16025        let registry = Arc::new(Registry::default());
16026        let forwarding = Arc::new(ForwardingTable::default());
16027        let handler =
16028            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
16029                .with_health_probe_timeout(Duration::from_secs(5));
16030        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
16031        hello_via_sink(
16032            &handler,
16033            &module_ctx,
16034            &mut module_rx,
16035            non_routable_hello_frame_with_control_ops(
16036                "mcp",
16037                300,
16038                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
16039            ),
16040        )
16041        .await;
16042        assert!(registry
16043            .get_module("mcp")
16044            .unwrap()
16045            .unwrap()
16046            .manifest
16047            .provides
16048            .is_empty());
16049
16050        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
16051        let route_response = handler
16052            .handle_control_frame(
16053                &route_client_ctx,
16054                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
16055            )
16056            .await
16057            .unwrap();
16058        assert_eq!(route_response[0].header.ty, FrameType::Error);
16059        assert_eq!(
16060            parse_error(&route_response[0])["code"],
16061            "target_unavailable"
16062        );
16063        assert!(parse_error(&route_response[0])["message"]
16064            .as_str()
16065            .unwrap()
16066            .contains("does not provide the requested target"));
16067        assert!(module_rx.try_recv().is_err());
16068
16069        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16070        let health_handler = handler.clone();
16071        let health_task = tokio::spawn(async move {
16072            health_handler
16073                .handle_control_frame(
16074                    &health_client_ctx,
16075                    supervisor_health_probe_frame(302, "mcp"),
16076                )
16077                .await
16078                .unwrap()
16079        });
16080        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16081            .await
16082            .unwrap()
16083            .unwrap();
16084        assert_eq!(
16085            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16086            ModuleControlRequest::HealthCheck {}
16087        );
16088        handler
16089            .handle_control_frame(
16090                &module_ctx,
16091                health_response(health_frame.header.corr, HealthStatus::Ok),
16092            )
16093            .await
16094            .unwrap();
16095        let health_response = health_task.await.unwrap();
16096        assert_eq!(health_response[0].header.ty, FrameType::Response);
16097        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16098            ClientControlResponse::SupervisorHealthProbe {
16099                module_id, status, ..
16100            } => {
16101                assert_eq!(module_id, "mcp");
16102                assert_eq!(status, HealthStatus::Ok);
16103            }
16104            other => panic!("unexpected health response: {other:?}"),
16105        }
16106
16107        // Exercise the forwarding cleanup path directly while leaving the registry
16108        // advertisement in place. If cleanup leaves a stale control sink behind,
16109        // the next probe will enqueue onto it and wait for the long probe timeout
16110        // instead of returning an immediate no-connection error.
16111        forwarding
16112            .cleanup_connection(module_ctx.connection_id)
16113            .unwrap();
16114        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16115        let cleanup_response = tokio::time::timeout(
16116            Duration::from_millis(200),
16117            handler.handle_control_frame(
16118                &cleanup_probe_ctx,
16119                supervisor_health_probe_frame(303, "mcp"),
16120            ),
16121        )
16122        .await
16123        .expect("probe should fail immediately when the control lane is gone")
16124        .unwrap();
16125        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16126        assert_eq!(
16127            parse_error(&cleanup_response[0])["code"],
16128            "target_unavailable"
16129        );
16130        assert!(parse_error(&cleanup_response[0])["message"]
16131            .as_str()
16132            .unwrap()
16133            .contains("no module connection"));
16134
16135        handler
16136            .cleanup_connection(module_ctx.connection_id)
16137            .unwrap();
16138    }
16139
16140    #[tokio::test]
16141    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16142        let registry = Arc::new(Registry::default());
16143        let supervisor_handle = SupervisorHandle::new();
16144        let supervisor =
16145            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16146                .with_handle(supervisor_handle.clone())
16147                .with_connection_file_path(
16148                    std::env::temp_dir()
16149                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16150                );
16151        let module = supervisor
16152            .supervise_configured(
16153                ModuleSpec {
16154                    script: None,
16155                    carry_containment: false,
16156                    module_id: "warming".to_string(),
16157                    program: fake_aft_stub_path(),
16158                    args: Vec::new(),
16159                    env: Vec::new(),
16160                    reserved: false,
16161                    reserved_prefixes: Vec::new(),
16162                    protocol: ModuleProtocol::Subc,
16163                    overlap: Default::default(),
16164                },
16165                true,
16166            )
16167            .unwrap();
16168        assert_eq!(module.state().unwrap(), ModuleState::Running);
16169
16170        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16171        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16172        let response = handler
16173            .handle_control_frame(
16174                &ctx,
16175                route_open_frame(304, "warming", unique_project_root("warming")),
16176            )
16177            .await
16178            .unwrap();
16179        module.stop().await.unwrap();
16180
16181        assert_eq!(response[0].header.ty, FrameType::Error);
16182        let error = parse_error(&response[0]);
16183        assert_eq!(error["code"], "module_warming");
16184        assert!(error["message"]
16185            .as_str()
16186            .unwrap()
16187            .contains("state=running, enabled=true, live=false"));
16188    }
16189
16190    #[test]
16191    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16192        let handler = ControlHandler::new(Arc::new(Registry::default()));
16193        let capture = EventCapture::default();
16194        let _subscriber =
16195            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16196        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16197        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16198        let pending = (0..limit).collect::<Vec<_>>();
16199        let response = handler
16200            .route_open_capacity_refusal(
16201                &ctx,
16202                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16203                "busy",
16204                pending.len(),
16205                limit,
16206            )
16207            .unwrap();
16208        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16209        let event = capture
16210            .events()
16211            .into_iter()
16212            .find(|event| {
16213                event.target == "control"
16214                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16215            })
16216            .expect("connection admission refusal event");
16217        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16218        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16219        // Refused before `handle_route_open` parses the request, so the caller
16220        // fields are read from the frame itself.
16221        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16222        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16223    }
16224
16225    #[test]
16226    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16227        let handler = ControlHandler::new(Arc::new(Registry::default()));
16228        let capture = EventCapture::default();
16229        let _subscriber =
16230            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16231        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16232        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16233        let guards = (0..limit)
16234            .map(|_| {
16235                handler
16236                    .route_bind_concurrency
16237                    .try_admit("busy", limit)
16238                    .unwrap()
16239            })
16240            .collect::<Vec<_>>();
16241        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16242            Err(in_flight) => in_flight,
16243            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16244        };
16245        let response = handler
16246            .route_open_target_capacity_refusal(
16247                &ctx,
16248                &RouteOpenCaller::unknown(),
16249                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16250                "busy",
16251                in_flight,
16252            )
16253            .unwrap();
16254        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16255        let event = capture
16256            .events()
16257            .into_iter()
16258            .find(|event| {
16259                event.target == "control"
16260                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16261            })
16262            .expect("target admission refusal event");
16263        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16264        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16265        drop(guards);
16266    }
16267
16268    #[cfg(unix)]
16269    #[tokio::test(start_paused = true)]
16270    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16271        let registry = Arc::new(Registry::default());
16272        let handle = SupervisorHandle::new();
16273        let supervisor =
16274            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16275                .with_handle(handle.clone());
16276        let module = supervisor
16277            .spawn(crate::ModuleSpec {
16278                script: None,
16279                carry_containment: false,
16280                module_id: "retry-list".into(),
16281                program: PathBuf::from("/bin/sh"),
16282                args: vec!["-c".into(), "exit 17".into()],
16283                env: vec![],
16284                reserved: false,
16285                reserved_prefixes: vec![],
16286                protocol: ModuleProtocol::None,
16287                overlap: Default::default(),
16288            })
16289            .unwrap();
16290        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16291        while module.state().unwrap() != crate::ModuleState::Failed {
16292            assert!(
16293                std::time::Instant::now() < deadline,
16294                "waiting for budget failure"
16295            );
16296            tokio::task::yield_now().await;
16297        }
16298        let handler = ControlHandler::new(registry).with_supervisor(handle);
16299        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16300        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16301        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16302        assert_eq!(body["modules"][0]["state"], "failed");
16303        let retry = body["modules"][0]["next_retry_at_ms"]
16304            .as_u64()
16305            .expect("scheduled retry on the wire");
16306        let now = std::time::SystemTime::now()
16307            .duration_since(std::time::UNIX_EPOCH)
16308            .unwrap()
16309            .as_millis() as u64;
16310        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16311        module.set_enabled(false).await.unwrap();
16312        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16313        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16314        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16315        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16316    }
16317
16318    #[tokio::test]
16319    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16320        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16321        let supervisor =
16322            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16323        let module = supervisor
16324            .spawn(crate::ModuleSpec {
16325                script: None,
16326                carry_containment: false,
16327                module_id: "pid-read-budget".into(),
16328                program: std::env::current_exe().unwrap(),
16329                args: vec![
16330                    "--exact".into(),
16331                    "control::tests::pid_resource_read_fixture".into(),
16332                ],
16333                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16334                    .into_iter()
16335                    .map(|key| (key.into(), dir.display().to_string()))
16336                    .chain(std::iter::once((
16337                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16338                        "1".into(),
16339                    )))
16340                    .collect(),
16341                reserved: false,
16342                reserved_prefixes: Vec::new(),
16343                protocol: ModuleProtocol::None,
16344                overlap: Default::default(),
16345            })
16346            .unwrap();
16347        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16348        while !matches!(
16349            module.child_resource_usage(),
16350            subc_control::ChildResourceUsage::Measured(_)
16351        ) {
16352            assert!(
16353                tokio::time::Instant::now() < ready_deadline,
16354                "fixture process was not measurable"
16355            );
16356            tokio::time::sleep(Duration::from_millis(10)).await;
16357        }
16358        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16359        let reading = {
16360            let _guard = crate::subtree_resources::fault_read_guard().await;
16361            crate::subtree_resources::read_process(module.clone()).await
16362        };
16363        stop_resource_fixture(&module, &dir).await;
16364        assert!(
16365            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16366            "{reading:?}"
16367        );
16368    }
16369
16370    #[test]
16371    fn pid_resource_read_fixture() {
16372        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16373            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16374            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16375            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16376                std::thread::sleep(Duration::from_millis(5));
16377            }
16378            std::fs::write(dir.join("module-stopped"), "").unwrap();
16379        }
16380    }
16381
16382    async fn stop_resource_fixture(
16383        module: &crate::supervise::SupervisedModule,
16384        dir: &std::path::Path,
16385    ) {
16386        let stopping = module.stop();
16387        tokio::pin!(stopping);
16388        tokio::select! {
16389            result = &mut stopping => result.unwrap(),
16390            () = async {
16391                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16392                    tokio::time::sleep(Duration::from_millis(5)).await;
16393                }
16394                std::fs::write(dir.join("stop-module"), "").unwrap();
16395            } => stopping.await.unwrap(),
16396        }
16397        #[cfg(windows)]
16398        assert!(
16399            dir.join("module-stopped").exists(),
16400            "the resource fixture must exit cooperatively, not wait for the drain kill"
16401        );
16402        assert_eq!(
16403            module.state().unwrap(),
16404            crate::supervise::ModuleState::Stopped
16405        );
16406    }
16407
16408    #[tokio::test]
16409    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16410        let registry = Arc::new(Registry::default());
16411        let handle = SupervisorHandle::new();
16412        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16413            .with_handle(handle.clone());
16414        supervisor
16415            .supervise_configured(
16416                crate::ModuleSpec {
16417                    script: None,
16418                    module_id: "disabled-resource-reading".into(),
16419                    program: std::env::current_exe().unwrap(),
16420                    args: Vec::new(),
16421                    env: Vec::new(),
16422                    reserved: false,
16423                    reserved_prefixes: Vec::new(),
16424                    protocol: ModuleProtocol::None,
16425                    overlap: Default::default(),
16426                    carry_containment: false,
16427                },
16428                false,
16429            )
16430            .unwrap();
16431        let handler = ControlHandler::new(registry).with_supervisor(handle);
16432        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16433        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16434        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16435        assert!(body["modules"][0].get("tree").is_none());
16436        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16437    }
16438
16439    #[tokio::test]
16440    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16441        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16442        let registry = Arc::new(Registry::default());
16443        let handle = SupervisorHandle::new();
16444        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16445            .with_handle(handle.clone());
16446        let module = supervisor
16447            .spawn(crate::ModuleSpec {
16448                script: None,
16449                carry_containment: false,
16450                module_id: "list-process-priority".into(),
16451                program: std::env::current_exe().unwrap(),
16452                args: vec![
16453                    "--exact".into(),
16454                    "control::tests::pid_resource_read_fixture".into(),
16455                ],
16456                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16457                    .into_iter()
16458                    .map(|key| (key.into(), dir.display().to_string()))
16459                    .chain(std::iter::once((
16460                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16461                        "1".into(),
16462                    )))
16463                    .collect(),
16464                reserved: false,
16465                reserved_prefixes: Vec::new(),
16466                protocol: ModuleProtocol::None,
16467                overlap: Default::default(),
16468            })
16469            .unwrap();
16470        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16471        loop {
16472            let image = module.running_image_agreement().await;
16473            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16474                break;
16475            }
16476            assert!(
16477                tokio::time::Instant::now() < ready_deadline,
16478                "the fixture process never became observable: {image:?}"
16479            );
16480            tokio::time::sleep(Duration::from_millis(10)).await;
16481        }
16482        let guard = crate::subtree_resources::fault_read_guard().await;
16483        let (target, release, _) = crate::subtree_resources::held();
16484        module.set_subtree_target_for_test(target);
16485        let handler = ControlHandler::new(registry).with_supervisor(handle);
16486        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16487        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16488        drop(release);
16489        drop(guard);
16490        stop_resource_fixture(&module, &dir).await;
16491        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16492        assert_eq!(
16493            body["modules"][0]["resources"]["status"], "measured",
16494            "the optional tree timeout must not discard the process reading: {body}"
16495        );
16496        assert!(body["modules"][0].get("tree").is_none());
16497        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16498        assert_eq!(
16499            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16500            "the tree timeout must not hide a completed image observation"
16501        );
16502    }
16503
16504    #[cfg(any(target_os = "linux", target_os = "macos"))]
16505    #[tokio::test]
16506    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16507        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16508            .with_daemon_provenance(
16509                std::process::id(),
16510                0,
16511                Some(std::env::current_exe().unwrap()),
16512                None,
16513                None,
16514            );
16515        let (probe, release, began) = ExecutableIdentityProbe::held();
16516        handler.daemon_provenance.probe = probe;
16517        let observe = |handler: ControlHandler, corr| {
16518            tokio::spawn(async move {
16519                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16520                let frame =
16521                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16522                        .unwrap();
16523                handler
16524                    .handle_supervisor_provenance(&ctx, frame, None)
16525                    .await
16526                    .unwrap()
16527            })
16528        };
16529        let explicit = observe(handler.clone(), 114);
16530        began.await.unwrap();
16531        let concurrent = observe(handler.clone(), 115);
16532        // Keep explicit provenance waiting on its first image observation beyond
16533        // the list deadline; release it only after the concurrent list replies.
16534        tokio::time::sleep(Duration::from_millis(300)).await;
16535        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16536        let list = tokio::time::timeout(
16537            Duration::from_secs(1),
16538            handler.handle_supervisor_list(frame),
16539        )
16540        .await;
16541        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16542        drop(release);
16543        let replies = explicit.await.unwrap();
16544        let concurrent_replies = concurrent.await.unwrap();
16545        assert!(
16546            explicit_was_pending,
16547            "explicit provenance must await the full observation"
16548        );
16549        let list = list
16550            .expect("a concurrent explicit probe must not stall list")
16551            .unwrap();
16552        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16553        assert_eq!(list_body["op"], "supervisor.list");
16554        for replies in [replies, concurrent_replies] {
16555            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16556            assert_eq!(
16557                body["daemon"]["daemon_observed"]["running_image"]["status"],
16558                "match"
16559            );
16560        }
16561    }
16562
16563    #[tokio::test]
16564    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16565        let registry = Arc::new(Registry::default());
16566        let handle = SupervisorHandle::new();
16567        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16568            .with_handle(handle.clone());
16569        let module = supervisor
16570            .supervise_configured(
16571                crate::ModuleSpec {
16572                    script: None,
16573                    carry_containment: false,
16574                    module_id: "memory-read".into(),
16575                    program: PathBuf::from("disabled-module"),
16576                    args: Vec::new(),
16577                    env: Vec::new(),
16578                    reserved: false,
16579                    reserved_prefixes: Vec::new(),
16580                    protocol: ModuleProtocol::Subc,
16581                    overlap: Default::default(),
16582                },
16583                true,
16584            )
16585            .unwrap();
16586        let _guard = crate::subtree_resources::fault_read_guard().await;
16587        let (target, release, began) = crate::subtree_resources::held();
16588        // Optional list work may be skipped when its deadline is already spent.
16589        // Establish the stalled fixture before asking the list to observe it.
16590        let stalled_target = target.clone();
16591        let stalled = tokio::task::spawn_blocking(move || {
16592            stalled_target.tree(&subc_os::ProcessTable::default())
16593        });
16594        began.await.unwrap();
16595        module.set_subtree_target_for_test(target);
16596        let handler = ControlHandler::new(registry).with_supervisor(handle);
16597        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16598        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16599        let replies = handler
16600            .handle_client_control_request(
16601                &ctx,
16602                frame,
16603                ClientControlRequest::SupervisorList {},
16604                &mut None,
16605            )
16606            .await
16607            .unwrap();
16608        assert!(
16609            replies.is_empty(),
16610            "list reply must be detached from the connection reader"
16611        );
16612        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16613        let replies = handler
16614            .handle_client_control_request(
16615                &ctx,
16616                frame,
16617                ClientControlRequest::SupervisorSpawnSnapshot {},
16618                &mut None,
16619            )
16620            .await
16621            .unwrap();
16622        assert_eq!(
16623            replies.len(),
16624            1,
16625            "another request must complete while the subtree read stalls"
16626        );
16627        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16628            .await
16629            .unwrap()
16630            .unwrap();
16631        release.send(()).unwrap();
16632        drop(release);
16633        stalled.await.unwrap();
16634        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16635        assert!(
16636            body["modules"][0].get("tree").is_none(),
16637            "an unknown tree reading must be omitted after the bounded read expires"
16638        );
16639        // Lists export completed work rather than measuring synchronously.
16640        // Complete a refresh after the fixture is released before asserting
16641        // that a later list contains its measured tree.
16642        handler
16643            .resource_tracker
16644            .read(handler.supervisor.list(), false, "released_tree_fixture")
16645            .await;
16646        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16647        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16648        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16649        assert_eq!(
16650            body["modules"][0]["tree"]["source"], "process_tree",
16651            "the next request must export the completed refresh"
16652        );
16653        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16654    }
16655
16656    #[tokio::test]
16657    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16658        use subc_control::{
16659            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16660            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16661            TreeReading, TreeSource,
16662        };
16663        let registry = Arc::new(Registry::default());
16664        let handle = SupervisorHandle::new();
16665        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16666            .with_handle(handle.clone());
16667        supervisor
16668            .supervise_configured(
16669                crate::ModuleSpec {
16670                    script: None,
16671                    carry_containment: false,
16672                    module_id: "budget-worker".into(),
16673                    program: PathBuf::from("disabled-module"),
16674                    args: Vec::new(),
16675                    env: Vec::new(),
16676                    reserved: false,
16677                    reserved_prefixes: Vec::new(),
16678                    protocol: ModuleProtocol::Subc,
16679                    overlap: Default::default(),
16680                },
16681                true,
16682            )
16683            .unwrap();
16684        let handler = ControlHandler::new(registry).with_supervisor(handle);
16685        let now = u64::try_from(
16686            std::time::SystemTime::now()
16687                .duration_since(std::time::UNIX_EPOCH)
16688                .unwrap()
16689                .as_millis(),
16690        )
16691        .unwrap();
16692        let measured = now - 1_000;
16693        let hour = CpuLastHour::new(100, 60_000);
16694        let daemon = DaemonResources::new(7, 1, "test")
16695            .with_measured_at_ms(Some(measured))
16696            .with_resources(Some(ChildResourceUsage::Measured(
16697                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16698            )))
16699            .with_cpu_last_hour(Some(hour.clone()));
16700        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16701            .with_measured_at_ms(Some(measured))
16702            .with_cpu_last_hour(Some(hour.clone()));
16703        let tree = TreeReading::new(
16704            150,
16705            50,
16706            ChildMemoryKind::ResidentSet,
16707            1,
16708            TreeSource::ProcessTree,
16709        )
16710        .with_measured_at_ms(Some(measured));
16711        handler.resource_tracker.seed_committed_for_test(
16712            &handler.supervisor.list(),
16713            crate::resource_totals::Readings {
16714                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16715                daemon: Some(daemon),
16716                agent_commands: Some(vec![agents]),
16717                ..Default::default()
16718            },
16719            now,
16720        );
16721        list_diagnostics::scope(async {
16722            tokio::time::sleep(Duration::from_millis(110)).await;
16723            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16724            let request =
16725                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16726            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16727            let ClientControlResponse::SupervisorList {
16728                modules,
16729                daemon,
16730                agent_commands,
16731                ..
16732            } = serde_json::from_slice(&replies[0].body).unwrap()
16733            else {
16734                panic!("expected a list response")
16735            };
16736            assert!(matches!(
16737                modules[0].resources,
16738                Some(ChildResourceUsage::Unavailable {
16739                    reason: ChildResourceUnavailableReason::Unreadable
16740                })
16741            ));
16742            assert_eq!(
16743                (
16744                    modules[0].tree.as_ref().unwrap().cpu_ms,
16745                    modules[0].tree.as_ref().unwrap().measured_at_ms
16746                ),
16747                (150, Some(measured))
16748            );
16749            let daemon = daemon.unwrap();
16750            let agents = agent_commands.unwrap();
16751            assert_eq!(daemon.measured_at_ms, Some(measured));
16752            assert_eq!(
16753                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16754                (1, 50, Some(measured))
16755            );
16756            for hour in [
16757                modules[0].cpu_last_hour.as_ref(),
16758                daemon.cpu_last_hour.as_ref(),
16759                agents[0].cpu_last_hour.as_ref(),
16760            ] {
16761                let hour = hour.unwrap();
16762                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16763            }
16764        })
16765        .await;
16766    }
16767
16768    #[tokio::test]
16769    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16770        let registry = Arc::new(Registry::default());
16771        let handle = SupervisorHandle::new();
16772        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16773            .with_handle(handle.clone());
16774        supervisor
16775            .supervise_configured(
16776                crate::ModuleSpec {
16777                    script: None,
16778                    carry_containment: false,
16779                    module_id: "drift".into(),
16780                    program: PathBuf::from("disabled-module"),
16781                    args: Vec::new(),
16782                    env: Vec::new(),
16783                    reserved: false,
16784                    reserved_prefixes: Vec::new(),
16785                    protocol: ModuleProtocol::Subc,
16786                    overlap: Default::default(),
16787                },
16788                false,
16789            )
16790            .unwrap();
16791        let handler = ControlHandler::new(registry).with_supervisor(handle);
16792        for configured in [None, Some(false), Some(true)] {
16793            handler.capability_evaluator.configure(
16794                configured.map(|enabled| ("drift".to_string(), enabled)),
16795                BTreeMap::new(),
16796            );
16797            let frame =
16798                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16799            let replies = handler
16800                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16801                .await
16802                .unwrap();
16803            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16804            assert!(body.get("configured_enabled").is_none());
16805            assert_eq!(body["op"], "supervisor.ack");
16806            let frame =
16807                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16808            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16809            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16810            assert_eq!(
16811                body["modules"][0].get("configured_enabled"),
16812                configured.map(Value::Bool).as_ref()
16813            );
16814            assert!(body["modules"][0].get("tree").is_none());
16815            assert!(body["modules"][0].get("subtree").is_none());
16816        }
16817    }
16818
16819    #[tokio::test(flavor = "current_thread")]
16820    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16821        let handler = ControlHandler::new(Arc::new(Registry::default()));
16822        let capture = EventCapture::default();
16823        let _subscriber =
16824            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16825        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16826        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16827
16828        let _ = handler
16829            .handle_client_control_request(
16830                &ctx,
16831                frame,
16832                ClientControlRequest::SupervisorSetEnabled {
16833                    module_id: "broca".to_string(),
16834                    enabled: false,
16835                },
16836                &mut None,
16837            )
16838            .await
16839            .unwrap();
16840
16841        let events = capture
16842            .events()
16843            .into_iter()
16844            .filter(|event| {
16845                event.target == "control"
16846                    && event.fields.get("message").map(String::as_str)
16847                        == Some("supervisor request received")
16848            })
16849            .collect::<Vec<_>>();
16850        assert_eq!(events.len(), 1, "one supervisor request log line");
16851        let event = &events[0];
16852        assert_eq!(event.level, tracing::Level::INFO);
16853        assert_eq!(
16854            event.fields.get("op"),
16855            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16856        );
16857        assert_eq!(
16858            event.fields.get("module_id"),
16859            Some(&"\"broca\"".to_string())
16860        );
16861        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16862        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16863        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16864    }
16865
16866    #[tokio::test(flavor = "current_thread")]
16867    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16868        let registry = Arc::new(Registry::default());
16869        let module_connection = ConnectionId::new(303);
16870        registry
16871            .register_with_control_ops(
16872                manifest("aft", PROTOCOL_VERSION),
16873                PROTOCOL_VERSION,
16874                module_connection,
16875                module_baseline_control_ops(),
16876            )
16877            .unwrap();
16878        let handler = ControlHandler::new(registry);
16879        let capture = EventCapture::default();
16880        let _subscriber =
16881            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16882        let (ctx, _rx) = route_ctx(module_connection);
16883        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16884
16885        let _ = handler
16886            .handle_client_control_request(
16887                &ctx,
16888                frame,
16889                ClientControlRequest::SupervisorSetEnabled {
16890                    module_id: "broca".to_string(),
16891                    enabled: false,
16892                },
16893                &mut None,
16894            )
16895            .await
16896            .unwrap();
16897
16898        let callers = capture
16899            .events()
16900            .into_iter()
16901            .filter(|event| {
16902                event.fields.get("message").map(String::as_str)
16903                    == Some("supervisor request received")
16904            })
16905            .map(|event| event.fields.get("caller").cloned())
16906            .collect::<Vec<_>>();
16907        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16908    }
16909
16910    #[tokio::test(flavor = "current_thread")]
16911    async fn supervisor_list_does_not_log_request_received() {
16912        let handler = ControlHandler::new(Arc::new(Registry::default()));
16913        let capture = EventCapture::default();
16914        let _subscriber =
16915            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16916        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16917        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16918
16919        handler
16920            .handle_client_control_request(
16921                &ctx,
16922                frame,
16923                ClientControlRequest::SupervisorList {},
16924                &mut None,
16925            )
16926            .await
16927            .unwrap();
16928
16929        assert!(capture.events().into_iter().all(|event| {
16930            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16931        }));
16932    }
16933
16934    #[tokio::test(flavor = "current_thread")]
16935    async fn supervisor_rescan_preview_does_not_log_request_received() {
16936        let handler = ControlHandler::new(Arc::new(Registry::default()));
16937        let capture = EventCapture::default();
16938        let _subscriber =
16939            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16940        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16941        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16942
16943        handler
16944            .handle_client_control_request(
16945                &ctx,
16946                frame,
16947                ClientControlRequest::SupervisorRescan { preview: true },
16948                &mut None,
16949            )
16950            .await
16951            .unwrap();
16952
16953        assert!(capture.events().into_iter().all(|event| {
16954            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16955        }));
16956    }
16957
16958    struct ApproveOperator;
16959    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16960        fn prompt(
16961            &self,
16962            _: &str,
16963            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16964        ) -> crate::operator_confirm::ProviderResult {
16965            crate::operator_confirm::ProviderResult::Approved
16966        }
16967    }
16968
16969    #[tokio::test]
16970    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
16971        assert_eq!(
16972            ControlHandler::default().privileged_operator_prompt,
16973            PrivilegedOperatorPrompt::Log
16974        );
16975        for (initial, changed, running) in [
16976            ("log", "enforce", PrivilegedOperatorPrompt::Log),
16977            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
16978        ] {
16979            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
16980            let path = dir.join("subc.jsonc");
16981            std::fs::write(
16982                &path,
16983                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
16984            )
16985            .unwrap();
16986            let config = crate::daemon_config::load(&path).unwrap().unwrap();
16987            let registry = Arc::new(Registry::default());
16988            let handle = SupervisorHandle::new();
16989            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
16990                .with_handle(handle.clone());
16991            let handler = ControlHandler::new(registry)
16992                .with_supervisor(handle)
16993                .with_privileged_operator_prompt(config.privileged_operator_prompt)
16994                .with_supervisor_rescan(supervisor, &path, config.port);
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(104));
17000
17001            for (disk_mode, needs_restart) in [
17002                (Some(initial), false),
17003                (Some(changed), true),
17004                (Some(changed), true),
17005                (None, running == PrivilegedOperatorPrompt::Enforce),
17006                (Some(initial), false),
17007            ] {
17008                let mut doc = json!({"version":1});
17009                if let Some(mode) = disk_mode {
17010                    doc["privileged_operator_prompt"] = json!(mode);
17011                }
17012                std::fs::write(&path, doc.to_string()).unwrap();
17013                for preview in [true, false] {
17014                    let request = ClientControlRequest::SupervisorRescan { preview };
17015                    let frame = Frame::build(
17016                        FrameType::Request,
17017                        control_flags(),
17018                        0,
17019                        0,
17020                        1,
17021                        serde_json::to_vec(&request).unwrap(),
17022                    )
17023                    .unwrap();
17024                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17025                    assert_eq!(frames.len(), 1);
17026                    let ClientControlResponse::SupervisorRescan { result } =
17027                        serde_json::from_slice(&frames[0].body).unwrap()
17028                    else {
17029                        panic!("expected a rescan response");
17030                    };
17031                    let expected = if needs_restart {
17032                        vec!["privileged_operator_prompt"]
17033                    } else {
17034                        Vec::new()
17035                    };
17036                    assert_eq!(result.restart_required, expected);
17037                    assert_eq!(handler.privileged_operator_prompt, running);
17038                    assert_eq!(
17039                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
17040                        running
17041                    );
17042                }
17043            }
17044        }
17045    }
17046
17047    #[tokio::test]
17048    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
17049        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
17050        let path = dir.join("subc.jsonc");
17051        let registry = Arc::new(Registry::default());
17052        let handle = SupervisorHandle::new();
17053        let supervisor =
17054            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
17055        let handler = ControlHandler::new(registry)
17056            .with_supervisor(handle)
17057            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
17058            .with_supervisor_rescan(supervisor, &path, None);
17059        handler.forwarding.operator_confirms().configure(
17060            Arc::new(ApproveOperator),
17061            crate::operator_confirm::OperatorLimits::default(),
17062        );
17063        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17064        for preview in [true, false] {
17065            std::fs::write(
17066                &path,
17067                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17068            )
17069            .unwrap();
17070            let request = ClientControlRequest::SupervisorRescan { preview };
17071            let frame = Frame::build(
17072                FrameType::Request,
17073                control_flags(),
17074                0,
17075                0,
17076                1,
17077                serde_json::to_vec(&request).unwrap(),
17078            )
17079            .unwrap();
17080            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17081            assert_eq!(frames.len(), 1);
17082            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17083            assert_eq!(
17084                handler.privileged_operator_prompt,
17085                PrivilegedOperatorPrompt::Enforce
17086            );
17087        }
17088    }
17089
17090    /// One wire code has several senders, so the refusal line names the check
17091    /// that refused. This drives the shared refusal path for ordinary refusals
17092    /// with an unregistered
17093    /// target and requires the branch label on the event.
17094    #[tokio::test]
17095    async fn route_open_refusal_names_the_check_that_refused() {
17096        let handler = ControlHandler::new(Arc::new(Registry::default()));
17097        let capture = EventCapture::default();
17098        let _subscriber =
17099            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17100        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17101        let response = handler
17102            .handle_control_frame(
17103                &ctx,
17104                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17105            )
17106            .await
17107            .unwrap();
17108
17109        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17110        let event = capture
17111            .events()
17112            .into_iter()
17113            .find(|event| {
17114                event.target == "control"
17115                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17116            })
17117            .expect("route.open refusal event");
17118        assert_eq!(
17119            event.fields.get("reason"),
17120            Some(&"\"not_registered\"".to_string())
17121        );
17122    }
17123
17124    #[tokio::test]
17125    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17126        let registry = Arc::new(Registry::default());
17127        let supervisor_handle = SupervisorHandle::new();
17128        let supervisor =
17129            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17130                .with_handle(supervisor_handle.clone())
17131                .with_connection_file_path(std::env::temp_dir().join(format!(
17132                    "subc-route-open-refusal-info-{}",
17133                    std::process::id()
17134                )));
17135        let module = supervisor
17136            .supervise_configured(
17137                ModuleSpec {
17138                    script: None,
17139                    carry_containment: false,
17140                    module_id: "warming".to_string(),
17141                    program: fake_aft_stub_path(),
17142                    args: Vec::new(),
17143                    env: Vec::new(),
17144                    reserved: false,
17145                    reserved_prefixes: Vec::new(),
17146                    protocol: ModuleProtocol::Subc,
17147                    overlap: Default::default(),
17148                },
17149                true,
17150            )
17151            .unwrap();
17152        assert_eq!(module.state().unwrap(), ModuleState::Running);
17153
17154        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17155        assert!(handler
17156            .counters()
17157            .snapshot()
17158            .get("route_open_refused_by_code")
17159            .is_none());
17160        let capture = EventCapture::default();
17161        let _subscriber =
17162            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17163        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17164        let response = handler
17165            .handle_control_frame(
17166                &ctx,
17167                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17168            )
17169            .await
17170            .unwrap();
17171        module.stop().await.unwrap();
17172
17173        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17174        let event = capture
17175            .events()
17176            .into_iter()
17177            .find(|event| {
17178                event.target == "control"
17179                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17180            })
17181            .expect("route.open refusal event");
17182        assert_eq!(
17183            event.fields.get("module_id"),
17184            Some(&"\"warming\"".to_string())
17185        );
17186        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17187        assert_eq!(
17188            event.fields.get("reason"),
17189            Some(&"\"supervised_not_registered\"".to_string())
17190        );
17191        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17192        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17193        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17194        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17195        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17196        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17197        assert_eq!(
17198            handler.counters().snapshot()["route_open_refused_by_code"],
17199            json!({ "module_warming": 1 })
17200        );
17201    }
17202
17203    const OUTAGE_START: &str = "route.open refusing module: not serving";
17204    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17205
17206    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17207        capture
17208            .events()
17209            .into_iter()
17210            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17211            .collect()
17212    }
17213
17214    fn supervise_stub(
17215        registry: &Arc<Registry>,
17216        module_id: &str,
17217        enabled: bool,
17218    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17219        let supervisor_handle = SupervisorHandle::new();
17220        let supervisor =
17221            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17222                .with_handle(supervisor_handle.clone())
17223                .with_connection_file_path(std::env::temp_dir().join(format!(
17224                    "subc-route-outage-{module_id}-{}",
17225                    std::process::id()
17226                )));
17227        let module = supervisor
17228            .supervise_configured(
17229                ModuleSpec {
17230                    script: None,
17231                    carry_containment: false,
17232                    module_id: module_id.to_string(),
17233                    program: fake_aft_stub_path(),
17234                    args: Vec::new(),
17235                    env: Vec::new(),
17236                    reserved: false,
17237                    reserved_prefixes: Vec::new(),
17238                    protocol: ModuleProtocol::Subc,
17239                    overlap: Default::default(),
17240                },
17241                enabled,
17242            )
17243            .unwrap();
17244        (supervisor_handle, module)
17245    }
17246
17247    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17248        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17249            module_id: module_id.to_string(),
17250            drain_timeout_ms: Some(50),
17251        })
17252        .unwrap();
17253        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17254    }
17255
17256    /// Two handlers built over one forwarding table must share one outage
17257    /// tracker; separate trackers would each log their own opening line for
17258    /// the same outage.
17259    #[test]
17260    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17261        let registry = Arc::new(Registry::default());
17262        let forwarding = Arc::new(ForwardingTable::default());
17263        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17264        let second = ControlHandler::with_forwarding(registry, forwarding);
17265        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17266    }
17267
17268    /// A client can name any module id it likes. Refusing an unknown one,
17269    /// however often, must not create outage state or outage lines, or the
17270    /// tracker would be a memory sink any client could fill.
17271    #[tokio::test(flavor = "current_thread")]
17272    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17273        let handler = ControlHandler::new(Arc::new(Registry::default()));
17274        let capture = EventCapture::default();
17275        let _subscriber =
17276            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17277        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17278        for corr in 0..8 {
17279            let response = handler
17280                .handle_control_frame(
17281                    &ctx,
17282                    route_open_frame(
17283                        380 + corr,
17284                        &format!("nobody-{corr}"),
17285                        unique_project_root("outage-unknown"),
17286                    ),
17287                )
17288                .await
17289                .unwrap();
17290            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17291        }
17292
17293        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17294        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17295        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17296    }
17297
17298    /// Drives the refusal path end to end: a supervised module that served
17299    /// before and stopped being registered with no instruction to stop is a
17300    /// WARN, and the same module refused after an operator `supervisor.restart`
17301    /// is an INFO.
17302    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17303    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17304        let registry = Arc::new(Registry::default());
17305        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17306        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17307        let capture = EventCapture::default();
17308        let _subscriber =
17309            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17310        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17311        // The stub never registers, so pretend it served once: otherwise every
17312        // refusal would fall in its startup window.
17313        handler.route_outages.record_accepted("outage-restart");
17314
17315        let response = handler
17316            .handle_control_frame(
17317                &ctx,
17318                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17319            )
17320            .await
17321            .unwrap();
17322        assert_eq!(response[0].header.ty, FrameType::Error);
17323        let starts = outage_lines(&capture, OUTAGE_START);
17324        assert_eq!(starts.len(), 1, "{starts:?}");
17325        assert_eq!(starts[0].level, tracing::Level::WARN);
17326        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17327        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17328        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17329        handler.route_outages.record_accepted("outage-restart");
17330        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17331
17332        // The missing connection file makes the stub exit immediately. Restart
17333        // is deliberately deferred while that exit is being recorded; Failed
17334        // means the zero restart budget and terminal record have been published.
17335        tokio::time::timeout(Duration::from_secs(10), async {
17336            while module.state().unwrap() != crate::ModuleState::Failed {
17337                tokio::task::yield_now().await;
17338            }
17339        })
17340        .await
17341        .expect("stub exit must be recorded before the operator restart");
17342
17343        let restart = handler
17344            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17345            .await
17346            .unwrap();
17347        assert_eq!(
17348            restart[0].header.ty,
17349            FrameType::Response,
17350            "{:?}",
17351            parse_error(&restart[0])
17352        );
17353        handler
17354            .handle_control_frame(
17355                &ctx,
17356                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17357            )
17358            .await
17359            .unwrap();
17360        module.stop().await.unwrap();
17361
17362        let starts = outage_lines(&capture, OUTAGE_START);
17363        assert_eq!(starts.len(), 2, "{starts:?}");
17364        assert_eq!(starts[1].level, tracing::Level::INFO);
17365        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17366    }
17367
17368    /// A restart refused before it touched the module (here: the module is
17369    /// disabled) must clear its operator mark, so the next real outage is
17370    /// still reported as a warning.
17371    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17372    async fn failed_operator_restart_leaves_no_operator_mark() {
17373        let registry = Arc::new(Registry::default());
17374        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17375        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17376        let capture = EventCapture::default();
17377        let _subscriber =
17378            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17379        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17380        handler.route_outages.record_accepted("outage-disabled");
17381
17382        let restart = handler
17383            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17384            .await
17385            .unwrap();
17386        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17387        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17388
17389        handler
17390            .handle_control_frame(
17391                &ctx,
17392                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17393            )
17394            .await
17395            .unwrap();
17396        let starts = outage_lines(&capture, OUTAGE_START);
17397        assert_eq!(starts.len(), 1, "{starts:?}");
17398        assert_eq!(starts[0].level, tracing::Level::WARN);
17399    }
17400
17401    #[tokio::test(flavor = "current_thread")]
17402    async fn route_open_unknown_module_escapes_target_module_id() {
17403        let handler = ControlHandler::new(Arc::new(Registry::default()));
17404        let capture = EventCapture::default();
17405        let _subscriber =
17406            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17407        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17408        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17409        let response = handler
17410            .handle_control_frame(
17411                &ctx,
17412                route_open_frame(
17413                    395,
17414                    hostile_module_id,
17415                    unique_project_root("hostile-target-module-id"),
17416                ),
17417            )
17418            .await
17419            .unwrap();
17420
17421        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17422        let event = capture
17423            .events()
17424            .into_iter()
17425            .find(|event| {
17426                event.target == "control"
17427                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17428            })
17429            .expect("route.open unknown-module refusal event");
17430        let logged = event.fields.get("module_id").expect("module_id field");
17431        assert!(!logged.bytes().any(|byte| byte < 0x20));
17432        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17433    }
17434
17435    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17436    /// the daemon-origin bit on the frame the client receives.
17437    #[tokio::test(flavor = "current_thread")]
17438    async fn route_open_refusal_carries_daemon_origin() {
17439        let handler = ControlHandler::new(Arc::new(Registry::default()));
17440        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17441        let response = handler
17442            .handle_control_frame(
17443                &ctx,
17444                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17445            )
17446            .await
17447            .unwrap();
17448
17449        assert_eq!(response.len(), 1);
17450        assert_eq!(response[0].header.ty, FrameType::Error);
17451        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17452        assert!(
17453            response[0].header.flags.is_daemon_origin(),
17454            "route.open refusal must carry daemon origin: {:?}",
17455            response[0].header.flags
17456        );
17457    }
17458
17459    /// The drain `module_reloading` refusal is daemon-synthesized for an
17460    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17461    /// frame the client receives.
17462    #[tokio::test(flavor = "current_thread")]
17463    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17464        let registry = Arc::new(Registry::default());
17465        let forwarding = Arc::new(ForwardingTable::default());
17466        let handler =
17467            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17468        let module_connection = ConnectionId::new(95);
17469        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17470        hello_via_sink(
17471            &handler,
17472            &module_ctx,
17473            &mut module_rx,
17474            hello_frame("aft", PROTOCOL_VERSION, 395),
17475        )
17476        .await;
17477        forwarding
17478            .begin_module_drain("aft", RouteCloseReason::Restart)
17479            .unwrap()
17480            .expect("the module endpoint drains");
17481
17482        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17483        let response = handler
17484            .handle_control_frame(
17485                &client_ctx,
17486                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17487            )
17488            .await
17489            .unwrap();
17490
17491        assert_eq!(response.len(), 1);
17492        assert_eq!(response[0].header.ty, FrameType::Error);
17493        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17494        assert!(
17495            response[0].header.flags.is_daemon_origin(),
17496            "drain module_reloading must carry daemon origin: {:?}",
17497            response[0].header.flags
17498        );
17499    }
17500
17501    /// A module that refuses a bind with a daemon code still cannot mint a
17502    /// daemon refusal: the relayed `module_reloading` body reaches the client
17503    /// with the daemon-origin bit clear.
17504    #[tokio::test(flavor = "current_thread")]
17505    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17506        let registry = Arc::new(Registry::default());
17507        let forwarding = Arc::new(ForwardingTable::default());
17508        let handler =
17509            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17510        let module_connection = ConnectionId::new(95);
17511        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17512        hello_via_sink(
17513            &handler,
17514            &module_ctx,
17515            &mut module_rx,
17516            hello_frame("aft", PROTOCOL_VERSION, 395),
17517        )
17518        .await;
17519
17520        let client_connection = ConnectionId::new(96);
17521        let (client_ctx, _client_rx) = route_ctx(client_connection);
17522        let (route_task, bind) = relay_route_open(
17523            &handler,
17524            client_connection,
17525            &client_ctx.egress,
17526            &mut module_rx,
17527            396,
17528            "aft",
17529            "spoofed-reloading",
17530        )
17531        .await;
17532        // The module sets the origin bit on its own rejection too: neither
17533        // the bit nor the daemon code may survive the relay as daemon-owned.
17534        let rejection = Frame::build(
17535            FrameType::Error,
17536            crate::router::daemon_error_flags(),
17537            0,
17538            0,
17539            bind.header.corr,
17540            serde_json::to_vec(&ErrorBody::new(
17541                "module_reloading",
17542                "module refused route.bind",
17543            ))
17544            .unwrap(),
17545        )
17546        .unwrap();
17547        handler
17548            .handle_control_frame(&module_ctx, rejection)
17549            .await
17550            .unwrap();
17551
17552        let response = route_task.await.unwrap();
17553        assert_eq!(response.len(), 1);
17554        assert_eq!(response[0].header.ty, FrameType::Error);
17555        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17556        assert!(
17557            !response[0].header.flags.is_daemon_origin(),
17558            "a module's own rejection must not carry daemon origin: {:?}",
17559            response[0].header.flags
17560        );
17561    }
17562
17563    #[tokio::test(flavor = "current_thread")]
17564    async fn route_open_module_rejection_uses_daemon_counter_key() {
17565        let registry = Arc::new(Registry::default());
17566        let forwarding = Arc::new(ForwardingTable::default());
17567        let handler =
17568            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17569        let module_connection = ConnectionId::new(95);
17570        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17571        hello_via_sink(
17572            &handler,
17573            &module_ctx,
17574            &mut module_rx,
17575            hello_frame("aft", PROTOCOL_VERSION, 395),
17576        )
17577        .await;
17578
17579        let client_connection = ConnectionId::new(96);
17580        let (client_ctx, _client_rx) = route_ctx(client_connection);
17581        let capture = EventCapture::default();
17582        // tracing-core decides once per callsite whether its events are enabled,
17583        // and caches the answer. If a parallel test with no subscriber reaches
17584        // this callsite first, the cached answer is "disabled" and this test's
17585        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17586        // ask every live subscriber instead, while only this test's default
17587        // receives the events.
17588        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17589        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17590        let _subscriber =
17591            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17592        let (route_task, bind) = relay_route_open(
17593            &handler,
17594            client_connection,
17595            &client_ctx.egress,
17596            &mut module_rx,
17597            396,
17598            "aft",
17599            "hostile-module-code",
17600        )
17601        .await;
17602        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17603        let rejection = Frame::build(
17604            FrameType::Error,
17605            control_flags(),
17606            0,
17607            0,
17608            bind.header.corr,
17609            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17610        )
17611        .unwrap();
17612        handler
17613            .handle_control_frame(&module_ctx, rejection)
17614            .await
17615            .unwrap();
17616
17617        let response = route_task.await.unwrap();
17618        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17619        let counters = handler.counters().snapshot();
17620        assert_eq!(
17621            counters["route_open_refused_by_code"],
17622            json!({ "module_rejected": 1 })
17623        );
17624        assert!(counters["route_open_refused_by_code"]
17625            .get(hostile_code)
17626            .is_none());
17627
17628        let event = capture
17629            .events()
17630            .into_iter()
17631            .find(|event| {
17632                event.target == "control"
17633                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17634            })
17635            .expect("route.open module-rejection refusal event");
17636        let logged = event.fields.get("module_code").expect("module_code field");
17637        assert!(!logged.bytes().any(|byte| byte < 0x20));
17638        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17639    }
17640
17641    #[tokio::test]
17642    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17643        let registry = Arc::new(Registry::default());
17644        let supervisor_handle = SupervisorHandle::new();
17645        let missing_program = std::env::temp_dir().join(format!(
17646            "subc-route-open-missing-program-{}",
17647            std::process::id()
17648        ));
17649        let supervisor =
17650            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17651                .with_handle(supervisor_handle.clone());
17652        let module = supervisor
17653            .supervise_configured(
17654                ModuleSpec {
17655                    script: None,
17656                    carry_containment: false,
17657                    module_id: "failed".to_string(),
17658                    program: missing_program,
17659                    args: Vec::new(),
17660                    env: Vec::new(),
17661                    reserved: false,
17662                    reserved_prefixes: Vec::new(),
17663                    protocol: ModuleProtocol::Subc,
17664                    overlap: Default::default(),
17665                },
17666                true,
17667            )
17668            .unwrap();
17669        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17670
17671        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17672        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17673        let response = handler
17674            .handle_control_frame(
17675                &ctx,
17676                route_open_frame(305, "failed", unique_project_root("failed")),
17677            )
17678            .await
17679            .unwrap();
17680
17681        assert_eq!(response[0].header.ty, FrameType::Error);
17682        let error = parse_error(&response[0]);
17683        assert_eq!(error["code"], "target_unavailable");
17684        assert!(error["message"]
17685            .as_str()
17686            .unwrap()
17687            .contains("state=failed, enabled=true, live=false"));
17688    }
17689
17690    #[tokio::test]
17691    async fn route_open_role_mismatch_remains_target_unavailable() {
17692        let registry = Arc::new(Registry::default());
17693        let handler = ControlHandler::new(Arc::clone(&registry));
17694        handler
17695            .handle_control(
17696                ConnectionId::new(41),
17697                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17698            )
17699            .unwrap();
17700
17701        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17702        let response = handler
17703            .handle_control_frame(
17704                &ctx,
17705                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17706            )
17707            .await
17708            .unwrap();
17709
17710        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17711        assert!(parse_error(&response[0])["message"]
17712            .as_str()
17713            .unwrap()
17714            .contains("does not provide the requested target"));
17715    }
17716
17717    #[tokio::test]
17718    async fn route_open_inactive_registration_remains_target_unavailable() {
17719        let registry = Arc::new(Registry::default());
17720        let handler = ControlHandler::new(Arc::clone(&registry));
17721        handler
17722            .handle_control(
17723                ConnectionId::new(43),
17724                hello_frame("inactive", PROTOCOL_VERSION, 308),
17725            )
17726            .unwrap();
17727        assert!(registry
17728            .set_module_state_for_test("inactive", ChannelState::Closed)
17729            .unwrap());
17730
17731        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17732        let response = handler
17733            .handle_control_frame(
17734                &ctx,
17735                route_open_frame(309, "inactive", unique_project_root("inactive")),
17736            )
17737            .await
17738            .unwrap();
17739
17740        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17741        assert!(parse_error(&response[0])["message"]
17742            .as_str()
17743            .unwrap()
17744            .contains("is not active"));
17745    }
17746
17747    #[tokio::test]
17748    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17749        let registry = Arc::new(Registry::default());
17750        let forwarding = Arc::new(ForwardingTable::default());
17751        let supervisor_handle = SupervisorHandle::new();
17752        let supervisor =
17753            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17754                .with_forwarding(Arc::clone(&forwarding))
17755                .with_handle(supervisor_handle.clone());
17756        let module = supervisor
17757            .supervise_configured(
17758                crate::ModuleSpec {
17759                    script: None,
17760                    carry_containment: false,
17761                    module_id: "late-health-response".to_string(),
17762                    program: PathBuf::from("disabled-module"),
17763                    args: Vec::new(),
17764                    env: Vec::new(),
17765                    reserved: false,
17766                    reserved_prefixes: Vec::new(),
17767                    protocol: ModuleProtocol::Subc,
17768                    overlap: Default::default(),
17769                },
17770                false,
17771            )
17772            .unwrap();
17773        let handler =
17774            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17775                .with_supervisor(supervisor_handle);
17776        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17777        handler
17778            .handle_control_frame(
17779                &module_ctx,
17780                hello_frame_with_control_ops(
17781                    "late-health-response",
17782                    PROTOCOL_VERSION,
17783                    7,
17784                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17785                ),
17786            )
17787            .await
17788            .unwrap();
17789        let probe_started_at = Instant::now() - Duration::from_millis(80);
17790        let pending = forwarding
17791            .begin_health_probe_rpc_for(
17792                "late-health-response",
17793                MODULE_CONTROL_OP_HEALTH_CHECK,
17794                probe_started_at,
17795                Instant::now() - Duration::from_millis(1),
17796            )
17797            .unwrap();
17798        assert!(forwarding
17799            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17800            .unwrap());
17801
17802        let responses = handler
17803            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17804            .await
17805            .unwrap();
17806
17807        assert!(responses.is_empty());
17808        let health = module.status().unwrap().health;
17809        assert_eq!(health.late_answer_count, 1);
17810        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17811    }
17812
17813    #[tokio::test]
17814    async fn health_probe_timeout_and_module_death_are_typed() {
17815        let registry = Arc::new(Registry::default());
17816        let forwarding = Arc::new(ForwardingTable::default());
17817        let handler =
17818            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17819                .with_health_probe_timeout(Duration::from_millis(50));
17820        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17821        hello_via_sink(
17822            &handler,
17823            &module_ctx,
17824            &mut module_rx,
17825            hello_frame_with_control_ops(
17826                "aft",
17827                PROTOCOL_VERSION,
17828                7,
17829                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17830            ),
17831        )
17832        .await;
17833
17834        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17835        let responses = handler
17836            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17837            .await
17838            .unwrap();
17839        assert_eq!(responses[0].header.ty, FrameType::Error);
17840        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17841        let _ = module_rx.try_recv();
17842
17843        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17844        let health_handler = handler.clone();
17845        let death_task = tokio::spawn(async move {
17846            health_handler
17847                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17848                .await
17849                .unwrap()
17850        });
17851        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17852            .await
17853            .unwrap()
17854            .unwrap();
17855        handler
17856            .cleanup_connection(module_ctx.connection_id)
17857            .unwrap();
17858        let responses = death_task.await.unwrap();
17859        assert_eq!(responses[0].header.ty, FrameType::Error);
17860        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17861    }
17862
17863    #[test]
17864    fn hello_requires_exact_protocol_version() {
17865        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17866            let registry = Arc::new(Registry::default());
17867            let handler = ControlHandler::new(Arc::clone(&registry));
17868            let responses = handler
17869                .handle_control(
17870                    ConnectionId::new(connection),
17871                    hello_frame("aft", offered, 9),
17872                )
17873                .unwrap();
17874
17875            assert_eq!(responses.len(), 1);
17876            assert_eq!(responses[0].header.ty, FrameType::Error);
17877            let error = parse_error(&responses[0]);
17878            assert_eq!(error["code"], "version_unsupported");
17879            assert!(registry.get_module("aft").unwrap().is_none());
17880            assert_eq!(registry.active_registration_count().unwrap(), 0);
17881        }
17882    }
17883
17884    #[test]
17885    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17886        let registry = Arc::new(Registry::default());
17887        let forwarding = Arc::new(ForwardingTable::default());
17888        let handler =
17889            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17890        let module_connection = ConnectionId::new(301);
17891        let registration = registry
17892            .register_with_control_ops(
17893                manifest("aft-push", PROTOCOL_VERSION),
17894                PROTOCOL_VERSION,
17895                module_connection,
17896                module_baseline_control_ops(),
17897            )
17898            .unwrap();
17899        let (module_tx, _module_rx) = mpsc::channel(8);
17900        let endpoint = forwarding
17901            .register_module_connection(
17902                module_connection,
17903                "aft-push".to_string(),
17904                PROTOCOL_VERSION,
17905                manifest_concurrency(&registration.manifest),
17906                FrameSink::new(module_tx),
17907            )
17908            .unwrap();
17909
17910        // A push op this version does not know is ignored (forward-compat), not errored.
17911        let unknown = Frame::build(
17912            FrameType::Push,
17913            control_flags(),
17914            0,
17915            0,
17916            5,
17917            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17918        )
17919        .unwrap();
17920        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17921        assert!(
17922            out.is_empty(),
17923            "unknown push op must be ignored, got {out:?}"
17924        );
17925
17926        // A malformed body for a KNOWN op is a real error worth surfacing.
17927        let malformed = Frame::build(
17928            FrameType::Push,
17929            control_flags(),
17930            0,
17931            0,
17932            6,
17933            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17934        )
17935        .unwrap();
17936        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17937        assert_eq!(out.len(), 1);
17938        assert_eq!(out[0].header.ty, FrameType::Error);
17939        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17940    }
17941
17942    #[test]
17943    fn hello_rejected_when_connection_already_owns_client_routes() {
17944        let registry = Arc::new(Registry::default());
17945        let forwarding = Arc::new(ForwardingTable::default());
17946        let handler =
17947            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17948        // Commits a client route on connection 202 (bound to a module on conn 101).
17949        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17950        let client_connection = ConnectionId::new(202);
17951
17952        // That same connection now tries to register as a module: rejected, so one
17953        // connection never holds both client-route and module-endpoint state.
17954        let responses = handler
17955            .handle_control(
17956                client_connection,
17957                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17958            )
17959            .unwrap();
17960        assert_eq!(responses[0].header.ty, FrameType::Error);
17961        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17962        assert!(registry.get_module("aft-second").unwrap().is_none());
17963    }
17964
17965    #[tokio::test]
17966    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17967        let registry = Arc::new(Registry::default());
17968        let forwarding = Arc::new(ForwardingTable::default());
17969        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
17970        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
17971        hello_via_sink(
17972            &handler,
17973            &module_ctx,
17974            &mut module_rx,
17975            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
17976        )
17977        .await;
17978        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
17979        let pending = forwarding
17980            .begin_route_bind_relay_for_test(
17981                client_ctx.connection_id,
17982                client_ctx.egress.clone(),
17983                2,
17984                "alpha",
17985            )
17986            .unwrap();
17987        forwarding
17988            .complete_pending_relay(
17989                module_ctx.connection_id,
17990                pending.corr,
17991                RouteBindRelayOutcome::Accepted,
17992            )
17993            .unwrap();
17994        client_rx.try_recv().unwrap();
17995        for module_id in ["beta", "alpha"] {
17996            let replies = handler
17997                .handle_control_frame(
17998                    &module_ctx,
17999                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
18000                )
18001                .await
18002                .unwrap();
18003            assert_eq!(replies.len(), 1, "second HELLO must be refused");
18004            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
18005        }
18006        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
18007        assert!(registry.get_module("beta").unwrap().is_none());
18008        assert!(matches!(
18009            forwarding
18010                .lookup_data_route(
18011                    client_ctx.connection_id,
18012                    pending.client_channel,
18013                    pending.client_epoch,
18014                )
18015                .unwrap(),
18016            DataRoute::Client(DataRouteState::Bound(_))
18017        ));
18018        assert!(handler
18019            .hello_launch_nonces
18020            .lock()
18021            .unwrap()
18022            .presented(module_ctx.connection_id, Some("alpha-nonce")));
18023        assert!(module_rx.try_recv().is_err());
18024    }
18025
18026    #[test]
18027    fn reserved_module_hello_requires_matching_launch_nonce() {
18028        let registry = Arc::new(Registry::default());
18029        let supervisor = SupervisorHandle::new();
18030        // The supervisor recorded the nonce it injected when it spawned the reserved
18031        // module; the HELLO verifier checks against the same shared handle.
18032        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
18033        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18034
18035        // A HELLO with NO nonce is rejected.
18036        let no_nonce = handler
18037            .handle_control(
18038                ConnectionId::new(1),
18039                hello_frame("vault", PROTOCOL_VERSION, 1),
18040            )
18041            .unwrap();
18042        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
18043        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
18044        assert!(registry.get_module("vault").unwrap().is_none());
18045
18046        // A HELLO with the WRONG nonce is rejected.
18047        let wrong = handler
18048            .handle_control(
18049                ConnectionId::new(2),
18050                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
18051            )
18052            .unwrap();
18053        assert_eq!(wrong[0].header.ty, FrameType::Error);
18054        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
18055        assert!(registry.get_module("vault").unwrap().is_none());
18056
18057        // A HELLO with the CORRECT nonce registers.
18058        let ok = handler
18059            .handle_control(
18060                ConnectionId::new(3),
18061                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
18062            )
18063            .unwrap();
18064        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18065        assert!(registry.get_module("vault").unwrap().is_some());
18066    }
18067
18068    #[test]
18069    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18070        let registry = Arc::new(Registry::default());
18071        let supervisor = SupervisorHandle::new();
18072        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18073        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18074        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18075
18076        let squat = handler
18077            .handle_control(
18078                ConnectionId::new(1),
18079                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18080            )
18081            .unwrap();
18082        assert_eq!(squat[0].header.ty, FrameType::Error);
18083        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18084        assert!(parse_error(&squat[0])["message"]
18085            .as_str()
18086            .unwrap()
18087            .contains("fed:"));
18088
18089        let accepted_peer = handler
18090            .handle_control(
18091                ConnectionId::new(2),
18092                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18093            )
18094            .unwrap();
18095        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18096
18097        let accepted_short = handler
18098            .handle_control(
18099                ConnectionId::new(3),
18100                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18101            )
18102            .unwrap();
18103        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18104
18105        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18106            let response = handler
18107                .handle_control(
18108                    ConnectionId::new(conn),
18109                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18110                )
18111                .unwrap();
18112            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18113        }
18114    }
18115
18116    #[test]
18117    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18118        let registry = Arc::new(Registry::default());
18119        let supervisor = SupervisorHandle::new();
18120        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18121        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18122        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18123        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18124
18125        let owner_nonce = handler
18126            .handle_control(
18127                ConnectionId::new(1),
18128                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18129            )
18130            .unwrap();
18131        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18132        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18133        assert!(registry.get_module("fed:special").unwrap().is_none());
18134
18135        let exact_nonce = handler
18136            .handle_control(
18137                ConnectionId::new(2),
18138                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18139            )
18140            .unwrap();
18141        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18142        assert!(registry.get_module("fed:special").unwrap().is_some());
18143    }
18144
18145    #[test]
18146    fn non_reserved_module_ignores_launch_nonce() {
18147        let registry = Arc::new(Registry::default());
18148        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18149        // registration succeeds whether a spawned process echoes a nonce or not.
18150        let handler = ControlHandler::new(Arc::clone(&registry));
18151        let no_nonce = handler
18152            .handle_control(
18153                ConnectionId::new(1),
18154                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18155            )
18156            .unwrap();
18157        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18158        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18159
18160        let echoed_nonce = handler
18161            .handle_control(
18162                ConnectionId::new(2),
18163                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18164            )
18165            .unwrap();
18166        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18167        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18168    }
18169
18170    #[test]
18171    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18172        let handler = ControlHandler::default();
18173        let conn = ConnectionId::new(1);
18174        let malformed = Frame::build(
18175            FrameType::Hello,
18176            control_flags(),
18177            0,
18178            0,
18179            3,
18180            b"{not json".to_vec(),
18181        )
18182        .unwrap();
18183
18184        let error = handler.handle_control(conn, malformed).unwrap();
18185        assert_eq!(error[0].header.ty, FrameType::Error);
18186        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18187
18188        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18189        let pong = handler.handle_control(conn, ping).unwrap();
18190        assert_eq!(pong[0].header.ty, FrameType::Pong);
18191        assert_eq!(pong[0].header.corr, 4);
18192    }
18193
18194    #[test]
18195    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18196        let registry = Arc::new(Registry::default());
18197        let handler = ControlHandler::new(Arc::clone(&registry));
18198
18199        handler
18200            .handle_control(
18201                ConnectionId::new(1),
18202                hello_frame("aft", PROTOCOL_VERSION, 1),
18203            )
18204            .unwrap();
18205        let duplicate = handler
18206            .handle_control(
18207                ConnectionId::new(2),
18208                hello_frame("aft", PROTOCOL_VERSION, 2),
18209            )
18210            .unwrap();
18211
18212        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18213        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18214        let registration = registry.get_module("aft").unwrap().unwrap();
18215        assert_eq!(registration.connection_id, ConnectionId::new(1));
18216    }
18217
18218    #[test]
18219    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18220        let registry = Arc::new(Registry::default());
18221        let forwarding = Arc::new(ForwardingTable::default());
18222        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18223        let handler =
18224            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18225                .with_process_liveness(process_liveness);
18226        let (ctx, route_channel, route_epoch) =
18227            bind_liveness_route(&registry, &forwarding, "aft-dead");
18228        let responses = handler
18229            .handle_route_poll(
18230                &ctx,
18231                route_poll_frame(41, PollKind::Liveness, route_channel),
18232                route_channel,
18233                route_epoch,
18234                PollKind::Liveness,
18235            )
18236            .unwrap();
18237
18238        assert_eq!(responses.len(), 1);
18239        assert_eq!(responses[0].header.ty, FrameType::Response);
18240        assert_route_poll_liveness(&responses[0], false);
18241    }
18242
18243    #[test]
18244    fn liveness_poll_without_process_source_uses_bound_route() {
18245        let registry = Arc::new(Registry::default());
18246        let forwarding = Arc::new(ForwardingTable::default());
18247        let handler =
18248            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18249        let (ctx, route_channel, route_epoch) =
18250            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18251        let responses = handler
18252            .handle_route_poll(
18253                &ctx,
18254                route_poll_frame(42, PollKind::Liveness, route_channel),
18255                route_channel,
18256                route_epoch,
18257                PollKind::Liveness,
18258            )
18259            .unwrap();
18260
18261        assert_route_poll_liveness(&responses[0], true);
18262    }
18263
18264    #[test]
18265    fn liveness_poll_untracked_process_source_uses_bound_route() {
18266        let registry = Arc::new(Registry::default());
18267        let forwarding = Arc::new(ForwardingTable::default());
18268        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18269        let handler =
18270            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18271                .with_process_liveness(process_liveness);
18272        let (ctx, route_channel, route_epoch) =
18273            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18274        let responses = handler
18275            .handle_route_poll(
18276                &ctx,
18277                route_poll_frame(43, PollKind::Liveness, route_channel),
18278                route_channel,
18279                route_epoch,
18280                PollKind::Liveness,
18281            )
18282            .unwrap();
18283
18284        assert_route_poll_liveness(&responses[0], true);
18285    }
18286
18287    #[tokio::test]
18288    async fn unknown_op_returns_unknown_control_op() {
18289        let handler = ControlHandler::default();
18290        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18291        let request = Frame::build(
18292            FrameType::Request,
18293            control_flags(),
18294            0,
18295            0,
18296            55,
18297            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18298        )
18299        .unwrap();
18300
18301        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18302
18303        assert_eq!(response.len(), 1);
18304        assert_eq!(response[0].header.ty, FrameType::Error);
18305        assert_eq!(response[0].header.corr, 55);
18306        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18307    }
18308
18309    #[tokio::test]
18310    async fn supervisor_provenance_rejects_unknown_exact_module() {
18311        let handler = ControlHandler::default();
18312        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18313        let request = Frame::build(
18314            FrameType::Request,
18315            control_flags(),
18316            0,
18317            0,
18318            57,
18319            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18320        )
18321        .unwrap();
18322
18323        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18324
18325        assert_eq!(response.len(), 1);
18326        assert_eq!(response[0].header.ty, FrameType::Error);
18327        assert_eq!(response[0].header.corr, 57);
18328        let error = parse_error(&response[0]);
18329        assert_eq!(error["code"], "unknown_module");
18330        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18331    }
18332
18333    #[test]
18334    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18335        let expected = subc_control::RunningImageAgreement::Unavailable {
18336            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18337        };
18338        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18339        assert_eq!(handler.provenance_probe_override, Some(expected));
18340    }
18341
18342    #[test]
18343    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18344        let verdict = reload_verdict(
18345            std::path::Path::new("/bin/new"),
18346            Some(std::path::Path::new("/bin/old")),
18347            subc_control::RunningImageAgreement::Unavailable {
18348                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18349            },
18350        );
18351        assert!(matches!(
18352            verdict.path,
18353            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18354                if configured == std::path::Path::new("/bin/new")
18355                    && spawned_from == std::path::Path::new("/bin/old")
18356        ));
18357    }
18358
18359    #[test]
18360    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18361        use subc_control::{
18362            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18363        };
18364        let configured = crate::supervise::ModuleSpec {
18365            script: None,
18366            carry_containment: false,
18367            module_id: "legacy".into(),
18368            program: "/module".into(),
18369            args: Vec::new(),
18370            env: Vec::new(),
18371            reserved: false,
18372            reserved_prefixes: Vec::new(),
18373            protocol: subc_control::ModuleProtocol::Subc,
18374            overlap: Default::default(),
18375        };
18376        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18377        assert_eq!(
18378            launch_spec_agreement(&configured, false, Some(&digest)),
18379            Agreement::Unavailable {
18380                reason: Reason::NotRunning
18381            }
18382        );
18383        assert_eq!(
18384            launch_spec_agreement(&configured, true, None),
18385            Agreement::Unavailable {
18386                reason: Reason::SpawnedSpecUnavailable
18387            }
18388        );
18389        assert_eq!(
18390            launch_spec_agreement(&configured, true, Some(&digest)),
18391            Agreement::Match
18392        );
18393    }
18394
18395    #[cfg(windows)]
18396    #[test]
18397    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18398        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18399        let configured = dir.join("module.exe");
18400        std::fs::write(&configured, b"executable path fixture").unwrap();
18401        let spawned = std::fs::canonicalize(&configured).unwrap();
18402        assert_ne!(
18403            configured, spawned,
18404            "fixture must exercise different path spellings"
18405        );
18406        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18407        let lower_case = configured.to_string_lossy().to_lowercase();
18408        for spelling in [
18409            &configured,
18410            Path::new(&forward_slashes),
18411            Path::new(&lower_case),
18412        ] {
18413            let verdict = reload_verdict(
18414                spelling,
18415                Some(&spawned),
18416                subc_control::RunningImageAgreement::Unavailable {
18417                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18418                },
18419            );
18420            assert_eq!(
18421                verdict.path,
18422                ReloadPathAgreement::Match,
18423                "configured {spelling:?}, spawned {spawned:?}"
18424            );
18425        }
18426    }
18427
18428    #[cfg(windows)]
18429    #[test]
18430    fn windows_reload_path_keeps_different_existing_program_pending() {
18431        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18432        let old = dir.join("old.exe");
18433        let new = dir.join("new.exe");
18434        std::fs::write(&old, b"same executable content").unwrap();
18435        std::fs::copy(&old, &new).unwrap();
18436        let spawned = std::fs::canonicalize(&old).unwrap();
18437        let image = subc_control::RunningImageAgreement::Unavailable {
18438            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18439        };
18440        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18441        assert!(
18442            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18443            if configured == new && spawned_from == spawned)
18444        );
18445        let missing = dir.join("missing.exe");
18446        assert!(matches!(
18447            reload_verdict(&missing, Some(&spawned), image).path,
18448            ReloadPathAgreement::Mismatch { .. }
18449        ));
18450    }
18451
18452    #[test]
18453    fn reload_verdict_detects_replaced_image_at_same_path() {
18454        let image = subc_control::RunningImageAgreement::Mismatch {
18455            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18456                digest: "old".into(),
18457            },
18458            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18459                digest: "new".into(),
18460            },
18461        };
18462        let verdict = reload_verdict(
18463            std::path::Path::new("/bin/same"),
18464            Some(std::path::Path::new("/bin/same")),
18465            image.clone(),
18466        );
18467        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18468        assert_eq!(verdict.image, image);
18469    }
18470
18471    #[test]
18472    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18473        let image = subc_control::RunningImageAgreement::Unavailable {
18474            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18475        };
18476        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18477        assert_eq!(
18478            verdict.path,
18479            subc_control::ReloadPathAgreement::Unavailable {
18480                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18481            }
18482        );
18483        assert_eq!(verdict.image, image);
18484
18485        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18486            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18487        };
18488        let verdict = reload_verdict(
18489            std::path::Path::new("/bin/same"),
18490            Some(std::path::Path::new("/bin/same")),
18491            unconfirmed.clone(),
18492        );
18493        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18494        assert_eq!(verdict.image, unconfirmed);
18495    }
18496
18497    #[test]
18498    fn reload_verdict_preserves_each_image_unavailability_reason() {
18499        use subc_control::RunningImageUnavailableReason as Reason;
18500
18501        for reason in [
18502            Reason::NotRunning,
18503            Reason::UnsupportedPlatform,
18504            Reason::RunningExecutableUnreadable,
18505            Reason::SpawnedPathUnreadable,
18506            Reason::HashFailed,
18507            Reason::ProcessIdentityUnconfirmed,
18508            Reason::Unknown("future_probe_reason".to_string()),
18509        ] {
18510            let image = subc_control::RunningImageAgreement::Unavailable {
18511                reason: reason.clone(),
18512            };
18513            let verdict = reload_verdict(
18514                std::path::Path::new("/bin/same"),
18515                Some(std::path::Path::new("/bin/same")),
18516                image.clone(),
18517            );
18518            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18519            assert_eq!(verdict.image, image, "{reason:?}");
18520        }
18521    }
18522
18523    #[tokio::test]
18524    async fn malformed_control_bodies_return_invalid_control_body() {
18525        let handler = ControlHandler::default();
18526        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18527
18528        for (corr, body) in [
18529            (56, br#"{"route_channel":1}"#.as_slice()),
18530            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18531            (
18532                58,
18533                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18534            ),
18535        ] {
18536            let request = Frame::build(
18537                FrameType::Request,
18538                control_flags(),
18539                0,
18540                0,
18541                corr,
18542                body.to_vec(),
18543            )
18544            .unwrap();
18545            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18546
18547            assert_eq!(response.len(), 1);
18548            assert_eq!(response[0].header.ty, FrameType::Error);
18549            assert_eq!(response[0].header.corr, corr);
18550            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18551        }
18552    }
18553
18554    #[tokio::test]
18555    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18556        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18557        let registry = Arc::new(Registry::default());
18558        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18559        let router = Router::with_control_handler(Arc::clone(&control));
18560        let connection = router.begin_connection();
18561        let (ctx, mut rx) = route_ctx(connection.id());
18562
18563        router
18564            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18565            .await
18566            .unwrap();
18567        let response = rx.recv().await.unwrap();
18568        let ack = parse_ack(&response);
18569        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18570        let channel = 1;
18571
18572        let goodbye =
18573            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18574        router.route_for_connection(&ctx, goodbye).await.unwrap();
18575        assert!(rx.try_recv().is_err());
18576        assert!(registry.get_module("aft").unwrap().is_none());
18577
18578        router
18579            .route_for_connection(&ctx, channel_request(channel, 13))
18580            .await
18581            .unwrap();
18582        let error_frame = rx.recv().await.unwrap();
18583        assert_eq!(error_frame.header.ty, FrameType::Error);
18584        assert_eq!(error_frame.header.channel, channel);
18585        let captured = crate::router::test_log::captured_logs(&logs);
18586        assert_eq!(
18587            captured
18588                .lines()
18589                .filter(|line| {
18590                    line.contains("module_id=aft")
18591                        && line.contains("reason=explicit_goodbye")
18592                        && line.contains("module registration ended")
18593                })
18594                .count(),
18595            1,
18596            "unexpected GOODBYE registry log: {captured}"
18597        );
18598    }
18599
18600    #[tokio::test]
18601    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18602        let registry = Arc::new(Registry::default());
18603        let handler = ControlHandler::new(registry).with_capability_config(
18604            [("prov".to_string(), true), ("cons".to_string(), true)],
18605            BTreeMap::new(),
18606        );
18607        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18608        register_capability_manifest(
18609            &handler,
18610            &provider_ctx,
18611            &mut provider_rx,
18612            capability_manifest("prov", &["thing/v1"], &[]),
18613            1,
18614        )
18615        .await;
18616        let mut consumer = capability_manifest("cons", &[], &[]);
18617        consumer.capabilities.as_mut().unwrap().requires.push(
18618            subc_protocol::manifest::CapabilityRequirement {
18619                capability: "thing/v1".to_string(),
18620                need: subc_protocol::manifest::CapabilityNeed::Required,
18621            },
18622        );
18623        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18624        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18625        assert_eq!(
18626            handler.capability_evaluator.verdict("cons", "thing/v1"),
18627            Some(CapabilityVerdict::Provided)
18628        );
18629        let (mut client_rx, _) = open_route_for_capability_test(
18630            &handler,
18631            &provider_ctx,
18632            &mut provider_rx,
18633            703,
18634            3,
18635            "prov",
18636            None,
18637        )
18638        .await;
18639        let goodbye =
18640            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18641        handler
18642            .handle_control_frame(&provider_ctx, goodbye)
18643            .await
18644            .unwrap();
18645        assert_eq!(
18646            handler.capability_evaluator.verdict("cons", "thing/v1"),
18647            Some(CapabilityVerdict::NeverProvided)
18648        );
18649        let closed = client_rx
18650            .try_recv()
18651            .expect("GOODBYE pushes route.closed before route GOODBYE");
18652        assert!(
18653            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18654            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18655        );
18656        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18657        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18658    }
18659
18660    struct RouteClosedFixture {
18661        handler: ControlHandler,
18662        #[cfg(unix)]
18663        supervisor: Supervisor,
18664        module_ctx: RouteCtx,
18665        #[cfg(unix)]
18666        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18667        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18668        route: Arc<crate::forwarding::RouteBinding>,
18669    }
18670
18671    async fn route_closed_fixture() -> RouteClosedFixture {
18672        let registry = Arc::new(Registry::default());
18673        let handler = ControlHandler::new(Arc::clone(&registry));
18674        #[cfg(unix)]
18675        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18676            .with_forwarding(Arc::clone(&handler.forwarding));
18677        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18678        register_capability_manifest(
18679            &handler,
18680            &module_ctx,
18681            &mut module_rx,
18682            capability_manifest("prov", &[], &[]),
18683            1,
18684        )
18685        .await;
18686        let (client_rx, bind) = open_route_for_capability_test(
18687            &handler,
18688            &module_ctx,
18689            &mut module_rx,
18690            702,
18691            2,
18692            "prov",
18693            None,
18694        )
18695        .await;
18696        let ModuleControlRequest::RouteBind {
18697            route_channel: channel,
18698            epoch: route_epoch,
18699            ..
18700        } = bind
18701        else {
18702            panic!("expected route.bind");
18703        };
18704        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18705            handler
18706                .forwarding
18707                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18708                .unwrap()
18709        else {
18710            panic!("the acknowledged route must be bound");
18711        };
18712        RouteClosedFixture {
18713            handler,
18714            #[cfg(unix)]
18715            supervisor,
18716            module_ctx,
18717            #[cfg(unix)]
18718            module_rx,
18719            client_rx,
18720            route,
18721        }
18722    }
18723
18724    impl RouteClosedFixture {
18725        #[cfg(unix)]
18726        async fn cut(&mut self) {
18727            let notices = async {
18728                let mut draining = self.module_rx.recv().await.unwrap();
18729                assert!(matches!(
18730                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18731                        &draining.body
18732                    )
18733                    .unwrap(),
18734                    subc_protocol::session::ModuleControlCommand::Draining {
18735                        reason: RouteCloseReason::Disable,
18736                        ..
18737                    }
18738                ));
18739                draining.flushed.take().unwrap().send(()).unwrap();
18740                let mut closing = self.client_rx.recv().await.unwrap();
18741                assert!(matches!(
18742                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18743                    ClientControlPush::RouteClosing {
18744                        reason: RouteCloseReason::Restart,
18745                        ..
18746                    }
18747                ));
18748                closing.flushed.take().unwrap().send(()).unwrap();
18749            };
18750            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18751            result.unwrap();
18752        }
18753
18754        fn disconnect(&mut self) -> ClientControlPush {
18755            self.handler
18756                .cleanup_connection(self.module_ctx.connection_id)
18757                .unwrap();
18758            let closed = self.client_rx.try_recv().unwrap();
18759            assert_eq!(closed.header.ty, FrameType::Push);
18760            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18761            assert!(matches!(
18762                &push,
18763                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18764                    if channels == &[self.route.client_channel]
18765            ));
18766            assert_eq!(
18767                self.client_rx.try_recv().unwrap().header.ty,
18768                FrameType::Goodbye
18769            );
18770            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18771            push
18772        }
18773    }
18774
18775    #[cfg(unix)]
18776    #[tokio::test(start_paused = true)]
18777    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18778        let mut fixture = route_closed_fixture().await;
18779        fixture.cut().await;
18780        assert!(matches!(
18781            fixture.disconnect(),
18782            ClientControlPush::RouteClosed {
18783                reason: RouteCloseReason::Restart,
18784                drained: true,
18785                ..
18786            }
18787        ));
18788    }
18789
18790    #[cfg(unix)]
18791    #[tokio::test(start_paused = true)]
18792    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18793        let mut fixture = route_closed_fixture().await;
18794        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18795        let started = tokio::time::Instant::now();
18796        fixture.cut().await;
18797        assert!(started.elapsed() >= Duration::from_secs(2));
18798        assert_eq!(fixture.route.flow.in_flight(), 1);
18799        assert!(matches!(
18800            fixture.disconnect(),
18801            ClientControlPush::RouteClosed {
18802                reason: RouteCloseReason::Restart,
18803                drained: false,
18804                ..
18805            }
18806        ));
18807    }
18808
18809    #[tokio::test]
18810    async fn module_connection_crash_reports_crash_and_not_drained() {
18811        let mut fixture = route_closed_fixture().await;
18812        // The server calls cleanup_connection on module EOF. Without a planned
18813        // daemon shutdown, that disconnect must remain a crash with no prior
18814        // route.closing notice, even when the route has no in-flight calls.
18815        assert!(matches!(
18816            fixture.disconnect(),
18817            ClientControlPush::RouteClosed {
18818                reason: RouteCloseReason::Crash,
18819                drained: false,
18820                ..
18821            }
18822        ));
18823    }
18824
18825    #[tokio::test]
18826    async fn dropping_router_connection_releases_registration() {
18827        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18828        let registry = Arc::new(Registry::default());
18829        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18830        let router = Router::with_control_handler(Arc::clone(&control));
18831        let connection = router.begin_connection();
18832        let connection_id = connection.id();
18833        let (ctx, mut rx) = route_ctx(connection_id);
18834
18835        router
18836            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18837            .await
18838            .unwrap();
18839        let response = rx.recv().await.unwrap();
18840        let ack = parse_ack(&response);
18841        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18842        assert!(registry.get_module("aft").unwrap().is_some());
18843
18844        drop(connection);
18845
18846        assert!(registry.get_module("aft").unwrap().is_none());
18847        assert_eq!(registry.active_registration_count().unwrap(), 0);
18848
18849        control
18850            .cleanup_connection(ConnectionId::new(u64::MAX))
18851            .unwrap();
18852        let captured = crate::router::test_log::captured_logs(&logs);
18853        println!("captured registry lifecycle logs:\n{captured}");
18854        let events: Vec<_> = captured
18855            .lines()
18856            .filter(|line| {
18857                line.contains("module registered module_id=aft ")
18858                    || line.contains("module registration ended")
18859            })
18860            .collect();
18861        assert_eq!(
18862            events.len(),
18863            2,
18864            "unexpected registry lifecycle logs: {captured}"
18865        );
18866        assert!(events[0].contains("module registered module_id=aft "));
18867        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18868        assert!(events[1].contains(&format!(
18869            "module_id=aft connection_id={}",
18870            connection_id.get()
18871        )));
18872        assert!(events[1].contains("reason=connection_closed"));
18873        assert!(events[1].contains("module registration ended"));
18874        assert_eq!(
18875            captured
18876                .lines()
18877                .filter(|line| line.contains("module registered module_id=aft "))
18878                .count(),
18879            1,
18880            "legacy registration admission line must appear once: {captured}"
18881        );
18882    }
18883
18884    #[tokio::test]
18885    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18886        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18887        let registry = Arc::new(Registry::default());
18888        let control = ControlHandler::new(Arc::clone(&registry));
18889        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18890        hello_via_sink(
18891            &control,
18892            &ctx,
18893            &mut rx,
18894            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18895        )
18896        .await;
18897
18898        let captured = crate::router::test_log::captured_logs(&logs);
18899        let admissions: Vec<_> = captured
18900            .lines()
18901            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18902            .collect();
18903        assert_eq!(
18904            admissions.len(),
18905            1,
18906            "legacy admission line must remain exactly once: {captured}"
18907        );
18908        assert!(admissions[0].contains("routable_provider=true"));
18909        assert!(admissions[0].contains("connection_id=777"));
18910    }
18911
18912    fn capability_manifest(
18913        module_id: &str,
18914        provides: &[&str],
18915        must_never_reach: &[&str],
18916    ) -> ModuleManifest {
18917        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18918        manifest.capabilities = Some(CapabilityDeclarations {
18919            provides: provides
18920                .iter()
18921                .map(|capability| (*capability).to_string())
18922                .collect(),
18923            requires: Vec::new(),
18924            must_never_reach: must_never_reach
18925                .iter()
18926                .map(|capability| (*capability).to_string())
18927                .collect(),
18928        });
18929        manifest
18930    }
18931
18932    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18933        Frame::build(
18934            FrameType::Hello,
18935            control_flags(),
18936            0,
18937            0,
18938            corr,
18939            serde_json::to_vec(&ModuleHelloBody {
18940                protocol_ver: manifest.protocol_ver,
18941                manifest,
18942                control_ops: None,
18943                launch_nonce: None,
18944            })
18945            .expect("capability test HELLO serializes"),
18946        )
18947        .expect("capability test HELLO frame builds")
18948    }
18949
18950    fn catalog_update_with_capabilities_frame(
18951        corr: u64,
18952        capabilities: CapabilityDeclarations,
18953    ) -> Frame {
18954        Frame::build(
18955            FrameType::Request,
18956            control_flags(),
18957            0,
18958            0,
18959            corr,
18960            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18961                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18962                capabilities: Some(capabilities),
18963                ready: None,
18964            })
18965            .expect("capability catalog.update serializes"),
18966        )
18967        .expect("capability catalog.update frame builds")
18968    }
18969
18970    async fn register_capability_manifest(
18971        handler: &ControlHandler,
18972        ctx: &RouteCtx,
18973        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18974        manifest: ModuleManifest,
18975        corr: u64,
18976    ) {
18977        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
18978    }
18979
18980    async fn open_route_for_capability_test(
18981        handler: &ControlHandler,
18982        target_ctx: &RouteCtx,
18983        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18984        client_connection_id: u64,
18985        corr: u64,
18986        target_module_id: &str,
18987        consumer_identity: Option<ConsumerIdentity>,
18988    ) -> (
18989        mpsc::Receiver<crate::router::OutboundFrame>,
18990        ModuleControlRequest,
18991    ) {
18992        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
18993        let route_handler = handler.clone();
18994        let target_module_id = target_module_id.to_string();
18995        let route_task = tokio::spawn(async move {
18996            route_handler
18997                .handle_control_frame(
18998                    &client_ctx,
18999                    route_open_frame_with_admission_facts(
19000                        corr,
19001                        &target_module_id,
19002                        unique_project_root("admission-facts"),
19003                        consumer_identity,
19004                        None,
19005                    ),
19006                )
19007                .await
19008                .expect("capability test route.open succeeds")
19009        });
19010        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
19011            .await
19012            .expect("capability test route.open must reach route.bind")
19013            .expect("target control receiver stays open");
19014        let bind_request: ModuleControlRequest =
19015            serde_json::from_slice(&bind.body).expect("route.bind decodes");
19016        handler
19017            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
19018            .await
19019            .expect("capability test route.bind ACK succeeds");
19020        assert!(route_task.await.expect("route.open task joins").is_empty());
19021        let opened = client_rx
19022            .recv()
19023            .await
19024            .expect("successful route.open publishes a response");
19025        assert!(matches!(
19026            serde_json::from_slice::<ClientControlResponse>(&opened.body),
19027            Ok(ClientControlResponse::RouteOpen { .. })
19028        ));
19029        (client_rx, bind_request)
19030    }
19031
19032    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
19033        assert_eq!(frame.header.ty, FrameType::Push);
19034        assert_eq!(frame.header.channel, 0);
19035        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
19036            .expect("route.closed control push decodes");
19037        let ClientControlPush::RouteClosed { channels, .. } = &push else {
19038            panic!("expected route.closed");
19039        };
19040        assert_eq!(channels.len(), 1, "exactly one violating route closed");
19041        let closed_channel = channels[0];
19042        let channels = channels.clone();
19043        assert_eq!(
19044            push,
19045            ClientControlPush::RouteClosed {
19046                module_id: target_module_id.to_string(),
19047                channels,
19048                reason: RouteCloseReason::CapabilityDenied,
19049                drained: false,
19050                abandoned: 0,
19051                excluded_subscriptions: 0,
19052                terminal: Some(false),
19053            }
19054        );
19055        closed_channel
19056    }
19057
19058    #[tokio::test]
19059    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
19060        let registry = Arc::new(Registry::default());
19061        let forwarding = Arc::new(ForwardingTable::default());
19062        let supervisor = SupervisorHandle::new();
19063        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19064        let handler =
19065            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19066                .with_supervisor(supervisor);
19067        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19068        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19069        register_capability_manifest(
19070            &handler,
19071            &target_ctx,
19072            &mut target_rx,
19073            capability_manifest("target", &["credentials-provider/v1"], &[]),
19074            1,
19075        )
19076        .await;
19077        register_capability_manifest(
19078            &handler,
19079            &opener_ctx,
19080            &mut opener_rx,
19081            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19082            2,
19083        )
19084        .await;
19085
19086        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19087        let replies = handler
19088            .handle_control_frame(
19089                &client_ctx,
19090                route_open_frame_with_admission_facts(
19091                    3,
19092                    "target",
19093                    unique_project_root("admission-facts"),
19094                    Some(ConsumerIdentity {
19095                        module_id: "opener".to_string(),
19096                        launch_nonce: "opener-nonce".to_string(),
19097                    }),
19098                    None,
19099                ),
19100            )
19101            .await
19102            .expect("denied route.open returns a typed frame");
19103        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19104        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19105        assert!(
19106            target_rx.try_recv().is_err(),
19107            "forbidden route.open must not relay route.bind"
19108        );
19109    }
19110
19111    #[tokio::test]
19112    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19113        let registry = Arc::new(Registry::default());
19114        let forwarding = Arc::new(ForwardingTable::default());
19115        let supervisor = SupervisorHandle::new();
19116        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19117        let handler =
19118            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19119                .with_supervisor(supervisor);
19120        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19121        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19122        register_capability_manifest(
19123            &handler,
19124            &target_ctx,
19125            &mut target_rx,
19126            capability_manifest("target", &["credentials-provider/v1"], &[]),
19127            1,
19128        )
19129        .await;
19130        register_capability_manifest(
19131            &handler,
19132            &old_opener_ctx,
19133            &mut old_opener_rx,
19134            capability_manifest("opener", &[], &[]),
19135            2,
19136        )
19137        .await;
19138        let (mut client_rx, _) = open_route_for_capability_test(
19139            &handler,
19140            &target_ctx,
19141            &mut target_rx,
19142            712,
19143            3,
19144            "target",
19145            Some(ConsumerIdentity {
19146                module_id: "opener".to_string(),
19147                launch_nonce: "opener-nonce".to_string(),
19148            }),
19149        )
19150        .await;
19151        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19152
19153        handler
19154            .cleanup_connection(old_opener_ctx.connection_id)
19155            .expect("old opener registration cleans up");
19156        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19157        register_capability_manifest(
19158            &handler,
19159            &new_opener_ctx,
19160            &mut new_opener_rx,
19161            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19162            4,
19163        )
19164        .await;
19165
19166        let closed_channel = assert_capability_denied_push(
19167            client_rx
19168                .try_recv()
19169                .expect("HELLO deny addition must emit route.closed")
19170                .frame,
19171            "target",
19172        );
19173        let goodbye = client_rx
19174            .try_recv()
19175            .expect("HELLO deny addition must send the client a route GOODBYE")
19176            .frame;
19177        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19178        assert_eq!(goodbye.header.channel, closed_channel);
19179        assert_ne!(goodbye.header.channel, 0);
19180        assert_ne!(goodbye.header.epoch, 0);
19181        assert!(client_rx.try_recv().is_err());
19182        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19183        assert!(matches!(
19184            target_rx.try_recv(),
19185            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19186        ));
19187    }
19188
19189    #[tokio::test]
19190    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19191        let registry = Arc::new(Registry::default());
19192        let forwarding = Arc::new(ForwardingTable::default());
19193        let supervisor = SupervisorHandle::new();
19194        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19195        let handler =
19196            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19197                .with_supervisor(supervisor);
19198        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19199        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19200        register_capability_manifest(
19201            &handler,
19202            &target_ctx,
19203            &mut target_rx,
19204            capability_manifest("target", &[], &[]),
19205            1,
19206        )
19207        .await;
19208        register_capability_manifest(
19209            &handler,
19210            &opener_ctx,
19211            &mut opener_rx,
19212            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19213            2,
19214        )
19215        .await;
19216        let (mut client_rx, _) = open_route_for_capability_test(
19217            &handler,
19218            &target_ctx,
19219            &mut target_rx,
19220            722,
19221            3,
19222            "target",
19223            Some(ConsumerIdentity {
19224                module_id: "opener".to_string(),
19225                launch_nonce: "opener-nonce".to_string(),
19226            }),
19227        )
19228        .await;
19229        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19230
19231        let replies = handler
19232            .handle_control_frame(
19233                &target_ctx,
19234                catalog_update_with_capabilities_frame(
19235                    4,
19236                    CapabilityDeclarations {
19237                        provides: vec!["credentials-provider/v1".to_string()],
19238                        requires: Vec::new(),
19239                        must_never_reach: Vec::new(),
19240                    },
19241                ),
19242            )
19243            .await
19244            .expect("claim catalog.update succeeds");
19245        assert!(matches!(
19246            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19247            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19248        ));
19249        let closed_channel = assert_capability_denied_push(
19250            client_rx
19251                .try_recv()
19252                .expect("claim addition must emit route.closed")
19253                .frame,
19254            "target",
19255        );
19256        let goodbye = client_rx
19257            .try_recv()
19258            .expect("claim addition must send the client a route GOODBYE")
19259            .frame;
19260        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19261        assert_eq!(goodbye.header.channel, closed_channel);
19262        assert_ne!(goodbye.header.channel, 0);
19263        assert_ne!(goodbye.header.epoch, 0);
19264        assert!(client_rx.try_recv().is_err());
19265        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19266        assert!(matches!(
19267            target_rx.try_recv(),
19268            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19269        ));
19270    }
19271
19272    #[tokio::test]
19273    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19274        let registry = Arc::new(Registry::default());
19275        let forwarding = Arc::new(ForwardingTable::default());
19276        let supervisor = SupervisorHandle::new();
19277        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19278        let handler =
19279            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19280                .with_supervisor(supervisor);
19281        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19282        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19283        register_capability_manifest(
19284            &handler,
19285            &target_ctx,
19286            &mut target_rx,
19287            capability_manifest("target", &["credentials-provider/v1"], &[]),
19288            1,
19289        )
19290        .await;
19291        register_capability_manifest(
19292            &handler,
19293            &opener_ctx,
19294            &mut opener_rx,
19295            capability_manifest("opener", &[], &[]),
19296            2,
19297        )
19298        .await;
19299        let (mut client_rx, _) = open_route_for_capability_test(
19300            &handler,
19301            &target_ctx,
19302            &mut target_rx,
19303            732,
19304            3,
19305            "target",
19306            Some(ConsumerIdentity {
19307                module_id: "opener".to_string(),
19308                launch_nonce: "opener-nonce".to_string(),
19309            }),
19310        )
19311        .await;
19312        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19313
19314        handler
19315            .handle_control_frame(
19316                &target_ctx,
19317                catalog_update_with_capabilities_frame(
19318                    4,
19319                    CapabilityDeclarations {
19320                        provides: Vec::new(),
19321                        requires: Vec::new(),
19322                        must_never_reach: Vec::new(),
19323                    },
19324                ),
19325            )
19326            .await
19327            .expect("claim removal catalog.update succeeds");
19328        assert_eq!(
19329            forwarding.active_binding_count().unwrap(),
19330            1,
19331            "removing an attested target claim must leave the route census unchanged"
19332        );
19333        assert!(
19334            client_rx.try_recv().is_err(),
19335            "claim removal must not emit route.closed or a client route GOODBYE"
19336        );
19337        assert!(
19338            target_rx.try_recv().is_err(),
19339            "claim removal must not send the target a route GOODBYE"
19340        );
19341    }
19342
19343    /// A direct client may open a route to a denied capability provider; this
19344    /// policy applies only to attested supervised module origins, not to direct clients.
19345    #[tokio::test]
19346    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19347        let registry = Arc::new(Registry::default());
19348        let forwarding = Arc::new(ForwardingTable::default());
19349        let supervisor = SupervisorHandle::new();
19350        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19351        let handler =
19352            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19353                .with_supervisor(supervisor);
19354        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19355        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19356        register_capability_manifest(
19357            &handler,
19358            &target_ctx,
19359            &mut target_rx,
19360            capability_manifest("target", &["credentials-provider/v1"], &[]),
19361            1,
19362        )
19363        .await;
19364        register_capability_manifest(
19365            &handler,
19366            &opener_ctx,
19367            &mut opener_rx,
19368            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19369            2,
19370        )
19371        .await;
19372
19373        let (_client_rx, bind) = open_route_for_capability_test(
19374            &handler,
19375            &target_ctx,
19376            &mut target_rx,
19377            742,
19378            3,
19379            "target",
19380            None,
19381        )
19382        .await;
19383        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19384            panic!("direct scope-honesty route must bind");
19385        };
19386        assert_eq!(principal, Some(Principal::Direct));
19387        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19388    }
19389
19390    /// A module that denies a capability receives no self-route exemption when it
19391    /// also attestedly provides that capability.
19392    #[tokio::test]
19393    async fn must_never_reach_self_route_is_capability_forbidden() {
19394        let registry = Arc::new(Registry::default());
19395        let forwarding = Arc::new(ForwardingTable::default());
19396        let supervisor = SupervisorHandle::new();
19397        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19398        let handler =
19399            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19400                .with_supervisor(supervisor);
19401        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19402        register_capability_manifest(
19403            &handler,
19404            &self_ctx,
19405            &mut self_rx,
19406            capability_manifest(
19407                "self-provider",
19408                &["credentials-provider/v1"],
19409                &["credentials-provider/v1"],
19410            ),
19411            1,
19412        )
19413        .await;
19414
19415        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19416        let replies = handler
19417            .handle_control_frame(
19418                &client_ctx,
19419                route_open_frame_with_admission_facts(
19420                    2,
19421                    "self-provider",
19422                    unique_project_root("admission-facts"),
19423                    Some(ConsumerIdentity {
19424                        module_id: "self-provider".to_string(),
19425                        launch_nonce: "self-nonce".to_string(),
19426                    }),
19427                    None,
19428                ),
19429            )
19430            .await
19431            .expect("self-route refusal returns a typed frame");
19432        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19433        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19434        assert!(
19435            self_rx.try_recv().is_err(),
19436            "self denial must not relay route.bind"
19437        );
19438    }
19439
19440    #[test]
19441    fn unsupported_channel_zero_frame_returns_error() {
19442        let handler = ControlHandler::default();
19443        let request = Frame::build(
19444            FrameType::Request,
19445            control_flags(),
19446            0,
19447            0,
19448            21,
19449            b"opaque".to_vec(),
19450        )
19451        .unwrap();
19452
19453        let response = handler
19454            .handle_control(ConnectionId::new(1), request)
19455            .unwrap();
19456
19457        assert_eq!(response[0].header.ty, FrameType::Error);
19458        assert_eq!(
19459            parse_error(&response[0])["code"],
19460            "unsupported_control_frame"
19461        );
19462    }
19463
19464    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19465    /// a swap is not wired yet, so the candidate is registered here directly
19466    /// into the registry and forwarding candidate slots, the way the swap's
19467    /// HELLO admission will.
19468    mod swap {
19469        use super::*;
19470
19471        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19472        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19473
19474        struct Swap {
19475            registry: Arc<Registry>,
19476            forwarding: Arc<ForwardingTable>,
19477            handler: ControlHandler,
19478            incumbent_ctx: RouteCtx,
19479            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19480            candidate_ctx: RouteCtx,
19481            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19482        }
19483
19484        async fn swap_with_incumbent() -> Swap {
19485            let registry = Arc::new(Registry::default());
19486            let forwarding = Arc::new(ForwardingTable::default());
19487            let handler =
19488                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19489            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19490            hello_via_sink(
19491                &handler,
19492                &incumbent_ctx,
19493                &mut incumbent_rx,
19494                hello_frame("aft", PROTOCOL_VERSION, 7),
19495            )
19496            .await;
19497            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19498            Swap {
19499                registry,
19500                forwarding,
19501                handler,
19502                incumbent_ctx,
19503                incumbent_rx,
19504                candidate_ctx,
19505                candidate_rx,
19506            }
19507        }
19508
19509        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19510            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19511            candidate_manifest.ready = ready;
19512            let registration = swap
19513                .registry
19514                .register_candidate_with_control_ops(
19515                    candidate_manifest,
19516                    PROTOCOL_VERSION,
19517                    CANDIDATE,
19518                    module_baseline_control_ops(),
19519                )
19520                .unwrap();
19521            swap.forwarding
19522                .register_candidate_module_connection(
19523                    CANDIDATE,
19524                    "aft".to_string(),
19525                    PROTOCOL_VERSION,
19526                    manifest_concurrency(&registration.manifest),
19527                    swap.candidate_ctx.egress.clone(),
19528                )
19529                .unwrap();
19530        }
19531
19532        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19533            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19534            swap.registry.promote_candidate("aft").unwrap().unwrap();
19535            cutover.incumbent.unwrap()
19536        }
19537
19538        /// A swap candidate's HELLO reserves its candidate registry entry
19539        /// before installing its candidate forwarding endpoint. The swap
19540        /// supervisor promotes a ready candidate as soon as it reads it as
19541        /// registered, and promotion cuts forwarding over to the candidate
19542        /// endpoint, so the lookup the supervisor reads
19543        /// (`Registry::published_registration`) must not return the candidate
19544        /// until that endpoint exists. Otherwise the cutover finds no candidate
19545        /// endpoint and the swap fails as if the candidate had disconnected.
19546        #[tokio::test]
19547        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19548            let mut swap = swap_with_incumbent().await;
19549            let hold = Arc::new(std::sync::Barrier::new(2));
19550            let handler = swap
19551                .handler
19552                .clone()
19553                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19554            handler
19555                .supervisor
19556                .open_swap("aft", "candidate-nonce".to_string());
19557            let hello = {
19558                let handler = handler.clone();
19559                let candidate_ctx = swap.candidate_ctx.clone();
19560                std::thread::spawn(move || {
19561                    handler
19562                        .handle_hello(
19563                            candidate_ctx.connection_id,
19564                            Some(candidate_ctx.egress.clone()),
19565                            hello_frame_with_nonce(
19566                                "aft",
19567                                PROTOCOL_VERSION,
19568                                8,
19569                                Some("candidate-nonce"),
19570                            ),
19571                        )
19572                        .unwrap()
19573                })
19574            };
19575
19576            hold.wait();
19577            // Parked: the candidate slot is claimed but not published, and
19578            // forwarding has no candidate endpoint.
19579            assert!(swap
19580                .registry
19581                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19582                .unwrap()
19583                .is_some());
19584            assert!(swap
19585                .registry
19586                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19587                .unwrap()
19588                .is_none());
19589            assert!(swap
19590                .forwarding
19591                .module_endpoint_for_connection(CANDIDATE)
19592                .unwrap()
19593                .is_none());
19594
19595            hold.wait();
19596            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19597            assert_eq!(
19598                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19599                FrameType::HelloAck
19600            );
19601            let published = swap
19602                .registry
19603                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19604                .unwrap()
19605                .expect("candidate is published once its HELLO completes");
19606            assert_eq!(published.connection_id, CANDIDATE);
19607            assert!(swap
19608                .forwarding
19609                .module_endpoint_for_connection(CANDIDATE)
19610                .unwrap()
19611                .is_some());
19612        }
19613
19614        #[tokio::test]
19615        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19616            let mut swap = swap_with_incumbent().await;
19617            let hold = Arc::new(std::sync::Barrier::new(2));
19618            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19619            swap.handler
19620                .supervisor
19621                .open_swap("aft", "candidate-nonce".to_string());
19622            let hello = {
19623                let handler = swap.handler.clone();
19624                let candidate_ctx = swap.candidate_ctx.clone();
19625                std::thread::spawn(move || {
19626                    handler
19627                        .handle_hello(
19628                            CANDIDATE,
19629                            Some(candidate_ctx.egress),
19630                            hello_frame_with_nonce(
19631                                "aft",
19632                                PROTOCOL_VERSION,
19633                                8,
19634                                Some("candidate-nonce"),
19635                            ),
19636                        )
19637                        .unwrap()
19638                })
19639            };
19640            hold.wait();
19641            assert_eq!(
19642                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19643                FrameType::HelloAck
19644            );
19645            let reader_registry = Arc::clone(&swap.registry);
19646            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19647                reader_registry
19648                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19649                    .unwrap()
19650            });
19651            assert!(hello.join().unwrap().is_empty());
19652            assert_eq!(
19653                published
19654                    .expect("ACK makes candidate publication visible")
19655                    .connection_id,
19656                CANDIDATE
19657            );
19658            assert_eq!(
19659                swap.registry.generation().unwrap(),
19660                1,
19661                "candidate is not a second catalog entry"
19662            );
19663        }
19664
19665        #[tokio::test]
19666        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19667            let mut swap = swap_with_incumbent().await;
19668            let hold = Arc::new(std::sync::Barrier::new(2));
19669            let handler = swap
19670                .handler
19671                .clone()
19672                .with_hello_registry_to_forwarding_hold(hold.clone());
19673            handler
19674                .supervisor
19675                .open_swap("aft", "candidate-nonce".into());
19676            let hello = {
19677                let handler = handler.clone();
19678                let ctx = swap.candidate_ctx.clone();
19679                std::thread::spawn(move || {
19680                    handler
19681                        .handle_hello(
19682                            CANDIDATE,
19683                            Some(ctx.egress),
19684                            hello_frame_with_nonce(
19685                                "aft",
19686                                PROTOCOL_VERSION,
19687                                8,
19688                                Some("candidate-nonce"),
19689                            ),
19690                        )
19691                        .unwrap()
19692                })
19693            };
19694            hold.wait();
19695            assert_eq!(
19696                swap.registry
19697                    .deregister_connection(CANDIDATE)
19698                    .unwrap()
19699                    .len(),
19700                1
19701            );
19702            hold.wait();
19703            assert!(hello.join().unwrap().is_empty());
19704            assert_eq!(
19705                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19706                FrameType::HelloAck
19707            );
19708            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19709            assert_eq!(
19710                handler
19711                    .supervisor
19712                    .swap_hello_admission("aft", Some("candidate-nonce")),
19713                SwapHelloAdmission::Candidate,
19714                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19715            );
19716            handler.supervisor.close_swap("aft");
19717        }
19718
19719        fn keyed_total(counters: &Value, key: &str) -> u64 {
19720            counters[key]
19721                .as_object()
19722                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19723                .unwrap_or(0)
19724        }
19725
19726        #[tokio::test]
19727        async fn replacement_logs_old_end_and_new_admission_once() {
19728            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19729            let mut swap = swap_with_incumbent().await;
19730            swap.handler
19731                .supervisor
19732                .open_swap("aft", "candidate-nonce".to_string());
19733            hello_via_sink(
19734                &swap.handler,
19735                &swap.candidate_ctx,
19736                &mut swap.candidate_rx,
19737                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19738            )
19739            .await;
19740            cutover(&swap);
19741            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19742
19743            let captured = crate::router::test_log::captured_logs(&logs);
19744            println!("captured replacement registry logs:\n{captured}");
19745            let new_admissions: Vec<_> = captured
19746                .lines()
19747                .filter(|line| {
19748                    line.contains("connection_id=40")
19749                        && line.contains("swap candidate registered; not routable until cutover")
19750                })
19751                .collect();
19752            assert_eq!(
19753                new_admissions.len(),
19754                1,
19755                "unexpected admission logs: {captured}"
19756            );
19757            assert!(new_admissions[0].contains("module_id=aft"));
19758            assert!(new_admissions[0].contains("connection_id=40"));
19759            assert!(
19760                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19761            );
19762            assert!(new_admissions[0].contains("ready=true"));
19763
19764            let old_admissions: Vec<_> = captured
19765                .lines()
19766                .filter(|line| {
19767                    line.contains("module registered module_id=aft ")
19768                        && line.contains("connection_id=30")
19769                })
19770                .collect();
19771            assert_eq!(
19772                old_admissions.len(),
19773                1,
19774                "unexpected incumbent admission: {captured}"
19775            );
19776
19777            let old_ends: Vec<_> = captured
19778                .lines()
19779                .filter(|line| {
19780                    line.contains("connection_id=30") && line.contains("module registration ended")
19781                })
19782                .collect();
19783            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19784            assert!(old_ends[0].contains("module_id=aft"));
19785            assert!(old_ends[0].contains("connection_id=30"));
19786            assert!(old_ends[0].contains("reason=replaced"));
19787            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19788            assert_eq!(
19789                captured
19790                    .lines()
19791                    .filter(|line| line.contains("module registration promoted"))
19792                    .count(),
19793                1,
19794                "unexpected promotion logs: {captured}"
19795            );
19796        }
19797
19798        /// An ack from the incumbent for a bind it was sent before cutover,
19799        /// arriving before the incumbent is drained. The incumbent is the live
19800        /// connection carrying every other client's routes, so the ack must
19801        /// not end it: the waiting client is told to retry, the reservation is
19802        /// given back, and the incumbent is told to drop just that binding.
19803        #[tokio::test]
19804        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19805            let mut swap = swap_with_incumbent().await;
19806            let handler = swap.handler.clone();
19807
19808            // A co-tenant route, bound on the incumbent before the swap.
19809            let cotenant = ConnectionId::new(31);
19810            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19811            let (cotenant_task, cotenant_bind) = relay_route_open(
19812                &handler,
19813                cotenant,
19814                &cotenant_ctx.egress,
19815                &mut swap.incumbent_rx,
19816                100,
19817                "aft",
19818                "swap-cotenant",
19819            )
19820            .await;
19821            handler
19822                .handle_control_frame(
19823                    &swap.incumbent_ctx,
19824                    route_bind_ack(cotenant_bind.header.corr),
19825                )
19826                .await
19827                .unwrap();
19828            assert!(cotenant_task.await.unwrap().is_empty());
19829            let (cotenant_channel, cotenant_epoch) =
19830                published_route(&cotenant_rx.recv().await.unwrap());
19831
19832            // A second route.open, relayed to the incumbent and not yet acked.
19833            let caller = ConnectionId::new(32);
19834            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19835            let (caller_task, caller_bind) = relay_route_open(
19836                &handler,
19837                caller,
19838                &caller_ctx.egress,
19839                &mut swap.incumbent_rx,
19840                101,
19841                "aft",
19842                "swap-caller",
19843            )
19844            .await;
19845            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19846
19847            register_candidate(&swap, None);
19848            cutover(&swap);
19849
19850            // The incumbent acks after promotion and before any drain.
19851            let ack = handler
19852                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19853                .await;
19854            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19855            if module_loop_error.is_some() {
19856                // What the connection loop does with an untranslated router
19857                // error: end the connection, releasing every route on it.
19858                handler.cleanup_connection(INCUMBENT).unwrap();
19859            }
19860
19861            // 1. The incumbent's other routes survive.
19862            assert!(
19863                cotenant_rx.try_recv().is_err(),
19864                "the co-tenant route on the incumbent was torn down by one late ack: \
19865                 {module_loop_error:?}"
19866            );
19867            assert!(matches!(
19868                swap.forwarding
19869                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19870                    .unwrap(),
19871                DataRoute::Client(DataRouteState::Bound(_))
19872            ));
19873            assert_eq!(module_loop_error, None);
19874            assert!(swap
19875                .registry
19876                .get_module_by_connection(INCUMBENT)
19877                .unwrap()
19878                .is_some());
19879
19880            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19881            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19882                .await
19883                .expect("the incumbent is told to drop the abandoned binding")
19884                .unwrap()
19885                .frame;
19886            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19887            assert_eq!(goodbye.header.channel, abandoned_channel);
19888            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19889            assert!(swap.incumbent_rx.try_recv().is_err());
19890
19891            // 3. The waiting client gets a retryable refusal and no route.
19892            let response = caller_task.await.unwrap();
19893            assert_eq!(response.len(), 1);
19894            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19895            assert!(caller_rx.try_recv().is_err());
19896
19897            // 4. The reservation pair is given back, and the pending bind
19898            //    settled exactly once: one accepted open (the co-tenant) and one
19899            //    refused open (the caller), nothing counted twice.
19900            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19901            let counters = handler.counters().snapshot();
19902            assert_eq!(
19903                keyed_total(&counters, "route_open_accepted_by_principal"),
19904                1
19905            );
19906            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19907            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19908        }
19909
19910        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19911        /// id would resolve to the promoted candidate and every new route.open
19912        /// would be refused as reloading, leaving neither process routable.
19913        #[tokio::test]
19914        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19915            let mut swap = swap_with_incumbent().await;
19916            register_candidate(&swap, None);
19917            let incumbent = cutover(&swap);
19918            swap.forwarding
19919                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19920                .unwrap()
19921                .expect("the incumbent is still registered");
19922
19923            let client = ConnectionId::new(33);
19924            let (client_ctx, mut client_rx) = route_ctx(client);
19925            let route_handler = swap.handler.clone();
19926            let open_ctx = RouteCtx {
19927                connection_id: client,
19928                egress: client_ctx.egress.clone(),
19929            };
19930            let mut route_task = tokio::spawn(async move {
19931                route_handler
19932                    .handle_control_frame(
19933                        &open_ctx,
19934                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19935                    )
19936                    .await
19937                    .unwrap()
19938            });
19939            let bind = tokio::select! {
19940                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19941                response = &mut route_task => {
19942                    let response = response.unwrap();
19943                    panic!(
19944                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19945                        parse_error(&response[0])["code"]
19946                    );
19947                }
19948            };
19949            swap.handler
19950                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19951                .await
19952                .unwrap();
19953            assert!(route_task.await.unwrap().is_empty());
19954            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19955            match swap
19956                .forwarding
19957                .lookup_data_route(client, channel, epoch)
19958                .unwrap()
19959            {
19960                DataRoute::Client(DataRouteState::Bound(route)) => {
19961                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19962                }
19963                other => panic!("expected a bound route on the candidate, got {other:?}"),
19964            }
19965            assert!(swap.incumbent_rx.try_recv().is_err());
19966        }
19967
19968        /// A candidate declares itself ready with `catalog.update` on its own
19969        /// connection. If the connection-keyed registry lookups searched only the
19970        /// active slot, this would answer `not_registered` and the candidate
19971        /// would never become ready.
19972        #[tokio::test]
19973        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
19974            let swap = swap_with_incumbent().await;
19975            register_candidate(&swap, Some(false));
19976            let update = Frame::build(
19977                FrameType::Request,
19978                control_flags(),
19979                0,
19980                0,
19981                55,
19982                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
19983                    provides: manifest("aft", PROTOCOL_VERSION).provides,
19984                    capabilities: None,
19985                    ready: Some(true),
19986                })
19987                .unwrap(),
19988            )
19989            .unwrap();
19990
19991            let replies = swap
19992                .handler
19993                .handle_control_frame(&swap.candidate_ctx, update)
19994                .await
19995                .unwrap();
19996
19997            assert_eq!(replies.len(), 1);
19998            assert_eq!(
19999                replies[0].header.ty,
20000                FrameType::Response,
20001                "candidate catalog.update was refused: {:?}",
20002                serde_json::from_slice::<Value>(&replies[0].body).ok()
20003            );
20004            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
20005            assert_eq!(
20006                swap.registry
20007                    .get_module("aft")
20008                    .unwrap()
20009                    .unwrap()
20010                    .connection_id,
20011                INCUMBENT
20012            );
20013        }
20014    }
20015
20016    /// The HELLO gate while the supervisor has a swap open: only the nonce it
20017    /// minted for the candidate admits a second process, into the candidate
20018    /// slot, and that check runs ahead of the reserved-module gate.
20019    mod swap_admission {
20020        use super::*;
20021
20022        const INCUMBENT_NONCE: &str = "incumbent-nonce";
20023        const CANDIDATE_NONCE: &str = "candidate-nonce";
20024
20025        fn handler_with_incumbent(
20026            module_id: &str,
20027            reserved: bool,
20028        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
20029            let registry = Arc::new(Registry::default());
20030            let supervisor = SupervisorHandle::new();
20031            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
20032            if reserved {
20033                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
20034            }
20035            let handler =
20036                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
20037            let incumbent = handler
20038                .handle_control(
20039                    ConnectionId::new(1),
20040                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
20041                )
20042                .unwrap();
20043            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
20044            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
20045            (registry, supervisor, handler)
20046        }
20047
20048        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
20049        /// admits every nonce, so while a swap is open the swap gate is the only
20050        /// thing between a key-holder and the candidate slot. A nonce the
20051        /// supervisor did not mint, or none at all, is refused, and neither the
20052        /// incumbent's registration nor the candidate slot moves.
20053        #[test]
20054        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
20055            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
20056
20057            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
20058                let replies = handler
20059                    .handle_control(
20060                        ConnectionId::new(connection),
20061                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
20062                    )
20063                    .unwrap();
20064                assert_eq!(replies[0].header.ty, FrameType::Error);
20065                assert_eq!(
20066                    parse_error(&replies[0])["code"],
20067                    "swap_token_invalid",
20068                    "nonce {nonce:?}"
20069                );
20070            }
20071            assert!(registry.get_candidate("aft").unwrap().is_none());
20072            assert_eq!(
20073                registry.get_module("aft").unwrap().unwrap().connection_id,
20074                ConnectionId::new(1)
20075            );
20076
20077            // Control: the minted token is admitted, into the candidate slot,
20078            // and only once.
20079            let admitted = handler
20080                .handle_control(
20081                    ConnectionId::new(4),
20082                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20083                )
20084                .unwrap();
20085            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20086            assert_eq!(
20087                registry
20088                    .get_candidate("aft")
20089                    .unwrap()
20090                    .unwrap()
20091                    .connection_id,
20092                ConnectionId::new(4)
20093            );
20094            assert_eq!(
20095                registry.get_module("aft").unwrap().unwrap().connection_id,
20096                ConnectionId::new(1),
20097                "the candidate must not take the active slot"
20098            );
20099            let replayed = handler
20100                .handle_control(
20101                    ConnectionId::new(5),
20102                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20103                )
20104                .unwrap();
20105            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20106
20107            // The case only this gate covers: the incumbent has died mid-swap,
20108            // so its duplicate refusal is gone too, and without the gate a
20109            // key-holder would take the id's ACTIVE slot.
20110            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20111            let squatter = handler
20112                .handle_control(
20113                    ConnectionId::new(6),
20114                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20115                )
20116                .unwrap();
20117            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20118            assert!(
20119                registry.get_module("aft").unwrap().is_none(),
20120                "a squatter took the active slot of an id being swapped"
20121            );
20122        }
20123
20124        /// Design mutation arm (iii). A reserved module's candidate presents a
20125        /// nonce the reserved gate has never seen (that gate holds the
20126        /// incumbent's), so the swap gate must run first or the candidate is
20127        /// refused `reserved_module` and a reserved module can never be swapped.
20128        #[test]
20129        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20130            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20131
20132            let replies = handler
20133                .handle_control(
20134                    ConnectionId::new(2),
20135                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20136                )
20137                .unwrap();
20138
20139            assert_eq!(
20140                replies[0].header.ty,
20141                FrameType::HelloAck,
20142                "reserved candidate refused: {:?}",
20143                serde_json::from_slice::<Value>(&replies[0].body).ok()
20144            );
20145            assert_eq!(
20146                registry
20147                    .get_candidate("vault")
20148                    .unwrap()
20149                    .unwrap()
20150                    .connection_id,
20151                ConnectionId::new(2)
20152            );
20153        }
20154
20155        /// With no swap open the gate is inert: the incumbent's reserved gate
20156        /// and duplicate refusal behave exactly as before.
20157        #[test]
20158        fn without_an_open_swap_the_ordinary_gates_decide() {
20159            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20160            supervisor.close_swap("vault");
20161
20162            let candidate = handler
20163                .handle_control(
20164                    ConnectionId::new(2),
20165                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20166                )
20167                .unwrap();
20168            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20169            let duplicate = handler
20170                .handle_control(
20171                    ConnectionId::new(3),
20172                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20173                )
20174                .unwrap();
20175            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20176            assert!(registry.get_candidate("vault").unwrap().is_none());
20177        }
20178    }
20179
20180    /// `scope.sync` and `scope.describe` through the real control handler: who
20181    /// may sync is decided by the registration and launch nonce of the module
20182    /// connection, never by the request body.
20183    mod scopes {
20184        mod close_reasons {
20185            include!("route_close_reason_tests.rs");
20186        }
20187        mod idle_tests {
20188            use super::*;
20189            include!("scope_idle_tests.rs");
20190        }
20191        mod route_open_timings {
20192            use super::*;
20193            include!("route_open_timing_tests.rs");
20194        }
20195        mod route_open_refusal_log {
20196            use super::*;
20197            include!("route_open_refusal_log_tests.rs");
20198        }
20199        mod activity {
20200            include!("activity_scope_tests.rs");
20201        }
20202        mod delta {
20203            include!("scope_handler_delta_tests.rs");
20204        }
20205        mod watch {
20206            include!("scope_watch_tests.rs");
20207        }
20208        mod call_modes {
20209            include!("scope_call_mode_tests.rs");
20210        }
20211        mod federated {
20212            include!("scope_federated_tests.rs");
20213        }
20214        mod authorize {
20215            include!("route_authorize_tests.rs");
20216        }
20217        #[tokio::test]
20218        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20219            let rig = rig().await;
20220            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20221                "s".into(),
20222                1,
20223                "tool".into(),
20224            ))
20225            .unwrap();
20226            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20227            let (direct, _rx) = wide_ctx(999);
20228            for (ctx, expected) in [
20229                (&rig.owner, FrameType::Response),
20230                (&direct, FrameType::Error),
20231            ] {
20232                let frame =
20233                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20234                        .unwrap();
20235                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20236                assert_eq!(replies[0].header.ty, expected);
20237                if expected == FrameType::Response {
20238                    let reply: subc_control::ScopeServedByReply =
20239                        serde_json::from_slice(&replies[0].body).unwrap();
20240                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20241                } else {
20242                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20243                }
20244            }
20245            let reply = call(
20246                &rig.handler,
20247                &rig.owner,
20248                &ModuleControlRequestFromModule::ScopeDescribe {
20249                    owner: Principal::Reserved {
20250                        module_id: OWNER.into(),
20251                    },
20252                    scope_ref: "s".into(),
20253                },
20254            )
20255            .await;
20256            assert!(matches!(
20257                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20258                ModuleControlResponseToModule::ScopeDescribe { .. }
20259            ));
20260        }
20261
20262        use subc_protocol::scope::{
20263            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20264            ScopeStatus,
20265        };
20266
20267        use super::*;
20268
20269        const OWNER: &str = "prefrontal-core";
20270
20271        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20272            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20273        }
20274
20275        async fn call(
20276            handler: &ControlHandler,
20277            ctx: &RouteCtx,
20278            request: &ModuleControlRequestFromModule,
20279        ) -> Frame {
20280            let body = serde_json::to_vec(request).unwrap();
20281            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20282            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20283            assert_eq!(replies.len(), 1, "{replies:?}");
20284            replies.pop().unwrap()
20285        }
20286
20287        async fn sync(
20288            handler: &ControlHandler,
20289            ctx: &RouteCtx,
20290            generation: u64,
20291            scopes: Vec<ScopeRecord>,
20292        ) -> Result<ModuleControlResponseToModule, String> {
20293            let reply = call(
20294                handler,
20295                ctx,
20296                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20297            )
20298            .await;
20299            match reply.header.ty {
20300                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20301                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20302            }
20303        }
20304
20305        async fn describe(
20306            handler: &ControlHandler,
20307            ctx: &RouteCtx,
20308            owner: &str,
20309            scope_ref: &str,
20310        ) -> ModuleControlResponseToModule {
20311            let reply = call(
20312                handler,
20313                ctx,
20314                &ModuleControlRequestFromModule::ScopeDescribe {
20315                    owner: Principal::Reserved {
20316                        module_id: owner.to_string(),
20317                    },
20318                    scope_ref: scope_ref.to_string(),
20319                },
20320            )
20321            .await;
20322            assert_eq!(
20323                reply.header.ty,
20324                FrameType::Response,
20325                "{:?}",
20326                parse_error(&reply)
20327            );
20328            serde_json::from_slice(&reply.body).unwrap()
20329        }
20330
20331        #[tokio::test]
20332        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20333            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20334            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20335            let mut rig = rig().await;
20336            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20337                .await;
20338            let _bound = rig
20339                .bound(
20340                    Some(AFT),
20341                    PLEXUS,
20342                    Some(
20343                        rig.selector("s", Some(1))
20344                            .with_bind_proof(Some(PROOF.into())),
20345                    ),
20346                )
20347                .await;
20348            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20349            let output = serde_json::to_string(&reply).unwrap();
20350            assert!(output.contains("\"status\":\"live\""));
20351            assert!(!output.contains(PROOF));
20352            assert!(!output.contains(HASH));
20353        }
20354
20355        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20356        async fn module(
20357            handler: &ControlHandler,
20358            connection: u64,
20359            module_id: &str,
20360            nonce: Option<&str>,
20361        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20362            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20363            hello_via_sink(
20364                handler,
20365                &ctx,
20366                &mut rx,
20367                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20368            )
20369            .await;
20370            (ctx, rx)
20371        }
20372
20373        /// `direct` and every other client connection has no registration, so
20374        /// it can neither sync nor own a scope.
20375        #[tokio::test]
20376        async fn a_client_connection_cannot_sync_or_describe() {
20377            let handler = ControlHandler::new(Arc::new(Registry::default()));
20378            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20379            for request in [
20380                ModuleControlRequestFromModule::ScopeSync {
20381                    generation: 1,
20382                    scopes: vec![head("s", 1)],
20383                },
20384                ModuleControlRequestFromModule::ScopeDescribe {
20385                    owner: Principal::Direct,
20386                    scope_ref: "s".to_string(),
20387                },
20388            ] {
20389                let reply = call(&handler, &ctx, &request).await;
20390                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20391            }
20392            assert!(
20393                !handler
20394                    .scopes
20395                    .read()
20396                    .unwrap()
20397                    .describe(
20398                        &Principal::Reserved {
20399                            module_id: OWNER.to_string()
20400                        },
20401                        "s"
20402                    )
20403                    .owner_synced
20404            );
20405        }
20406
20407        /// A module the supervisor did not spawn registers without a launch
20408        /// nonce, so it is never an owner's current launch.
20409        #[tokio::test]
20410        async fn a_module_without_a_supervised_launch_cannot_sync() {
20411            let handler = ControlHandler::new(Arc::new(Registry::default()));
20412            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20413            assert_eq!(
20414                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20415                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20416            );
20417        }
20418
20419        #[tokio::test]
20420        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20421            let supervisor = SupervisorHandle::new();
20422            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20423            let handler = ControlHandler::new(Arc::new(Registry::default()))
20424                .with_supervisor(supervisor.clone());
20425            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20426            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20427                .await
20428                .expect("the current launch syncs");
20429
20430            // A swap candidate registers with the swap token and is refused
20431            // while the incumbent keeps syncing.
20432            supervisor.open_swap(OWNER, "n2".to_string());
20433            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20434            assert_eq!(
20435                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20436                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20437            );
20438            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20439                .await
20440                .expect("the serving owner syncs during the swap");
20441
20442            // The swap fails and is rolled back. The candidate never held sync
20443            // authority, and still cannot sync.
20444            supervisor.close_swap(OWNER);
20445            assert_eq!(
20446                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20447                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20448            );
20449            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20450                .await
20451                .expect("the serving owner syncs after the rollback");
20452            handler.cleanup_connection(candidate.connection_id).unwrap();
20453
20454            // A swap that cuts over. Promotion records the candidate's nonce as
20455            // the module's spawn nonce, which is what `set_spawn_nonce` does
20456            // here; the promoted connection then takes authority at any
20457            // generation and the superseded incumbent is refused.
20458            supervisor.open_swap(OWNER, "n3".to_string());
20459            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20460            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20461            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20462                .await
20463                .expect("the promoted launch takes authority");
20464            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20465                panic!("unexpected reply {reply:?}");
20466            };
20467            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20468            assert_eq!(
20469                sync(&handler, &incumbent, 4, Vec::new()).await,
20470                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20471            );
20472        }
20473
20474        /// Authority dies with its connection: the cleanup path releases it,
20475        /// so the owner's next connection takes it at any generation.
20476        #[tokio::test]
20477        async fn closing_the_authority_connection_frees_sync_authority() {
20478            let supervisor = SupervisorHandle::new();
20479            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20480            let handler = ControlHandler::new(Arc::new(Registry::default()))
20481                .with_supervisor(supervisor.clone());
20482            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20483            sync(&handler, &first, 10, vec![head("s", 1)])
20484                .await
20485                .unwrap();
20486            handler.cleanup_connection(first.connection_id).unwrap();
20487
20488            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20489            sync(&handler, &second, 1, vec![head("s", 1)])
20490                .await
20491                .expect("the next connection takes the released authority");
20492        }
20493
20494        #[tokio::test]
20495        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20496            let supervisor = SupervisorHandle::new();
20497            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20498            let handler =
20499                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20500            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20501            sync(&handler, &first, 10, vec![head("s", 1)])
20502                .await
20503                .unwrap();
20504            handler
20505                .handle_control_frame(
20506                    &first,
20507                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20508                )
20509                .await
20510                .unwrap();
20511            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20512            sync(&handler, &second, 1, vec![head("s", 1)])
20513                .await
20514                .expect("GOODBYE releases authority even if the old socket remains open");
20515        }
20516
20517        #[tokio::test]
20518        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20519            let registry = Arc::new(Registry::default());
20520            let supervisor_handle = SupervisorHandle::new();
20521            let supervisor =
20522                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20523                    .with_handle(supervisor_handle.clone())
20524                    .with_daemon_incarnation("incarnation-7".to_string());
20525            // Configured with enabled: false, so the supervisor lists the
20526            // module without spawning a process for it.
20527            supervisor
20528                .supervise_configured(
20529                    ModuleSpec {
20530                        script: None,
20531                        carry_containment: false,
20532                        module_id: OWNER.to_string(),
20533                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20534                        args: Vec::new(),
20535                        env: Vec::new(),
20536                        reserved: false,
20537                        reserved_prefixes: Vec::new(),
20538                        protocol: ModuleProtocol::Subc,
20539                        overlap: Default::default(),
20540                    },
20541                    false,
20542                )
20543                .unwrap();
20544            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20545            let handler =
20546                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20547            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20548
20549            // Configured but not yet synced: a reader waits for the owner.
20550            let ModuleControlResponseToModule::ScopeDescribe {
20551                status,
20552                daemon_incarnation,
20553                owner_synced,
20554                owner_configured,
20555                scope,
20556                ..
20557            } = describe(&handler, &reader, OWNER, "s").await
20558            else {
20559                panic!("not a describe reply");
20560            };
20561            assert_eq!(status, ScopeStatus::NotLive);
20562            assert_eq!(daemon_incarnation, "incarnation-7");
20563            assert!(!owner_synced);
20564            assert!(owner_configured);
20565            assert!(scope.is_none());
20566
20567            // Not a supervised module: the owner will never sync, and a reader
20568            // refuses rather than waits.
20569            let ModuleControlResponseToModule::ScopeDescribe {
20570                status,
20571                owner_configured,
20572                ..
20573            } = describe(&handler, &reader, "ghost", "s").await
20574            else {
20575                panic!("not a describe reply");
20576            };
20577            assert_eq!(status, ScopeStatus::NotLive);
20578            assert!(!owner_configured);
20579
20580            // Live, with the stamp fields and the computed owner_authorized.
20581            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20582            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20583            let ModuleControlResponseToModule::ScopeDescribe {
20584                status,
20585                scope_epoch,
20586                owner_synced,
20587                scope,
20588                ..
20589            } = describe(&handler, &reader, OWNER, "s").await
20590            else {
20591                panic!("not a describe reply");
20592            };
20593            assert_eq!(status, ScopeStatus::Live);
20594            assert_eq!(scope_epoch, Some(4));
20595            assert!(owner_synced);
20596            let stamp = scope.expect("a live scope carries its stamp");
20597            assert!(
20598                stamp.owner_authorized,
20599                "prefrontal-core is the default authority"
20600            );
20601            assert_eq!(stamp.kind, ScopeKind::Head);
20602        }
20603
20604        #[tokio::test]
20605        async fn scope_authority_owners_decides_owner_authorized() {
20606            let supervisor = SupervisorHandle::new();
20607            supervisor.set_spawn_nonce("broca", "b1".to_string());
20608            let handler = ControlHandler::new(Arc::new(Registry::default()))
20609                .with_supervisor(supervisor)
20610                .with_scope_authority_owners(vec!["broca".to_string()]);
20611            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20612            let mut gated = head("s", 1);
20613            gated.attributes.agent_id = Some("agent".to_string());
20614            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20615            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20616                describe(&handler, &broca, "broca", "s").await
20617            else {
20618                panic!("not a describe reply");
20619            };
20620            assert!(scope.unwrap().owner_authorized);
20621        }
20622
20623        /// With route admission, the stamp, the commit re-check and drains in
20624        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20625        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20626        #[tokio::test]
20627        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20628            let handler = ControlHandler::new(Arc::new(Registry::default()));
20629            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20630            let ack = hello_via_sink(
20631                &handler,
20632                &ctx,
20633                &mut rx,
20634                hello_frame("m", PROTOCOL_VERSION, 1),
20635            )
20636            .await;
20637            let ack = parse_ack(&ack);
20638            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20639                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20640            }
20641            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20642
20643            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20644            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20645            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20646            let reply = handler
20647                .handle_control_frame(&client, frame)
20648                .await
20649                .unwrap()
20650                .pop()
20651                .unwrap();
20652            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20653                serde_json::from_slice(&reply.body).unwrap()
20654            else {
20655                panic!("not a server.describe reply");
20656            };
20657            assert!(
20658                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20659                "{capabilities:?}"
20660            );
20661        }
20662
20663        // ---- route admission, stamps, commit re-check and drains ----------
20664
20665        const PLEXUS: &str = "plexus";
20666        const OTHER: &str = "other";
20667        const AFT: &str = "aft";
20668        const BROCA: &str = "broca";
20669        const MAGIC: &str = "magic-context";
20670
20671        fn nonce(module_id: &str) -> String {
20672            format!("nonce-{module_id}")
20673        }
20674
20675        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20676            let (tx, rx) = mpsc::channel(64);
20677            (
20678                RouteCtx {
20679                    connection_id: ConnectionId::new(connection),
20680                    egress: FrameSink::new(tx),
20681                },
20682                rx,
20683            )
20684        }
20685
20686        /// A daemon with a configured owner (prefrontal-core) registered on its
20687        /// own module connection, two routable targets (plexus, other), and
20688        /// launch nonces minted for the modules that open routes as carriers.
20689        struct Rig {
20690            handler: ControlHandler,
20691            forwarding: Arc<ForwardingTable>,
20692            owner: RouteCtx,
20693            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20694            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20695            generation: u64,
20696            next_connection: u64,
20697            _supervisor: Supervisor,
20698        }
20699
20700        async fn rig() -> Rig {
20701            rig_with_flow_support(true).await
20702        }
20703
20704        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20705            rig_with_scope_capabilities(flow_support, false).await
20706        }
20707
20708        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20709            let mut provides = Vec::new();
20710            if flow_support {
20711                provides.push("flow-scopes/v1");
20712            }
20713            if run_support {
20714                provides.push("agent-run-scopes/v1");
20715            }
20716            rig_with_target_capabilities(&provides).await
20717        }
20718
20719        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20720            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20721            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20722            // Decoder versions alone cannot admit scoped calls: only a capability
20723            // declaration promises the required run or flow behaviour.
20724            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20725            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20726            Frame::build(
20727                FrameType::Hello,
20728                control_flags(),
20729                0,
20730                0,
20731                connection,
20732                serde_json::to_vec(&body).unwrap(),
20733            )
20734            .unwrap()
20735        }
20736
20737        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20738            let registry = Arc::new(Registry::default());
20739            let forwarding = Arc::new(ForwardingTable::default());
20740            let supervisor_handle = SupervisorHandle::new();
20741            let supervisor =
20742                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20743                    .with_handle(supervisor_handle.clone());
20744            supervisor
20745                .supervise_configured(
20746                    ModuleSpec {
20747                        script: None,
20748                        carry_containment: false,
20749                        module_id: OWNER.to_string(),
20750                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20751                        args: Vec::new(),
20752                        env: Vec::new(),
20753                        reserved: false,
20754                        reserved_prefixes: Vec::new(),
20755                        protocol: ModuleProtocol::Subc,
20756                        overlap: Default::default(),
20757                    },
20758                    false,
20759                )
20760                .unwrap();
20761            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20762                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20763            }
20764            let handler =
20765                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20766                    .with_supervisor(supervisor_handle);
20767            let (owner, mut owner_rx) = wide_ctx(1);
20768            hello_via_sink(
20769                &handler,
20770                &owner,
20771                &mut owner_rx,
20772                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20773            )
20774            .await;
20775            let mut modules = BTreeMap::new();
20776            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20777                let (ctx, mut rx) = wide_ctx(connection);
20778                let hello = hello_with_capabilities(module_id, connection, provides);
20779                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20780                modules.insert(module_id.to_string(), (ctx, rx));
20781            }
20782            Rig {
20783                handler,
20784                forwarding,
20785                owner,
20786                _owner_rx: owner_rx,
20787                modules,
20788                generation: 0,
20789                next_connection: 100,
20790                _supervisor: supervisor,
20791            }
20792        }
20793
20794        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20795            ScopeCarrier::new(Principal::Reserved {
20796                module_id: module_id.to_string(),
20797            })
20798            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20799        }
20800
20801        /// The scope most tests open under: aft carries to any module, broca
20802        /// only to plexus and other, and the owner delegates as agent-1.
20803        fn session(scope_epoch: u64) -> ScopeRecord {
20804            let mut record = head("s", scope_epoch);
20805            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20806            record.attributes.agent_id = Some("agent-1".to_string());
20807            record.attributes.delegates = true;
20808            record
20809        }
20810
20811        impl Rig {
20812            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20813                self.generation += 1;
20814                sync(&self.handler, &self.owner, self.generation, scopes)
20815                    .await
20816                    .expect("the owner's sync is accepted");
20817            }
20818
20819            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20820                ScopeSelector::new(
20821                    Principal::Reserved {
20822                        module_id: OWNER.to_string(),
20823                    },
20824                    scope_ref.to_string(),
20825                    scope_epoch,
20826                )
20827            }
20828
20829            fn open_frame(
20830                &mut self,
20831                opener: Option<&str>,
20832                target: &str,
20833                scope: Option<ScopeSelector>,
20834            ) -> (
20835                RouteCtx,
20836                mpsc::Receiver<crate::router::OutboundFrame>,
20837                Frame,
20838            ) {
20839                self.next_connection += 1;
20840                let (ctx, rx) = wide_ctx(self.next_connection);
20841                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20842                    busy_refusals: None,
20843                    target: RouteTarget::ToolProvider {
20844                        module_id: target.to_string(),
20845                    },
20846                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20847                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20848                        module_id: module_id.to_string(),
20849                        launch_nonce: nonce(module_id),
20850                    }),
20851                    consumer_capabilities: None,
20852                    role_versions: None,
20853                    admission_facts: None,
20854                    scope,
20855                })
20856                .unwrap();
20857                let frame = Frame::build(
20858                    FrameType::Request,
20859                    control_flags(),
20860                    0,
20861                    0,
20862                    self.next_connection,
20863                    body,
20864                )
20865                .unwrap();
20866                (ctx, rx, frame)
20867            }
20868
20869            /// Open and expect a refusal before anything is relayed.
20870            async fn refused(
20871                &mut self,
20872                opener: Option<&str>,
20873                target: &str,
20874                scope: Option<ScopeSelector>,
20875            ) -> String {
20876                self.refusal_body(opener, target, scope).await["code"]
20877                    .as_str()
20878                    .unwrap()
20879                    .to_string()
20880            }
20881
20882            async fn refusal_body(
20883                &mut self,
20884                opener: Option<&str>,
20885                target: &str,
20886                scope: Option<ScopeSelector>,
20887            ) -> Value {
20888                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20889                let replies = tokio::time::timeout(
20890                    Duration::from_secs(2),
20891                    self.handler.handle_control_frame(&ctx, frame),
20892                )
20893                .await
20894                .expect("the open must be refused before waiting for a bind ack")
20895                .unwrap();
20896                assert_eq!(replies.len(), 1, "{replies:?}");
20897                assert_eq!(replies[0].header.ty, FrameType::Error);
20898                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20899                assert!(
20900                    module_rx.try_recv().is_err(),
20901                    "a refused open relays nothing"
20902                );
20903                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20904                parse_error(&replies[0])
20905            }
20906
20907            /// Start an open and return its task and the bind the target got.
20908            async fn relayed(
20909                &mut self,
20910                opener: Option<&str>,
20911                target: &str,
20912                scope: Option<ScopeSelector>,
20913            ) -> Relayed {
20914                self.relayed_with_legacy_root(opener, target, scope, None)
20915                    .await
20916            }
20917
20918            async fn relayed_with_legacy_root(
20919                &mut self,
20920                opener: Option<&str>,
20921                target: &str,
20922                scope: Option<ScopeSelector>,
20923                legacy_root: Option<&std::path::Path>,
20924            ) -> Relayed {
20925                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20926                if let Some(root) = legacy_root {
20927                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20928                    body["identity"]["project_root"] = serde_json::json!(root);
20929                    frame.body = serde_json::to_vec(&body).unwrap();
20930                }
20931                let handler = self.handler.clone();
20932                let task_ctx = ctx.clone();
20933                let task = tokio::spawn(async move {
20934                    handler
20935                        .handle_control_frame(&task_ctx, frame)
20936                        .await
20937                        .unwrap()
20938                });
20939                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20940                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20941                    .await
20942                    .expect("the target receives the relayed route.bind")
20943                    .unwrap()
20944                    .frame;
20945                Relayed {
20946                    target: target.to_string(),
20947                    client: ctx,
20948                    client_rx: rx,
20949                    task,
20950                    bind,
20951                }
20952            }
20953
20954            async fn ack(&self, relayed: &Relayed) {
20955                let (module, _) = &self.modules[&relayed.target];
20956                self.handler
20957                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20958                    .await
20959                    .unwrap();
20960            }
20961
20962            /// Open, ack and return the bound route.
20963            async fn bound(
20964                &mut self,
20965                opener: Option<&str>,
20966                target: &str,
20967                scope: Option<ScopeSelector>,
20968            ) -> Bound {
20969                let relayed = self.relayed(opener, target, scope).await;
20970                self.commit_relayed(relayed).await
20971            }
20972
20973            async fn bound_with_legacy_root(
20974                &mut self,
20975                opener: Option<&str>,
20976                target: &str,
20977                scope: Option<ScopeSelector>,
20978                root: &std::path::Path,
20979            ) -> Bound {
20980                let relayed = self
20981                    .relayed_with_legacy_root(opener, target, scope, Some(root))
20982                    .await;
20983                self.commit_relayed(relayed).await
20984            }
20985
20986            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
20987                self.ack(&relayed).await;
20988                let Relayed {
20989                    target,
20990                    client,
20991                    mut client_rx,
20992                    task,
20993                    bind,
20994                } = relayed;
20995                assert!(
20996                    task.await.unwrap().is_empty(),
20997                    "the open is answered by commit"
20998                );
20999                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
21000                Bound {
21001                    target,
21002                    client,
21003                    client_rx,
21004                    channel,
21005                    epoch,
21006                    bind,
21007                }
21008            }
21009
21010            fn live(&self, route: &Bound) -> bool {
21011                matches!(
21012                    self.forwarding
21013                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21014                        .unwrap(),
21015                    DataRoute::Client(DataRouteState::Bound(_))
21016                )
21017            }
21018        }
21019
21020        struct Relayed {
21021            target: String,
21022            client: RouteCtx,
21023            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21024            task: tokio::task::JoinHandle<Vec<Frame>>,
21025            bind: Frame,
21026        }
21027
21028        struct Bound {
21029            target: String,
21030            client: RouteCtx,
21031            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21032            channel: u16,
21033            epoch: u32,
21034            bind: Frame,
21035        }
21036
21037        impl Bound {
21038            /// The reason of the `route.closed` this client was sent, after
21039            /// checking it also got a GOODBYE on exactly this route.
21040            fn closed_reason(&mut self) -> RouteCloseReason {
21041                let mut reason = None;
21042                let mut goodbye = false;
21043                while let Ok(outbound) = self.client_rx.try_recv() {
21044                    let frame = outbound.frame;
21045                    match frame.header.ty {
21046                        FrameType::Goodbye => {
21047                            assert_eq!(
21048                                (frame.header.channel, frame.header.epoch),
21049                                (self.channel, self.epoch)
21050                            );
21051                            goodbye = true;
21052                        }
21053                        FrameType::Push => {
21054                            let ClientControlPush::RouteClosed {
21055                                reason: r,
21056                                module_id,
21057                                ..
21058                            } = serde_json::from_slice(&frame.body).unwrap()
21059                            else {
21060                                panic!("unexpected push");
21061                            };
21062                            assert_eq!(module_id, self.target);
21063                            reason = Some(r);
21064                        }
21065                        other => panic!("unexpected frame {other:?}"),
21066                    }
21067                }
21068                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21069                reason.expect("the client is told why the route closed")
21070            }
21071
21072            fn untouched(&mut self) -> bool {
21073                self.client_rx.try_recv().is_err()
21074            }
21075
21076            fn stamp(&self) -> Option<ScopeStamp> {
21077                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21078                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21079                    other => panic!("expected a route.bind, got {other:?}"),
21080                }
21081            }
21082        }
21083
21084        #[tokio::test]
21085        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21086        ) {
21087            let mut rig = rig().await;
21088            let mut record = session(1);
21089            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21090            record.child_owners = vec![Principal::Reserved {
21091                module_id: MAGIC.to_string(),
21092            }];
21093            rig.sync(vec![record]).await;
21094            let scope = || Some(rig_selector("s", Some(1)));
21095
21096            // Admitted: the owner, a bare carrier to any module, a targeted
21097            // carrier to its listed module.
21098            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21099            rig.bound(Some(AFT), OTHER, scope()).await;
21100            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21101
21102            // Refused scope_not_carrier: a targeted carrier to an unlisted
21103            // module, a module that is not listed at all (a child owner is not
21104            // a carrier), and a direct key-holder.
21105            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21106                assert_eq!(
21107                    rig.refused(opener, target, scope()).await,
21108                    error_codes::SCOPE_NOT_CARRIER,
21109                    "{opener:?} -> {target}"
21110                );
21111            }
21112        }
21113
21114        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21115            ScopeSelector::new(
21116                Principal::Reserved {
21117                    module_id: OWNER.to_string(),
21118                },
21119                scope_ref.to_string(),
21120                scope_epoch,
21121            )
21122        }
21123
21124        #[tokio::test]
21125        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21126            let mut rig = rig().await;
21127            rig.sync(vec![session(1)]).await;
21128            for opener in [OWNER, AFT] {
21129                assert_eq!(
21130                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21131                        .await,
21132                    error_codes::SCOPE_EPOCH_REQUIRED,
21133                    "{opener}"
21134                );
21135            }
21136        }
21137
21138        #[tokio::test]
21139        async fn admission_separates_not_synced_not_live_and_ended() {
21140            let mut rig = rig().await;
21141            // Before the configured owner's first sync: retryable.
21142            let code = rig
21143                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21144                .await;
21145            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21146            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21147
21148            // An owner that is not configured will never sync: terminal.
21149            let ghost = ScopeSelector::new(
21150                Principal::Reserved {
21151                    module_id: "ghost".to_string(),
21152                },
21153                "s".to_string(),
21154                Some(1),
21155            );
21156            assert_eq!(
21157                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21158                error_codes::SCOPE_NOT_LIVE
21159            );
21160
21161            rig.sync(vec![session(2)]).await;
21162            assert_eq!(
21163                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21164                    .await,
21165                error_codes::SCOPE_NOT_LIVE
21166            );
21167            for epoch in [1, 3] {
21168                assert_eq!(
21169                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21170                        .await,
21171                    error_codes::SCOPE_ENDED,
21172                    "epoch {epoch}"
21173                );
21174            }
21175            // Control: the live epoch is admitted.
21176            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21177                .await;
21178        }
21179
21180        #[tokio::test]
21181        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21182            let mut rig = rig().await;
21183            rig.sync(vec![session(1)]).await;
21184            let route = rig
21185                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21186                .await;
21187            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21188            assert_eq!(stamp.scope_ref, "s");
21189            assert_eq!(stamp.scope_epoch, 1);
21190            assert_eq!(stamp.kind, ScopeKind::Head);
21191            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21192            assert!(stamp.attributes.delegates);
21193            assert!(stamp.owner_authorized);
21194            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21195            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21196
21197            // broca owns a scope of its own on its own module connection; it is
21198            // not in scope_authority_owners, so its stamp is not authorized.
21199            let (broca, mut broca_rx) = wide_ctx(50);
21200            hello_via_sink(
21201                &rig.handler,
21202                &broca,
21203                &mut broca_rx,
21204                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21205            )
21206            .await;
21207            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21208                .await
21209                .unwrap();
21210            let own = ScopeSelector::new(
21211                Principal::Reserved {
21212                    module_id: BROCA.to_string(),
21213                },
21214                "b".to_string(),
21215                Some(1),
21216            );
21217            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21218            assert!(!route.stamp().unwrap().owner_authorized);
21219        }
21220
21221        #[tokio::test]
21222        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21223            let mut rig = rig().await;
21224            let mut record = head("s", 1);
21225            record.carriers = vec![carrier(AFT, None)];
21226            let flow_id = "Flow:run-7/step_2!~";
21227            record.attributes.flow_id = Some(flow_id.to_string());
21228            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21229                .await
21230                .unwrap();
21231            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21232                panic!("not a sync reply");
21233            };
21234            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21235            let route = rig
21236                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21237                .await;
21238            assert!(rig.live(&route), "the stamped bind committed");
21239            let stamp = route.stamp().expect("a flow scope carries a stamp");
21240            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21241            assert_eq!(stamp.attributes.agent_id, None);
21242            assert!(!stamp.attributes.delegates);
21243            assert!(stamp.owner_authorized);
21244            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21245            assert_eq!(unscoped.stamp(), None);
21246        }
21247
21248        #[tokio::test]
21249        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21250            let mut rig = rig_with_flow_support(false).await;
21251            let mut record = session(1);
21252            record.attributes.flow_id = Some("flow:7".to_string());
21253            rig.sync(vec![record]).await;
21254            for opener in [OWNER, AFT] {
21255                let body = rig
21256                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21257                    .await;
21258                assert_eq!(body["code"], "target_flow_unsupported");
21259                let message = body["message"].as_str().unwrap();
21260                for required in [PLEXUS, "flow-scopes/v1"] {
21261                    assert!(message.contains(required), "{message}");
21262                }
21263            }
21264        }
21265
21266        #[tokio::test]
21267        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21268            let mut rig = rig_with_flow_support(true).await;
21269            let mut record = session(1);
21270            record.attributes.flow_id = Some("flow:7".to_string());
21271            rig.sync(vec![record]).await;
21272            for opener in [OWNER, AFT] {
21273                let route = rig
21274                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21275                    .await;
21276                assert!(rig.live(&route));
21277                assert_eq!(
21278                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21279                    Some("flow:7")
21280                );
21281            }
21282        }
21283
21284        #[tokio::test]
21285        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21286            use std::future::Future;
21287
21288            let mut rig = rig_with_flow_support(true).await;
21289            let mut record = session(1);
21290            record.attributes.flow_id = Some("flow:7".to_string());
21291            rig.sync(vec![record]).await;
21292            let (client, mut client_rx, frame) =
21293                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21294            // Hold the route-open response permit so admission sees the first
21295            // target but relay reservation cannot capture an endpoint yet.
21296            for _ in 0..64 {
21297                client.egress.try_send(route_bind_ack(1)).unwrap();
21298            }
21299            let handler = rig.handler.clone();
21300            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21301            std::future::poll_fn(|cx| {
21302                assert!(open.as_mut().poll(cx).is_pending());
21303                std::task::Poll::Ready(())
21304            })
21305            .await;
21306            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21307
21308            let old_connection = rig.modules[PLEXUS].0.connection_id;
21309            rig.handler.cleanup_connection(old_connection).unwrap();
21310            let (replacement, mut replacement_rx) = wide_ctx(200);
21311            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21312            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21313            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21314            let hello = Frame::build(
21315                FrameType::Hello,
21316                control_flags(),
21317                0,
21318                0,
21319                200,
21320                serde_json::to_vec(&body).unwrap(),
21321            )
21322            .unwrap();
21323            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21324
21325            client_rx.try_recv().unwrap();
21326            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21327                .await
21328                .expect("the replacement is refused without waiting for a bind ack")
21329                .unwrap();
21330            assert_eq!(replies.len(), 1);
21331            let body = parse_error(&replies[0]);
21332            assert_eq!(body["code"], "target_flow_unsupported");
21333            for required in [PLEXUS, "flow-scopes/v1"] {
21334                assert!(body["message"].as_str().unwrap().contains(required));
21335            }
21336            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21337            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21338            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21339            assert!(rig
21340                .handler
21341                .registry
21342                .get_module_by_connection(replacement.connection_id)
21343                .unwrap()
21344                .is_some());
21345        }
21346
21347        #[tokio::test]
21348        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21349            use std::future::Future;
21350            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21351            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21352            const NEXT_HASH: &str =
21353                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21354            let mut rig = rig().await;
21355            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21356            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21357            rig.sync(vec![record.clone()]).await;
21358            let (client, mut rx, frame) = rig.open_frame(
21359                None,
21360                PLEXUS,
21361                Some(
21362                    rig.selector("s", Some(1))
21363                        .with_bind_proof(Some(PROOF.into())),
21364                ),
21365            );
21366            // Hold egress reservation while the scope owner changes its bind-proof
21367            // hash, so a proof valid at admission must be checked again at relay.
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            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21379            rig.sync(vec![record]).await;
21380            rx.try_recv().unwrap();
21381            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21382                .await
21383                .unwrap()
21384                .unwrap();
21385            assert_eq!(
21386                parse_error(&replies[0])["code"],
21387                error_codes::SCOPE_BIND_PROOF_MISMATCH
21388            );
21389            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21390            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21391            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21392        }
21393
21394        #[tokio::test]
21395        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21396            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21397            let mut rig = rig().await;
21398            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21399                .await;
21400            for opener in [OWNER, AFT] {
21401                for proof in [None, Some("malformed+proof=")] {
21402                    let route = rig
21403                        .bound(
21404                            Some(opener),
21405                            PLEXUS,
21406                            Some(
21407                                rig.selector("s", Some(1))
21408                                    .with_bind_proof(proof.map(str::to_string)),
21409                            ),
21410                        )
21411                        .await;
21412                    assert!(rig.live(&route));
21413                }
21414            }
21415        }
21416
21417        #[tokio::test]
21418        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21419            use std::future::Future;
21420            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21421            const NEXT_HASH: &str =
21422                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21423            let mut rig = rig().await;
21424            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21425                .await;
21426            let (client, mut rx, frame) =
21427                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21428            for _ in 0..64 {
21429                client.egress.try_send(route_bind_ack(1)).unwrap();
21430            }
21431            let handler = rig.handler.clone();
21432            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21433            std::future::poll_fn(|cx| {
21434                assert!(open.as_mut().poll(cx).is_pending());
21435                std::task::Poll::Ready(())
21436            })
21437            .await;
21438            rig.sync(vec![
21439                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21440            ])
21441            .await;
21442            rx.try_recv().unwrap();
21443            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21444            let bind = std::future::poll_fn(|cx| {
21445                assert!(open.as_mut().poll(cx).is_pending());
21446                module_rx.poll_recv(cx)
21447            })
21448            .await
21449            .unwrap()
21450            .frame;
21451            handler
21452                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21453                .await
21454                .unwrap();
21455            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21456                .await
21457                .unwrap()
21458                .unwrap();
21459            assert_eq!(replies.len(), 1);
21460            // Proof rechecking allowed the relay. Independent tag settlement
21461            // still asks the opener to retry after any same-epoch content change.
21462            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21463            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21464            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21465            let route = rig
21466                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21467                .await;
21468            assert!(rig.live(&route));
21469        }
21470
21471        #[tokio::test]
21472        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21473        {
21474            let mut rig = rig_with_flow_support(false).await;
21475            rig.sync(vec![session(1)]).await;
21476            let route = rig
21477                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21478                .await;
21479            assert!(rig.live(&route));
21480            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21481            let mut record = session(1);
21482            record.attributes.flow_id = Some("flow:7".to_string());
21483            rig.sync(vec![record]).await;
21484            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21485            assert!(rig.live(&unscoped));
21486            assert_eq!(unscoped.stamp(), None);
21487        }
21488
21489        #[tokio::test]
21490        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21491            let mut rig = rig().await;
21492            let mut record = session(1);
21493            record.attributes.flow_id = Some("flow:7".to_string());
21494            rig.sync(vec![record.clone()]).await;
21495            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21496            let mut owner_route = rig
21497                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21498                .await;
21499            let mut carrier_route = rig
21500                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21501                .await;
21502            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21503            rig.sync(vec![record.clone()]).await;
21504            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21505            assert!(rig.live(&owner_route) && owner_route.untouched());
21506            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21507
21508            record.attributes.flow_id = Some("flow:8".to_string());
21509            rig.sync(vec![record]).await;
21510            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21511            let before = before.unwrap();
21512            assert_eq!(after.scope_epoch, before.scope_epoch);
21513            assert!(after.version > before.version);
21514            for route in [&mut owner_route, &mut carrier_route] {
21515                assert!(!rig.live(route));
21516                assert_eq!(
21517                    route.closed_reason(),
21518                    RouteCloseReason::ScopeDelegationChanged
21519                );
21520            }
21521            assert!(rig.live(&unscoped) && unscoped.untouched());
21522            // Each provider also receives a GOODBYE for its drained route;
21523            // consume it before expecting the next route.bind on that sink.
21524            for target in [PLEXUS, OTHER] {
21525                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21526                let goodbye = module_rx
21527                    .try_recv()
21528                    .expect("the provider sees the drain")
21529                    .frame;
21530                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21531                assert!(module_rx.try_recv().is_err());
21532            }
21533            let rebound = rig
21534                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21535                .await;
21536            assert_eq!(
21537                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21538                Some("flow:8")
21539            );
21540        }
21541
21542        /// The owner's sync lands between admission and the module's ack. The
21543        /// open is refused by name, the module's other routes stay up, and the
21544        /// reserved pair is released. Changed content is retryable; an ended
21545        /// scope is not.
21546        #[tokio::test]
21547        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21548            let mut rig = rig().await;
21549            rig.sync(vec![session(1)]).await;
21550            let mut cotenant = rig
21551                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21552                .await;
21553
21554            let mut changed = session(1);
21555            changed.child_owners.push(Principal::Reserved {
21556                module_id: MAGIC.to_string(),
21557            });
21558            let mut ended = None;
21559            for (code, next) in [
21560                (error_codes::SCOPE_CHANGED, vec![changed]),
21561                (error_codes::SCOPE_ENDED, Vec::new()),
21562            ] {
21563                let relayed = rig
21564                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21565                    .await;
21566                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21567                ended = Some(next.is_empty());
21568                rig.sync(next).await;
21569                rig.ack(&relayed).await;
21570                let replies = relayed.task.await.unwrap();
21571                assert_eq!(replies.len(), 1, "{replies:?}");
21572                assert_eq!(parse_error(&replies[0])["code"], code);
21573                assert_eq!(
21574                    subc_protocol::error_codes::is_retryable_route_open(code),
21575                    code == error_codes::SCOPE_CHANGED
21576                );
21577                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21578                // The module is told to drop just the binding it created.
21579                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21580                // Collected, because ending the scope also closes the co-tenant
21581                // route, whose GOODBYE comes first.
21582                let mut goodbyes = Vec::new();
21583                while let Ok(outbound) = plexus_rx.try_recv() {
21584                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21585                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21586                }
21587                assert!(
21588                    goodbyes.contains(&(bind_channel, bind_epoch)),
21589                    "{goodbyes:?}"
21590                );
21591                assert!(rig
21592                    .handler
21593                    .registry
21594                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21595                    .unwrap()
21596                    .is_some());
21597            }
21598            assert_eq!(ended, Some(true));
21599            // The co-tenant stayed up through the change, and closed only when
21600            // the scope ended, by the drain rule rather than by the commit.
21601            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21602        }
21603
21604        /// Each row of the drain table on one set of routes: the owner's, a
21605        /// bare carrier's, and a targeted carrier's to each of its targets.
21606        #[tokio::test]
21607        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21608            struct Case {
21609                name: &'static str,
21610                change: fn(&mut ScopeRecord),
21611                /// Closed routes by index: owner->plexus, aft->plexus,
21612                /// broca->plexus, broca->other.
21613                closed: [Option<RouteCloseReason>; 4],
21614            }
21615            use RouteCloseReason::*;
21616            let cases = [
21617                Case {
21618                    name: "a carrier entry removed",
21619                    change: |r| {
21620                        r.carriers.retain(|c| {
21621                            c.principal
21622                                != Principal::Reserved {
21623                                    module_id: AFT.to_string(),
21624                                }
21625                        })
21626                    },
21627                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21628                },
21629                Case {
21630                    name: "a target removed from a carrier",
21631                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21632                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21633                },
21634                Case {
21635                    name: "a bare carrier narrowed to targets",
21636                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21637                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21638                },
21639                Case {
21640                    name: "delegates turned off",
21641                    change: |r| r.attributes.delegates = false,
21642                    closed: [Some(ScopeDelegationChanged); 4],
21643                },
21644                Case {
21645                    name: "agent_id changed",
21646                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21647                    closed: [Some(ScopeDelegationChanged); 4],
21648                },
21649                Case {
21650                    name: "a carrier added, child owners changed, the record re-sent",
21651                    change: |r| {
21652                        r.carriers.push(carrier(MAGIC, None));
21653                        r.child_owners.push(Principal::Reserved {
21654                            module_id: MAGIC.to_string(),
21655                        });
21656                    },
21657                    closed: [None; 4],
21658                },
21659                Case {
21660                    name: "a target added",
21661                    change: |r| {
21662                        r.carriers[1]
21663                            .targets
21664                            .as_mut()
21665                            .unwrap()
21666                            .push("third".to_string())
21667                    },
21668                    closed: [None; 4],
21669                },
21670                Case {
21671                    name: "delegates turned on",
21672                    change: |r| r.attributes.delegates = true,
21673                    closed: [None; 4],
21674                },
21675            ];
21676            for case in cases {
21677                let mut rig = rig().await;
21678                rig.sync(vec![session(1)]).await;
21679                let scope = || Some(rig_selector("s", Some(1)));
21680                let mut routes = [
21681                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21682                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21683                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21684                    rig.bound(Some(BROCA), OTHER, scope()).await,
21685                ];
21686                let mut record = session(1);
21687                (case.change)(&mut record);
21688                rig.sync(vec![record]).await;
21689                for (index, expected) in case.closed.iter().enumerate() {
21690                    let route = &mut routes[index];
21691                    match expected {
21692                        Some(reason) => {
21693                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21694                            assert_eq!(
21695                                route.closed_reason(),
21696                                *reason,
21697                                "{}: route {index}",
21698                                case.name
21699                            );
21700                        }
21701                        None => {
21702                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21703                            assert!(
21704                                route.untouched(),
21705                                "{}: route {index} was told something",
21706                                case.name
21707                            );
21708                        }
21709                    }
21710                }
21711            }
21712        }
21713
21714        #[tokio::test]
21715        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21716            // Removed, and replaced by a higher epoch.
21717            for next in [Vec::new(), vec![session(2)]] {
21718                let mut rig = rig().await;
21719                rig.sync(vec![session(1)]).await;
21720                let mut route = rig
21721                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21722                    .await;
21723                rig.sync(next).await;
21724                assert!(!rig.live(&route));
21725                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21726            }
21727
21728            // A child whose parent ends: its routes close as parent-ended, the
21729            // child stays live, and routes under the parent close as ended.
21730            let mut rig = rig().await;
21731            let mut child = session(1);
21732            child.scope_ref = "child".to_string();
21733            child.kind = ScopeKind::Worker;
21734            child.parent = Some(ScopeParent::new(
21735                Principal::Reserved {
21736                    module_id: OWNER.to_string(),
21737                },
21738                "s".to_string(),
21739                1,
21740            ));
21741            rig.sync(vec![session(1), child.clone()]).await;
21742            let mut child_route = rig
21743                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21744                .await;
21745            assert_eq!(
21746                child_route.stamp().unwrap().parent_state,
21747                Some(ParentState::Linked)
21748            );
21749            rig.sync(vec![child]).await;
21750            assert!(!rig.live(&child_route));
21751            assert_eq!(
21752                child_route.closed_reason(),
21753                RouteCloseReason::ScopeParentEnded
21754            );
21755        }
21756
21757        #[tokio::test]
21758        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21759        ) {
21760            let mut rig = rig().await;
21761            rig.sync(vec![session(1)]).await;
21762            let mut route = rig
21763                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21764                .await;
21765            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21766            rig.sync(vec![session(1)]).await;
21767            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21768            assert!(rig.live(&route) && route.untouched());
21769
21770            // A call in flight on the route when another carrier is added. A
21771            // forwarded REQUEST holds one credit on the route's flow until the
21772            // module answers; the router takes it exactly like this.
21773            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21774                .forwarding
21775                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21776                .unwrap()
21777            else {
21778                panic!("the route is bound");
21779            };
21780            binding.flow.acquire_tagged(9, false).await.unwrap();
21781            let mut widened = session(1);
21782            widened.carriers.push(carrier(MAGIC, None));
21783            rig.sync(vec![widened]).await;
21784            assert!(rig.live(&route) && route.untouched());
21785            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21786            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21787            // The call's credit is still held on an open flow, so its answer
21788            // will be delivered: closing the route would have closed the flow.
21789            assert_eq!(binding.flow.in_flight(), 1);
21790            binding
21791                .flow
21792                .acquire_tagged(10, false)
21793                .await
21794                .expect("the flow is still open");
21795        }
21796
21797        /// A swap's superseded endpoint keeps its routes until drained; ending
21798        /// the scope closes them there too.
21799        #[tokio::test]
21800        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21801            let mut rig = rig().await;
21802            rig.sync(vec![session(1)]).await;
21803            let mut on_incumbent = rig
21804                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21805                .await;
21806
21807            // Swap plexus: register a candidate and cut over, leaving the
21808            // incumbent superseded with the route still on it.
21809            let (candidate, _candidate_rx) = wide_ctx(9);
21810            let registration = rig
21811                .handler
21812                .registry
21813                .register_candidate_with_control_ops(
21814                    manifest(PLEXUS, PROTOCOL_VERSION),
21815                    PROTOCOL_VERSION,
21816                    candidate.connection_id,
21817                    module_baseline_control_ops(),
21818                )
21819                .unwrap();
21820            rig.forwarding
21821                .register_candidate_module_connection(
21822                    candidate.connection_id,
21823                    PLEXUS.to_string(),
21824                    PROTOCOL_VERSION,
21825                    manifest_concurrency(&registration.manifest),
21826                    candidate.egress.clone(),
21827                )
21828                .unwrap();
21829            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21830            rig.handler
21831                .registry
21832                .promote_candidate(PLEXUS)
21833                .unwrap()
21834                .unwrap();
21835            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21836
21837            rig.sync(Vec::new()).await;
21838            assert!(!rig.live(&on_incumbent));
21839            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21840            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21841            let goodbye = incumbent_rx
21842                .try_recv()
21843                .expect("the superseded endpoint is told")
21844                .frame;
21845            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21846        }
21847    }
21848}
21849
21850#[cfg(test)]
21851mod concurrency_default_exposure_tests {
21852    use super::*;
21853
21854    fn hello_body(role_json: &str) -> Vec<u8> {
21855        format!(
21856            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":[]}}}}}}}}"#
21857        )
21858        .into_bytes()
21859    }
21860
21861    fn manifest_from(body: &[u8]) -> ModuleManifest {
21862        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21863        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21864            .expect("manifest parses")
21865    }
21866
21867    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21868
21869    #[test]
21870    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21871        let body = hello_body(&format!(
21872            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21873        ));
21874        let manifest = manifest_from(&body);
21875        // Precondition: serde really resolved it to the default, so the typed
21876        // manifest alone cannot answer the question this probe exists for.
21877        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21878        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21879    }
21880
21881    #[test]
21882    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21883        let body = hello_body(&format!(
21884            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21885        ));
21886        let manifest = manifest_from(&body);
21887        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21888        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21889    }
21890
21891    #[test]
21892    fn non_management_roles_are_never_reported() {
21893        let body = hello_body(
21894            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21895        );
21896        let manifest = manifest_from(&body);
21897        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21898    }
21899}