Skip to main content

subc_daemon/
control.rs

1#[path = "control/list_diagnostics.rs"]
2pub(crate) mod list_diagnostics;
3
4use std::{
5    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
6    fmt,
7    net::SocketAddr,
8    path::{Path, PathBuf},
9    sync::{Arc, Mutex, RwLock},
10    time::{Duration, Instant as StdInstant},
11};
12
13use crate::scopes::admission::denied_capability;
14use serde::{Deserialize, Serialize};
15use subc_control::{
16    ops, CapabilityRequirementStatus, CatalogEntry, ClientControlPush, ClientControlRequest,
17    ClientControlResponse, ConsumerIdentity, DaemonBuildProvenance, DaemonObservedProcess,
18    ModuleDeclaredProvenance, ModuleProtocol, NotReadyReason, PendingReloadVerdict, PollKind,
19    ReloadPathAgreement, ReloadPathUnavailableReason, RouteCloseReason, SpawnCursor,
20    StderrCaptureState, StderrTail, StderrTailEntry, SupervisorDaemonProvenance, SupervisorEntry,
21    SupervisorHealthEntry, SupervisorModuleProvenance, SupervisorObservedProcess,
22    SupervisorRescanResult, SupervisorRoute, SupervisorRouteConsumer, SupervisorRouteModule,
23};
24use subc_protocol::{
25    call_mode::{derive_call_mode, CALL_MODES_CAPABILITY},
26    error_codes,
27    manifest::{
28        validate_hello_capability_grammar, validate_hello_confirm_operations,
29        validate_hello_display_name, validate_hello_event_declarations,
30        validate_hello_flow_operations, validate_hello_operation_deferral,
31        validate_hello_rich_ui_descriptor, validate_hello_role_declarations,
32        validate_hello_self_signal_declarations, validate_role_declarations_value,
33        CapabilityDeclarations, CapabilityNeed, Concurrency, ManifestProvenance, ModuleManifest,
34        ProviderRole,
35    },
36    peer::{
37        ObservedPeer, RouteBindPeer, OBSERVED_PEER_CAPABILITY, OPERATOR_APP_CAPABILITY,
38        PEER_BUILD_CAPABILITY,
39    },
40    provider_declarations::ProviderDeclarations,
41    scope::{
42        ScopeEnd, ScopeRecord, ScopeRecordOutcome, ScopeRecordResult, ScopeSelector,
43        CAP_ROUTE_ROLE_VERSIONS_V1, CAP_SCOPES_V1, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP,
44        SCOPE_SYNC_OP,
45    },
46    session::{
47        validate_role_versions, HealthReport, ModuleControlPush, ModuleControlRequest,
48        ModuleControlRequestFromModule, ModuleControlResponse, ModuleControlResponseToModule,
49        OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK, MODULE_TO_SUBC_OP_CATALOG_UPDATE,
50        MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS, ROLE_VERSIONS_FIELD,
51    },
52    BindIdentity, ErrorBody, Flags, FrameType, ModuleHelloAckBody, ModuleHelloBody, Principal,
53    Priority, RouteTarget, PROTOCOL_VERSION,
54};
55use tokio::time::{timeout_at, Instant};
56use tracing::{debug, info, instrument::WithSubscriber, warn};
57
58use crate::{
59    caller_identity::CallerIdentity,
60    capability_requirements::{
61        log_duplicate_claim_events, log_manifest_change, log_requirement_events,
62        CapabilityRequirementEvaluator, CapabilityVerdict, DuplicateClaimSource, RegisteredModule,
63        RequirementStatus, RuntimeModule,
64    },
65    child_roster::DaemonShutdownFlag,
66    daemon_config::{PrivilegedOperatorPrompt, RestartRequiredSection},
67    forwarding::{
68        CloseReason, EndpointRoute, ForwardingError, ForwardingTable, GoodbyeTarget,
69        ModuleControlRpcCompletion, ModuleControlRpcOutcome, ModuleEndpointId,
70        PendingModuleControlRpc, RouteBindRelayOutcome, RoutePollSnapshot, RouteRelease,
71    },
72    observability::{
73        ROUTE_OPEN_REFUSED_DECLARED_NOT_READY, ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
74    },
75    privileged_prompt::{prompt_text, PrivilegedOperation},
76    provenance::{
77        process_start_time, spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity,
78    },
79    registry::{ChannelState, ConnectionId, RegistrationEndReason, Registry, RegistryError},
80    router::{daemon_error_flags, RouteCtx, RouterError},
81    scopes::{HelloLaunchNonces, ScopeRecords, ScopeTable},
82    server::MAX_PENDING_ROUTE_BINDS_PER_TARGET,
83    stderr_tail::{CaptureState, TailEntry},
84    supervise::{
85        validate_spec, ModuleProcessLiveness, ReservedHelloRejection, ReservedHelloVerification,
86        SpawnSubscribeRefusal, SupervisorHandle, SwapHelloAdmission,
87    },
88    ConnectedClients, DaemonCounters, Frame, ProjectRootId, Supervisor,
89};
90
91/// Lowest envelope version this subc build will negotiate.
92///
93/// Module HELLO negotiation is exact: peers must use the daemon's locked
94/// protocol version. Older and newer peers receive `version_unsupported` and
95/// are not registered.
96pub const MIN_SUPPORTED_VERSION: u8 = PROTOCOL_VERSION;
97
98const CAP_MANIFEST_REGISTRATION: &str = "manifest_registration_v1";
99const CAP_CHANNEL_LIFECYCLE: &str = "channel_lifecycle_v1";
100const CAP_PING_PONG: &str = "ping_pong_v1";
101const CAP_SESSION_ATTACH: &str = "session_attach_v1";
102const CAP_ADMISSION_FACTS_RELAY: &str = "admission_facts_relay_v1";
103
104const SUBC_CONTROL_OPS: &[&str] = &[
105    "claim.mint",
106    "claim.present",
107    ops::DAEMON_SHUTDOWN_INTENT,
108    ops::ACTIVITY_RECORD,
109    ops::ACTIVITY_QUERY,
110    ops::ACTIVITY_SUBSCRIBE,
111    ops::SERVER_DESCRIBE,
112    ops::CATALOG_LIST,
113    ops::CATALOG_WATCH,
114    ops::ROUTE_OPEN,
115    ops::ROUTE_POLL,
116    ops::ROUTE_CLOSING,
117    ops::ROUTE_CLOSED,
118    ops::SUPERVISOR_LIST,
119    ops::SUPERVISOR_RESTART,
120    ops::SUPERVISOR_SWAP,
121    ops::SUPERVISOR_RELOAD,
122    ops::SUPERVISOR_RESCAN,
123    ops::SUPERVISOR_RELEASE_RESERVED,
124    ops::SUPERVISOR_SET_ENABLED,
125    ops::SUPERVISOR_HEALTH_PROBE,
126    ops::SUPERVISOR_HEALTH,
127    ops::SUPERVISOR_STDERR_TAIL,
128    ops::SUPERVISOR_TERMINALS,
129    ops::SUPERVISOR_ROUTES,
130    ops::SUPERVISOR_PROVENANCE,
131    ops::SUPERVISOR_SPAWN_SNAPSHOT,
132    ops::SUPERVISOR_SPAWN_SUBSCRIBE,
133];
134
135/// Client ops the daemon serves but leaves out of `subc_ops`. Each is
136/// announced by a capability in `server.describe` instead, and clients check
137/// that capability before sending it. `ck daemon --json` prints `subc_ops`
138/// verbatim and scripts read that output, so a new name there would change it.
139/// A malformed body for one of these is still refused `invalid_control_body`
140/// rather than as an unknown op.
141const SUBC_UNADVERTISED_CONTROL_OPS: &[&str] = &[
142    ops::SUPERVISOR_RESCAN_CHECKED,
143    "config.modules",
144    "config.schema",
145    "config.show",
146    "config.watch",
147    "config.status",
148    "config.plan",
149    "config.plan_get",
150    "config.plan_discard",
151    "config.apply",
152    "config.stamp",
153    "config.unstamp",
154    "config.history",
155    "config.rollback",
156];
157
158mod caller_attestation;
159mod channel_operations;
160#[cfg(all(test, unix, feature = "test-support"))]
161#[path = "control/channel_operations_tests.rs"]
162mod channel_operations_tests;
163pub(crate) mod claims;
164#[cfg(test)]
165#[path = "control/config_advertisement_tests.rs"]
166mod config_advertisement_tests;
167mod config_gate;
168use caller_attestation::{caller_for_target, scope_acts_for_another};
169#[cfg(all(test, unix, feature = "test-support"))]
170#[path = "control/caller_attestation_tests.rs"]
171mod caller_attestation_tests;
172mod scope_expiry;
173mod scope_watch;
174mod usage;
175
176mod agent_commands;
177pub(crate) mod catalog;
178mod rescan_checked;
179use rescan_checked::{RescanMode, RescanPlan};
180
181const MODULE_TO_SUBC_CONTROL_OPS: &[&str] = &[
182    "claim.mint",
183    "claim.present",
184    MODULE_TO_SUBC_OP_CATALOG_UPDATE,
185    MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
186    "supervisor.live_roots",
187    "supervisor.agent_commands",
188    SCOPE_SYNC_OP,
189    SCOPE_APPLY_OP,
190    SCOPE_DESCRIBE_OP,
191    ops::SCOPE_WATCH,
192    subc_protocol::scope::ROUTE_AUTHORIZE_OP,
193    "operator.confirm",
194];
195
196/// Module-originated ops the daemon answers but does not advertise in
197/// `HELLO_ACK`. Empty today; an op is served from here while the feature it
198/// belongs to is incomplete, so no module is told it works before it does.
199const MODULE_TO_SUBC_UNADVERTISED_OPS: &[&str] = &[];
200
201const MODULE_BASELINE_CONTROL_OPS: &[&str] = &["route.bind", "route.status"];
202
203/// How long subc waits for a module to ack a relayed route.bind before returning
204/// `module_timeout`. The ack waits on the module's own configure, which for AFT
205/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
206/// and DB-open work — on a cold page cache or a large repo that legitimately
207/// exceeds a couple of seconds. The default is generous because rejecting a VALID
208/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
209/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
210pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
211
212/// How many CONSECUTIVE full-budget relay timeouts against one target module
213/// open that module's bind-relay breaker.
214///
215/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
216/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
217/// so three consecutive full-budget timeouts take ~36s to observe: every client
218/// whose open contributed to opening the breaker had already given up on its
219/// own. That is what makes opening the breaker unable to turn a call that would
220/// have succeeded into a refusal — it can only make an already-failing module
221/// fail faster.
222///
223/// Two would be reachable inside one default deadline. One would convict a
224/// module on a single cold-cache bind, which is exactly the valid-but-slow case
225/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
226pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
227
228/// How long a module's bind-relay breaker stays open before exactly one
229/// `route.open` is let through as a probe.
230///
231/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
232/// re-pays a full-budget stall almost continuously, and the breaker stops being
233/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
234/// deadline: a client that starts retrying after the module recovers has to get
235/// a probe opportunity inside its own deadline, or the breaker converts a
236/// recovered module into a failed call — the failure it exists to prevent,
237/// pointed the other way.
238///
239/// 20s sits between those with room on both sides, and it caps what a wedged
240/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
241/// rather than one per `route.open` per connection. The stall that motivated
242/// this, with its measurements, is written up in
243/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
244/// waited the whole budget out.
245pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
246
247const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
248const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
249
250fn reload_verdict(
251    configured: &Path,
252    spawned_from: Option<&Path>,
253    image: subc_control::RunningImageAgreement,
254) -> PendingReloadVerdict {
255    let path = match spawned_from {
256        Some(spawned_from) if reload_paths_match(configured, spawned_from) => {
257            ReloadPathAgreement::Match
258        }
259        Some(spawned_from) => ReloadPathAgreement::Mismatch {
260            configured: configured.to_path_buf(),
261            spawned_from: spawned_from.to_path_buf(),
262        },
263        None => ReloadPathAgreement::Unavailable {
264            reason: if matches!(
265                image,
266                subc_control::RunningImageAgreement::Unavailable {
267                    reason: subc_control::RunningImageUnavailableReason::NotRunning
268                }
269            ) {
270                ReloadPathUnavailableReason::NotRunning
271            } else {
272                ReloadPathUnavailableReason::SpawnedPathUnavailable
273            },
274        },
275    };
276    PendingReloadVerdict::new(path, image)
277}
278
279fn launch_spec_agreement(
280    configured: &crate::supervise::ModuleSpec,
281    running: bool,
282    spawned: Option<&crate::supervise::LaunchSpecDigest>,
283) -> subc_control::LaunchSpecAgreement {
284    use subc_control::{LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason};
285    if !running {
286        return Agreement::Unavailable {
287            reason: Reason::NotRunning,
288        };
289    }
290    match spawned {
291        None => Agreement::Unavailable {
292            reason: Reason::SpawnedSpecUnavailable,
293        },
294        Some(digest) if *digest == crate::supervise::LaunchSpecDigest::from_spec(configured) => {
295            Agreement::Match
296        }
297        Some(_) => Agreement::Mismatch,
298    }
299}
300
301fn reload_paths_match(configured: &Path, spawned_from: &Path) -> bool {
302    if configured == spawned_from {
303        return true;
304    }
305    #[cfg(windows)]
306    {
307        // Windows spawn records the resolved verbatim path (\\?\...), while
308        // configuration keeps its original spelling. Resolve both with the OS
309        // instead of stripping prefixes or folding case, which could conflate
310        // distinct names in case-sensitive directories. Different resolved
311        // paths still differ even if their files have identical content.
312        match (
313            std::fs::canonicalize(configured),
314            std::fs::canonicalize(spawned_from),
315        ) {
316            (Ok(configured), Ok(spawned_from)) => configured == spawned_from,
317            _ => false,
318        }
319    }
320    #[cfg(not(windows))]
321    {
322        false
323    }
324}
325
326#[derive(Clone)]
327struct DaemonProvenanceFacts {
328    build: DaemonBuildProvenance,
329    pid: Option<u32>,
330    started_at_ms: Option<u64>,
331    start_clock: Option<crate::clock::StartClock>,
332    executable_path: Option<PathBuf>,
333    executable_identity: Option<SpawnedFileIdentity>,
334    process_start_time: Option<u64>,
335    probe: ExecutableIdentityProbe,
336}
337
338impl Default for DaemonProvenanceFacts {
339    fn default() -> Self {
340        Self {
341            build: DaemonBuildProvenance {
342                build_git_sha: None,
343                build_lock_digest: None,
344            },
345            pid: None,
346            started_at_ms: None,
347            start_clock: None,
348            executable_path: None,
349            executable_identity: None,
350            process_start_time: None,
351            probe: ExecutableIdentityProbe::default(),
352        }
353    }
354}
355
356#[derive(Debug, Clone)]
357struct SupervisorRescanContext {
358    supervisor: Supervisor,
359    config_path: PathBuf,
360    configured_port: Option<u16>,
361    storage_config: Option<crate::daemon_config::StorageConfig>,
362    admission_facts_carrier_module_id: Option<String>,
363    admission_facts_targets: Option<Vec<String>>,
364    scope_authority_owners: Vec<String>,
365    federated_scope_owner: String,
366    privileged_operator_prompt: PrivilegedOperatorPrompt,
367    /// Counts executed rescans that set out to change the supervised modules'
368    /// staged or applied configuration, counted before the first change so a
369    /// rescan that fails partway still counts. With the daemon incarnation it
370    /// names the state a `supervisor.rescan_checked` preview was computed
371    /// against.
372    generation: Arc<std::sync::atomic::AtomicU64>,
373    module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
374}
375
376/// Refusal labels passed to `observe_route_open_refusal` that mean the target
377/// module is not serving right now, and so open or extend an outage in the
378/// route outage tracker. Every one of them is only reachable after the target
379/// was found in the registry, which is what keeps an arbitrary client-chosen
380/// id from ever creating tracker state.
381///
382/// Deliberately absent: `not_registered` and `removed` (the id may be
383/// anything a client sent, and a removed module is gone on purpose),
384/// `protocol_none` (such a module never serves routes, so nothing is out),
385/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
386/// capability and admission-facts refusals (they refuse the caller, not a
387/// module outage), and `relay_reservation_failed` (its code ranges over
388/// capacity limits as well as a vanished connection). Capacity, breaker,
389/// relay-timeout and module-rejection refusals do not pass through that
390/// function at all; the breaker logs its own transitions.
391///
392/// The two not-serving refusals that bypass that function record themselves
393/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
394/// `required_capability_unprovided` is not tracked: the module itself is up,
395/// and the outage belongs to the missing provider.
396const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
397    "reloading",
398    "supervisor_not_live",
399    "registration_not_active",
400    "no_forwarding_connection",
401    "relay_send_failed",
402];
403
404/// Observe test request cancellation relative to the connection's cleanup.
405#[cfg(test)]
406struct ActivityRequestPause {
407    connection: ConnectionId,
408    started: tokio::sync::Notify,
409    cancelled: tokio::sync::Notify,
410    cleanup_started: std::sync::atomic::AtomicBool,
411    cancelled_after_cleanup: std::sync::atomic::AtomicBool,
412}
413
414#[cfg(test)]
415struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
416
417#[cfg(test)]
418impl Drop for ActivityRequestCancellation {
419    fn drop(&mut self) {
420        self.0.cancelled_after_cleanup.store(
421            self.0
422                .cleanup_started
423                .load(std::sync::atomic::Ordering::Acquire),
424            std::sync::atomic::Ordering::Release,
425        );
426        self.0.cancelled.notify_one();
427    }
428}
429
430/// A test hold: signal arrival, then wait for release on the holding thread.
431#[cfg(test)]
432type TestPause = (
433    tokio::sync::oneshot::Sender<()>,
434    std::sync::mpsc::Receiver<()>,
435);
436
437/// A test hook run once at a fixed point in a handler.
438#[cfg(test)]
439type TestHook = Box<dyn FnOnce() + Send>;
440
441/// A test hold for async code: signal arrival, then await release.
442#[cfg(test)]
443type AsyncTestPause = (
444    tokio::sync::oneshot::Sender<()>,
445    tokio::sync::oneshot::Receiver<()>,
446);
447
448/// Real channel-0 control handler for subc itself.
449#[derive(Clone)]
450pub struct ControlHandler {
451    #[cfg(test)]
452    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
453    /// Holds connection cleanup at a numbered point: 0 is just after the agent
454    /// declaration queue closes, 1 just after the registration channel is
455    /// forgotten.
456    #[cfg(test)]
457    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
458    /// Runs once in `route.open`'s launch-nonce attestation, right after the
459    /// nonce is resolved, to interleave a nonce withdrawal there.
460    #[cfg(test)]
461    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
462    /// Holds a registration channel's HELLO after its reader resolved the
463    /// channel and before the blocking HELLO handler starts.
464    #[cfg(test)]
465    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
466    /// Holds an agent command declaration at a numbered point in its handler.
467    #[cfg(test)]
468    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
469    claims: Arc<claims::Claims>,
470    registry: Arc<Registry>,
471    control_usage: Arc<Mutex<usage::ControlUsage>>,
472    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
473    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
474    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
475    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
476    config_review_admission_is_default: bool,
477    activity: Option<crate::activity::ActivityLedger>,
478    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
479    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
480    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
481    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
482    forwarding: Arc<ForwardingTable>,
483    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
484    supervisor: SupervisorHandle,
485    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
486    agent_declarations: agent_commands::Queues,
487    list_admission: Arc<tokio::sync::Semaphore>,
488    subc_capabilities: Arc<[String]>,
489    /// Daemon-wide route.bind relay budget. Used as the fallback when the
490    /// target module has no per-module override in
491    /// `route_bind_relay_timeouts`.
492    route_bind_relay_timeout: Duration,
493    /// Per-module route.bind relay budget overrides, keyed by module id. When
494    /// `handle_route_open` resolves the deadline for a target module, a
495    /// per-module entry wins over the daemon-wide value above.
496    route_bind_relay_timeouts: BTreeMap<String, Duration>,
497    /// Per-target-module bind-relay breaker state. Shared with the forwarding
498    /// table, which is where a new module connection resets it.
499    route_bind_breakers: RouteBindBreakers,
500    /// Live relay admissions keyed by target module. Shared through the
501    /// forwarding table so cloned or separately built handlers enforce one cap.
502    route_bind_concurrency: RouteBindConcurrency,
503    /// Start and end of each module's not-serving period as seen by
504    /// `route.open`, so an outage gets one line at each edge instead of only
505    /// the per-refusal INFO lines. Taken from the forwarding table, so every
506    /// handler built over one table shares it.
507    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
508    /// Consecutive relay timeouts that open a module's breaker.
509    route_bind_breaker_threshold: u32,
510    /// How long a breaker stays open before one probe is admitted.
511    route_bind_breaker_cooldown: Duration,
512    health_probe_timeout: Duration,
513    /// Central storage policy. When set, each registering module receives its
514    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
515    storage_config: Option<crate::daemon_config::StorageConfig>,
516    /// The machine id established at boot, served on every HELLO_ACK and on
517    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
518    /// changes the file, never this value. `None` serves no id.
519    machine_id: Option<crate::machine_id::MachineId>,
520    admission_facts_carrier_module_id: Option<String>,
521    admission_facts_targets: Option<Vec<String>>,
522    /// Scope records with their sync authorities and tombstones; see
523    /// `crate::scopes`. Shared by clones of this handler, so every connection
524    /// reads and writes one table.
525    scopes: Arc<RwLock<ScopeTable>>,
526    /// Wakes the expiry loop when an accepted scope change may have added a
527    /// deadline, so the loop can wait without ticking while no live scope has
528    /// one. A permit is stored when nothing waits, so no wake is lost.
529    scope_deadline_added: Arc<tokio::sync::Notify>,
530    /// The configured `scope_authority_owners`, kept so a rescan can report a
531    /// changed value as needing a daemon restart; rescan never applies it.
532    scope_authority_owners: Vec<String>,
533    federated_scope_owner: String,
534    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
535    privileged_operator_prompt: PrivilegedOperatorPrompt,
536    /// The local and peer address of each accepted TCP client connection, read
537    /// from the daemon's own socket, so a privileged request can name its caller.
538    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
539    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
540    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
541    captured_peers: Arc<Mutex<HashMap<ConnectionId, subc_os::local_peer::CapturedPeer>>>,
542    config_desktop_stamps:
543        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
544    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
545    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
546    pub(crate) operator_apps:
547        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
548    /// One launch entry per app, behind a leaf lock: no other lock is taken
549    /// while it is held. Entries are memory-only, so a daemon or
550    /// installed-service restart drops them and a relaunched daemon never
551    /// mistakes an older process for its own launch.
552    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
553    /// Serializes `app.open` launches: the liveness check in the decision and
554    /// the later publish must not interleave across concurrent calls, or two
555    /// calls could both launch and the second publish would orphan the first
556    /// process. Refusals and `already_running` answers share the same lock;
557    /// `app.open` is rare, so the cost is negligible.
558    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
559    // Portable wire samples exercise dispatch without starting an OS process.
560    #[cfg(test)]
561    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
562    #[cfg(test)]
563    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
564    #[cfg(test)]
565    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
566    #[cfg(test)]
567    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
568    #[cfg(test)]
569    recovery_exit_test_completed: Option<fn(u64)>,
570    #[cfg(test)]
571    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
572    #[cfg(test)]
573    recovery_exit_test_quiet_retry: bool,
574    #[cfg(test)]
575    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
576    #[cfg(test)]
577    config_delivery_test_wakes:
578        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
579    #[cfg(all(test, unix))]
580    config_delivery_test_idle:
581        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
582    /// Test-only Windows signature and flash hooks. Production builds carry
583    /// neither: with the publisher unset, the production table never reaches
584    /// verification, and the default attention hook only logs.
585    #[allow(dead_code)]
586    #[cfg(windows)]
587    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
588    #[allow(dead_code)]
589    #[cfg(windows)]
590    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
591    /// Test-only tracking fault hook: makes opening the tracking handle on
592    /// the launched pid fail, so a test can prove an untrackable launch is
593    /// stopped rather than left running.
594    #[allow(dead_code)]
595    #[cfg(windows)]
596    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
597    /// Test-only count of Windows spawn attempts, so a test can prove a
598    /// refused launch started no process. Unit tests only.
599    #[cfg(all(test, windows))]
600    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
601    #[cfg(test)]
602    caller_lookup: Option<TestCallerLookup>,
603    /// The launch nonce each module connection presented at HELLO, which is how
604    /// a `scope.sync` is matched to the owner's current launch.
605    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
606    rescan: Option<SupervisorRescanContext>,
607    connected_clients: ConnectedClients,
608    counters: DaemonCounters,
609    /// Why this daemon serves no local endpoint, when binding one failed. `None`
610    /// when the endpoint is served, and also on a handler that was never told.
611    local_endpoint_unavailable: Option<String>,
612    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
613    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
614    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
615    /// their usual severity (see [`log_requirement_events`]). A handler built
616    /// without one has a flag that is never set.
617    daemon_shutdown: DaemonShutdownFlag,
618    daemon_provenance: DaemonProvenanceFacts,
619    #[cfg(test)]
620    control_dispatch_delay: Option<Duration>,
621    #[cfg(test)]
622    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
623    /// Holds `route.open` after the route.bind is queued to the module and
624    /// before it is marked enqueued, so a test can make the module's reply (or
625    /// a client teardown) land exactly inside that window.
626    #[cfg(test)]
627    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
628    /// Holds a HELLO after its registry entry is reserved and before its
629    /// forwarding endpoint is installed, so a test can read the catalog and
630    /// open routes while the module is registered but not yet routable. A
631    /// blocking barrier because the HELLO handler is synchronous; the test
632    /// runs the HELLO on its own thread.
633    #[cfg(test)]
634    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
635    #[cfg(test)]
636    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
637    #[cfg(test)]
638    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
639    #[cfg(test)]
640    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
641    #[cfg(test)]
642    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
643}
644
645impl fmt::Debug for ControlHandler {
646    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647        f.debug_struct("ControlHandler")
648            .field("registry", &self.registry)
649            .field("forwarding", &self.forwarding)
650            .field("process_liveness", &self.process_liveness.is_some())
651            .field("supervisor", &self.supervisor)
652            .field("subc_capabilities", &self.subc_capabilities)
653            .finish()
654    }
655}
656
657struct RouteOpenRequest {
658    target: RouteTarget,
659    identity: BindIdentity,
660    consumer_identity: Option<ConsumerIdentity>,
661    consumer_capabilities: Option<Vec<String>>,
662    role_versions: Option<BTreeMap<String, String>>,
663    busy_refusals: Option<bool>,
664    admission_facts: Option<serde_json::Value>,
665    scope: Option<ScopeSelector>,
666    accepts_close_reasons: Option<Vec<String>>,
667}
668
669#[derive(Clone, Copy)]
670enum RouteOpenPhase {
671    Admission,
672    ProjectRoot,
673    EgressReservation,
674    BindSend,
675    BindAckWait,
676}
677
678/// Store elapsed time for each route-open phase, including attempts that end
679/// in an early refusal or backend error. Admission also includes rechecks and
680/// commit bookkeeping performed between the other timed phases.
681struct RouteOpenTimings {
682    module_id: String,
683    principal: String,
684    admission: Duration,
685    project_root: Duration,
686    egress_reservation: Duration,
687    bind_send: Duration,
688    bind_ack_wait: Duration,
689    phase: Option<RouteOpenPhase>,
690    phase_started_at: Instant,
691}
692
693impl RouteOpenTimings {
694    fn new() -> Self {
695        Self {
696            module_id: String::new(),
697            // Refusals before attestation must not claim a verified principal.
698            principal: "unresolved".to_string(),
699            admission: Duration::ZERO,
700            project_root: Duration::ZERO,
701            egress_reservation: Duration::ZERO,
702            bind_send: Duration::ZERO,
703            bind_ack_wait: Duration::ZERO,
704            phase: Some(RouteOpenPhase::Admission),
705            phase_started_at: Instant::now(),
706        }
707    }
708
709    fn finish(&mut self) {
710        let elapsed = self.phase_started_at.elapsed();
711        match self.phase.take() {
712            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
713            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
714            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
715            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
716            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
717            None => {}
718        }
719    }
720
721    fn enter(&mut self, phase: RouteOpenPhase) {
722        self.finish();
723        self.phase = Some(phase);
724        self.phase_started_at = Instant::now();
725    }
726}
727
728struct RouteBindReservationGuard {
729    forwarding: Arc<ForwardingTable>,
730    endpoint: ModuleEndpointId,
731    relay_corr: u64,
732    armed: bool,
733}
734
735struct ModuleControlRpcGuard {
736    forwarding: Arc<ForwardingTable>,
737    endpoint: ModuleEndpointId,
738    corr: u64,
739    armed: bool,
740}
741
742impl ModuleControlRpcGuard {
743    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
744        Self {
745            forwarding,
746            endpoint,
747            corr,
748            armed: true,
749        }
750    }
751
752    fn disarm(&mut self) {
753        self.armed = false;
754    }
755}
756
757impl Drop for ModuleControlRpcGuard {
758    fn drop(&mut self) {
759        if self.armed {
760            let _ = self
761                .forwarding
762                .cancel_module_control_rpc(self.endpoint, self.corr);
763        }
764    }
765}
766
767impl RouteBindReservationGuard {
768    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
769        Self {
770            forwarding,
771            endpoint,
772            relay_corr,
773            armed: true,
774        }
775    }
776
777    fn release_and_disarm(&mut self) {
778        if !self.armed {
779            return;
780        }
781        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
782            self.endpoint,
783            self.relay_corr,
784            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
785        ) {
786            send_goodbye_target_best_effort(
787                &self.forwarding.counters(),
788                &target,
789                "canceled route.bind",
790            );
791        }
792        self.armed = false;
793    }
794
795    fn disarm(&mut self) {
796        self.armed = false;
797    }
798}
799
800impl Drop for RouteBindReservationGuard {
801    fn drop(&mut self) {
802        self.release_and_disarm();
803    }
804}
805
806/// Per-target-module circuit breaker around the `route.bind` relay.
807///
808/// The connection reader is serial per connection, so a module whose `on_bind`
809/// sits on the ack blocks every LATER frame on the connections that call it,
810/// including calls to unrelated modules. This does not make any module's bind
811/// fast; it stops the daemon paying the full budget again and again for a
812/// condition it has already observed.
813///
814/// State is keyed by TARGET MODULE and shared by every connection: a wedged
815/// module wedges everyone, so what one connection learned should protect the
816/// rest.
817///
818/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
819/// relay to that module has actually timed out, and is removed again when a
820/// relay is accepted or the module reconnects, so it cannot grow with traffic
821/// or with modules that behave.
822///
823/// # Why a `std` mutex here is not the head-of-line defect again
824///
825/// Acquisition never awaits. The critical section is a hash lookup plus a few
826/// integer updates, with no I/O and no `.await` inside it, so a reader task
827/// cannot be descheduled behind it the way it can behind
828/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
829/// primitive, held for the same kind of work, as the refusal counter this very
830/// path already increments.
831///
832/// It is also NOT on the data-plane splice path: only `route.open` and module
833/// registration touch it, so bound-route frames gain no state check and no
834/// contention.
835#[derive(Debug, Clone, Default)]
836pub(crate) struct RouteBindBreakers {
837    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
838}
839
840#[derive(Debug, Clone, Default)]
841pub(crate) struct RouteBindConcurrency {
842    modules: Arc<Mutex<HashMap<String, usize>>>,
843}
844
845struct RouteBindConcurrencyGuard {
846    concurrency: RouteBindConcurrency,
847    module_id: String,
848}
849
850impl RouteBindConcurrency {
851    /// Admit without waiting. Waiting here would move the bind stall from the
852    /// module reply to a semaphore and restore reader head-of-line blocking.
853    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
854        let mut modules = self
855            .modules
856            .lock()
857            .expect("route.bind concurrency mutex poisoned");
858        let in_flight = modules.entry(module_id.to_string()).or_default();
859        if *in_flight >= limit {
860            return Err(*in_flight);
861        }
862        *in_flight += 1;
863        Ok(RouteBindConcurrencyGuard {
864            concurrency: self.clone(),
865            module_id: module_id.to_string(),
866        })
867    }
868}
869
870impl Drop for RouteBindConcurrencyGuard {
871    fn drop(&mut self) {
872        let mut modules = self
873            .concurrency
874            .modules
875            .lock()
876            .expect("route.bind concurrency mutex poisoned");
877        let remove = {
878            let in_flight = modules
879                .get_mut(&self.module_id)
880                .expect("admitted route.bind has a concurrency entry");
881            *in_flight -= 1;
882            *in_flight == 0
883        };
884        if remove {
885            modules.remove(&self.module_id);
886        }
887    }
888}
889
890#[derive(Debug, Default)]
891struct ModuleBreakerState {
892    /// Relay timeouts observed with no accepted relay in between.
893    consecutive_timeouts: u32,
894    /// `Some` while the breaker is open: the instant the cooldown expires and
895    /// the next arrival may probe. `None` means closed.
896    cooldown_until: Option<Instant>,
897    /// A half-open probe has been admitted and has not settled yet. This is
898    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
899    /// that read the cooldown, so concurrent opens arriving at the moment the
900    /// cooldown expires cannot all decide that they are the probe.
901    probe_in_flight: Option<Arc<()>>,
902}
903
904/// What the breaker decided for one `route.open`, before any relay work.
905enum RouteBindAdmission<'a> {
906    Admitted {
907        guard: RouteBindBreakerGuard<'a>,
908        /// This open is the single half-open probe, so the transition is worth
909        /// one log line.
910        probe: bool,
911    },
912    Refused {
913        consecutive_timeouts: u32,
914        /// What is left of the cooldown. Zero when the refusal is because the
915        /// one probe is already in flight rather than because the cooldown has
916        /// not elapsed.
917        retry_in: Duration,
918        probe_in_flight: bool,
919    },
920}
921
922/// An outstanding admission, which must be told how its relay settled.
923///
924/// `Drop` settles it as inconclusive, so an early return between admission and
925/// the relay -- or the whole handler being cancelled when the client
926/// disconnects -- releases a half-open probe slot instead of leaving the
927/// breaker wedged half-open with no further probes.
928struct RouteBindBreakerGuard<'a> {
929    breakers: RouteBindBreakers,
930    module_id: &'a str,
931    probe_token: Option<Arc<()>>,
932    settled: bool,
933}
934
935impl RouteBindBreakerGuard<'_> {
936    /// The module answered within the budget and took the bind. THE ONLY
937    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
938    /// breaker, which is a transition worth logging.
939    fn record_accepted(&mut self) -> bool {
940        self.settled = true;
941        self.breakers.record_accepted(self.module_id)
942    }
943
944    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
945    /// COUNTS TOWARD OPENING.
946    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
947        self.settled = true;
948        self.breakers.record_timeout(
949            self.module_id,
950            self.probe_token.as_ref(),
951            threshold,
952            cooldown,
953        )
954    }
955
956    /// Everything else: the module REJECTED the bind, its connection went away
957    /// mid-relay, or the waiter was cancelled.
958    ///
959    /// None of these is evidence that a module is slow, and each already has
960    /// its own refusal with its own code. A module that rejects a bind in
961    /// microseconds is healthy and must never be convicted for it; a module
962    /// that died has said nothing about the module that replaces it. So these
963    /// neither increment nor reset the count -- they only release a probe slot.
964    fn record_inconclusive(&mut self) {
965        self.settled = true;
966        self.breakers
967            .record_inconclusive(self.module_id, self.probe_token.as_ref());
968    }
969}
970
971impl Drop for RouteBindBreakerGuard<'_> {
972    fn drop(&mut self) {
973        if !self.settled {
974            self.breakers
975                .record_inconclusive(self.module_id, self.probe_token.as_ref());
976        }
977    }
978}
979
980/// The breaker moved to open, reported so the caller can log it outside the
981/// lock. Opening is rare and load-bearing; the refusals that follow are
982/// frequent and are counted rather than logged.
983struct BreakerOpened {
984    consecutive_timeouts: u32,
985    /// True when a failed probe re-opened an already-open breaker, which reads
986    /// very differently in a log from a first opening.
987    reopened_after_probe: bool,
988}
989
990impl RouteBindBreakers {
991    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
992        self.modules
993            .lock()
994            .expect("route.bind breaker mutex poisoned")
995    }
996
997    /// Decide whether this `route.open` may attempt its relay. Takes the map
998    /// lock and nothing else, and never awaits.
999    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
1000        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
1001            probe: probe_token.is_some(),
1002            guard: RouteBindBreakerGuard {
1003                breakers: self.clone(),
1004                module_id,
1005                probe_token,
1006                settled: false,
1007            },
1008        };
1009
1010        let mut modules = self.lock();
1011        let Some(state) = modules.get_mut(module_id) else {
1012            return admitted(None);
1013        };
1014        let Some(cooldown_until) = state.cooldown_until else {
1015            return admitted(None);
1016        };
1017        if state.probe_in_flight.is_some() {
1018            return RouteBindAdmission::Refused {
1019                consecutive_timeouts: state.consecutive_timeouts,
1020                retry_in: Duration::ZERO,
1021                probe_in_flight: true,
1022            };
1023        }
1024        let now = Instant::now();
1025        if now < cooldown_until {
1026            return RouteBindAdmission::Refused {
1027                consecutive_timeouts: state.consecutive_timeouts,
1028                retry_in: cooldown_until - now,
1029                probe_in_flight: false,
1030            };
1031        }
1032        let token = Arc::new(());
1033        state.probe_in_flight = Some(Arc::clone(&token));
1034        admitted(Some(token))
1035    }
1036
1037    fn record_accepted(&self, module_id: &str) -> bool {
1038        self.lock()
1039            .remove(module_id)
1040            .is_some_and(|state| state.cooldown_until.is_some())
1041    }
1042
1043    fn record_timeout(
1044        &self,
1045        module_id: &str,
1046        probe_token: Option<&Arc<()>>,
1047        threshold: u32,
1048        cooldown: Duration,
1049    ) -> Option<BreakerOpened> {
1050        let mut modules = self.lock();
1051        let state = modules.entry(module_id.to_string()).or_default();
1052        let was_open = state.cooldown_until.is_some();
1053        let was_probe = Self::owns_probe(state, probe_token);
1054        if was_probe {
1055            state.probe_in_flight = None;
1056        }
1057        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
1058        if state.consecutive_timeouts < threshold {
1059            return None;
1060        }
1061        state.cooldown_until = Some(Instant::now() + cooldown);
1062        Some(BreakerOpened {
1063            consecutive_timeouts: state.consecutive_timeouts,
1064            reopened_after_probe: was_open && was_probe,
1065        })
1066    }
1067
1068    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
1069        // A relay can finish after the breaker was reset or after it opened
1070        // again and started a new probe. Only the guard whose token matches the
1071        // active probe may release it, so a late relay never frees a newer probe.
1072        state
1073            .probe_in_flight
1074            .as_ref()
1075            .zip(token)
1076            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
1077    }
1078
1079    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
1080        if let Some(state) = self.lock().get_mut(module_id) {
1081            if Self::owns_probe(state, probe_token) {
1082                state.probe_in_flight = None;
1083            }
1084        }
1085    }
1086
1087    /// Discard what was learned about a module, because the process it was
1088    /// learned about is gone. Returns the discarded count when it was non-zero.
1089    ///
1090    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
1091    /// `module_id` is a configuration identity that outlives any particular
1092    /// child; what the breaker observed was the process behind the module
1093    /// connection of the moment. When a new connection registers under that id
1094    /// the verdict's subject no longer exists, so the verdict is stale by
1095    /// construction rather than merely likely to be wrong. Keeping it would
1096    /// apply a dead process's record to a live one, which is the same defect
1097    /// class this breaker exists to stop the daemon committing.
1098    ///
1099    /// A half-open probe in flight is discarded with the rest: it was a
1100    /// question about the old process.
1101    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
1102        self.lock()
1103            .remove(module_id)
1104            .map(|state| state.consecutive_timeouts)
1105            .filter(|discarded| *discarded > 0)
1106    }
1107
1108    /// Open breakers, for the `server.describe` counters object. `None` when
1109    /// none is open, so the key stays absent rather than present-and-empty.
1110    ///
1111    /// This is the operator's answer to "is this module refusing instantly or
1112    /// is it fine?", which look identical from a client that retries and then
1113    /// succeeds.
1114    fn open_snapshot(&self) -> Option<serde_json::Value> {
1115        let now = Instant::now();
1116        let modules = self.lock();
1117        let open = modules
1118            .iter()
1119            .filter_map(|(module_id, state)| {
1120                let cooldown_until = state.cooldown_until?;
1121                Some((
1122                    module_id.clone(),
1123                    serde_json::json!({
1124                        "consecutive_timeouts": state.consecutive_timeouts,
1125                        "cooldown_remaining_ms":
1126                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
1127                        "probe_in_flight": state.probe_in_flight.is_some(),
1128                    }),
1129                ))
1130            })
1131            .collect::<serde_json::Map<String, serde_json::Value>>();
1132        (!open.is_empty()).then_some(serde_json::Value::Object(open))
1133    }
1134}
1135
1136impl ControlHandler {
1137    pub(crate) fn install_registration_service(
1138        &self,
1139        router: std::sync::Weak<crate::Router>,
1140        auth: crate::server::ServerAuth,
1141    ) {
1142        self.supervisor.install_registration_service(router, auth);
1143    }
1144    pub fn new(registry: Arc<Registry>) -> Self {
1145        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
1146    }
1147
1148    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
1149        let counters = forwarding.counters();
1150        // Taken from the forwarding table rather than created here, so that the
1151        // breaker a `route.open` consults is the same one a module's
1152        // registration resets, however many handlers are built over one table.
1153        let route_bind_breakers = forwarding.route_bind_breakers();
1154        let route_bind_concurrency = forwarding.route_bind_concurrency();
1155        let route_outages = forwarding.route_outages();
1156        Self {
1157            registry,
1158            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
1159            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
1160            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1161            #[cfg(test)]
1162            activity_request_pause: Arc::new(Mutex::new(None)),
1163            #[cfg(test)]
1164            cleanup_pause: Arc::new(Mutex::new(None)),
1165            #[cfg(test)]
1166            after_nonce_attestation: Arc::new(Mutex::new(None)),
1167            #[cfg(test)]
1168            hello_ingress_pause: Arc::new(Mutex::new(None)),
1169            #[cfg(test)]
1170            agent_commands_pause: Arc::new(Mutex::new(None)),
1171            claims: Arc::new(claims::Claims::default()),
1172            config_runtime: None,
1173            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
1174            config_review_admission_is_default: true,
1175            activity: None,
1176            activity_streams: Arc::new(Mutex::new(HashMap::new())),
1177            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
1178            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
1179            scope_streams: Arc::new(Mutex::new(HashMap::new())),
1180            forwarding,
1181            process_liveness: None,
1182            supervisor: SupervisorHandle::new(),
1183            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
1184                env!("CARGO_PKG_VERSION").to_owned(),
1185            )),
1186            agent_declarations: agent_commands::Queues::default(),
1187            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
1188            subc_capabilities: Arc::from([
1189                CAP_MANIFEST_REGISTRATION.to_string(),
1190                CAP_CHANNEL_LIFECYCLE.to_string(),
1191                CAP_PING_PONG.to_string(),
1192                CAP_SESSION_ATTACH.to_string(),
1193                CAP_ADMISSION_FACTS_RELAY.to_string(),
1194                CAP_SCOPES_V1.to_string(),
1195                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
1196                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1197                PEER_BUILD_CAPABILITY.to_string(),
1198                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1199                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1200                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1201                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1202                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1203                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1204                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1205                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1206                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1207                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1208                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1209                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1210            ]),
1211            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1212            route_bind_relay_timeouts: BTreeMap::new(),
1213            route_bind_breakers,
1214            route_bind_concurrency,
1215            route_outages,
1216            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1217            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1218            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1219            storage_config: None,
1220            machine_id: None,
1221            admission_facts_carrier_module_id: None,
1222            admission_facts_targets: None,
1223            scopes: Arc::new(RwLock::new(ScopeTable::new(
1224                crate::daemon_config::default_scope_authority_owners(),
1225            ))),
1226            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1227            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1228            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1229            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1230            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1231            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1232            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1233            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1234            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1235            local_connections: Arc::new(Mutex::new(HashSet::new())),
1236            operator_app_policy: Default::default(),
1237            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1238            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1239            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1240            #[cfg(test)]
1241            app_open_test_platform: None,
1242            #[cfg(test)]
1243            app_open_test_launch: None,
1244            #[cfg(test)]
1245            config_review_test_reply: None,
1246            #[cfg(test)]
1247            recovery_exit_test_after_step: None,
1248            #[cfg(test)]
1249            recovery_exit_test_completed: None,
1250            #[cfg(test)]
1251            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1252            #[cfg(test)]
1253            recovery_exit_test_quiet_retry: false,
1254            #[cfg(test)]
1255            recovery_exit_test_retry_pause: None,
1256            #[cfg(test)]
1257            config_delivery_test_wakes: None,
1258            #[cfg(all(test, unix))]
1259            config_delivery_test_idle: None,
1260            #[cfg(windows)]
1261            windows_verify: None,
1262            #[cfg(windows)]
1263            windows_flash: None,
1264            #[cfg(windows)]
1265            windows_track: None,
1266            #[cfg(all(test, windows))]
1267            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1268            #[cfg(test)]
1269            caller_lookup: None,
1270            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1271            rescan: None,
1272            connected_clients: ConnectedClients::new(),
1273            local_endpoint_unavailable: None,
1274            counters,
1275            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1276            daemon_shutdown: DaemonShutdownFlag::default(),
1277            daemon_provenance: DaemonProvenanceFacts::default(),
1278            #[cfg(test)]
1279            control_dispatch_delay: None,
1280            #[cfg(test)]
1281            provenance_probe_override: None,
1282            #[cfg(test)]
1283            route_bind_relay_sent_hold: None,
1284            #[cfg(test)]
1285            hello_registry_to_forwarding_hold: None,
1286            #[cfg(test)]
1287            hello_ack_to_publication_hold: None,
1288            #[cfg(test)]
1289            hello_before_publication_hold: None,
1290            #[cfg(test)]
1291            hello_after_launch_check_hold: None,
1292            #[cfg(test)]
1293            hello_inside_publication_hold: None,
1294        }
1295    }
1296
1297    /// Set the central storage policy: registering modules then receive their
1298    /// resolved storage descriptor in HELLO_ACK.
1299    pub fn with_storage_config(
1300        mut self,
1301        storage_config: Option<crate::daemon_config::StorageConfig>,
1302    ) -> Self {
1303        self.storage_config = storage_config;
1304        self
1305    }
1306
1307    /// Open the ledger on its own writer thread; an unavailable sink does not
1308    /// prevent the daemon from serving routing or supervisor requests.
1309    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1310        self.activity = Some(crate::activity::ActivityLedger::open(
1311            run_dir.join("activity.jsonl"),
1312            incarnation,
1313        ));
1314        self.supervisor.set_activity(self.activity.clone());
1315        self
1316    }
1317
1318    /// Set the machine id served to every registering module (HELLO_ACK) and on
1319    /// `server.describe`.
1320    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1321        self.machine_id = machine_id;
1322        self
1323    }
1324
1325    /// Configure the exact reserved module and target ids permitted to relay
1326    /// opaque admission facts. Config-file loading validates this authority;
1327    /// this builder keeps the same policy available to embedded test daemons.
1328    pub fn with_admission_facts_config(
1329        mut self,
1330        carrier_module_id: Option<String>,
1331        targets: Option<Vec<String>>,
1332    ) -> Self {
1333        self.admission_facts_carrier_module_id = carrier_module_id;
1334        self.admission_facts_targets = targets;
1335        self
1336    }
1337
1338    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1339    /// Replaces the scope table with an empty one under the new list, so call it
1340    /// while building the handler, before any module can sync.
1341    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1342        self.scopes = Arc::new(RwLock::new(
1343            ScopeTable::new(owners.iter().cloned())
1344                .with_federated_owner(self.federated_scope_owner.clone()),
1345        ));
1346        self.scope_authority_owners = owners;
1347        self
1348    }
1349
1350    /// Set the exclusive federated owner while building the handler, before syncs.
1351    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1352        self.scopes = Arc::new(RwLock::new(
1353            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1354                .with_federated_owner(owner.clone()),
1355        ));
1356        self.federated_scope_owner = owner;
1357        self
1358    }
1359
1360    /// Set the startup policy before installing the rescan context or serving requests.
1361    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1362        self.privileged_operator_prompt = mode;
1363        self
1364    }
1365
1366    /// Override the route.bind relay timeout. Used by tests that assert the
1367    /// timeout path so they don't block on the production-safe default.
1368    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1369        self.route_bind_relay_timeout = timeout;
1370        self
1371    }
1372
1373    /// Install per-module route.bind relay budget overrides. A module id
1374    /// listed here wins over the daemon-wide default set via
1375    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1376    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1377    /// the same `Duration` the bind path will use.
1378    pub fn with_route_bind_relay_timeouts(
1379        mut self,
1380        timeouts: impl IntoIterator<Item = (String, Duration)>,
1381    ) -> Self {
1382        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1383        self
1384    }
1385
1386    /// Resolve the route.bind relay budget for a specific target module id.
1387    /// Per-module overrides win; the daemon-wide value (set via
1388    /// `with_route_bind_relay_timeout` or the built-in default) is the
1389    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1390    /// the same resolution `handle_route_open` will use.
1391    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1392        self.route_bind_relay_timeouts
1393            .get(module_id)
1394            .copied()
1395            .unwrap_or(self.route_bind_relay_timeout)
1396    }
1397
1398    /// Override the per-module bind-relay breaker policy.
1399    ///
1400    /// Used by tests, which cannot spend three production budgets opening a
1401    /// breaker or twenty seconds waiting for its cooldown. The production
1402    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1403    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1404    /// reasoning for the numbers.
1405    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1406        self.route_bind_breaker_threshold = threshold.max(1);
1407        self.route_bind_breaker_cooldown = cooldown;
1408        self
1409    }
1410
1411    #[cfg(test)]
1412    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1413        self.health_probe_timeout = timeout;
1414        self
1415    }
1416
1417    #[cfg(test)]
1418    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1419        self.control_dispatch_delay = Some(delay);
1420        self
1421    }
1422
1423    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1424    /// announce it is parked, once to be released. Build the barrier for two
1425    /// parties, the test being the other one.
1426    #[cfg(test)]
1427    pub(crate) fn with_route_bind_relay_sent_hold(
1428        mut self,
1429        hold: Arc<tokio::sync::Barrier>,
1430    ) -> Self {
1431        self.route_bind_relay_sent_hold = Some(hold);
1432        self
1433    }
1434
1435    /// A HELLO waits on `hold` twice between reserving its registry entry and
1436    /// installing its forwarding endpoint: once to announce it is parked, once
1437    /// to be released. Build the barrier for two parties, the test being the
1438    /// other one, and run the HELLO on a thread of its own.
1439    #[cfg(test)]
1440    pub(crate) fn with_hello_registry_to_forwarding_hold(
1441        mut self,
1442        hold: Arc<std::sync::Barrier>,
1443    ) -> Self {
1444        self.hello_registry_to_forwarding_hold = Some(hold);
1445        self
1446    }
1447
1448    #[cfg(test)]
1449    fn hold_between_registry_and_forwarding(&self) {
1450        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1451            hold.wait();
1452            hold.wait();
1453        }
1454    }
1455
1456    /// Park after the ACK is queued and forwarding is installed, until a test
1457    /// has read the ACK and issued a registry lookup from another connection.
1458    #[cfg(test)]
1459    fn hold_between_ack_and_publication(&self) {
1460        if let Some(hold) = &self.hello_ack_to_publication_hold {
1461            hold.wait();
1462            hold.wait();
1463        }
1464    }
1465
1466    #[cfg(all(test, unix))]
1467    pub(crate) fn with_hello_before_publication_hold(
1468        mut self,
1469        hold: Arc<std::sync::Barrier>,
1470    ) -> Self {
1471        self.hello_before_publication_hold = Some(hold);
1472        self
1473    }
1474
1475    #[cfg(all(test, unix))]
1476    pub(crate) fn with_hello_after_launch_check_hold(
1477        mut self,
1478        hold: Arc<std::sync::Barrier>,
1479    ) -> Self {
1480        self.hello_after_launch_check_hold = Some(hold);
1481        self
1482    }
1483
1484    #[cfg(all(test, unix))]
1485    pub(crate) fn with_hello_inside_publication_hold(
1486        mut self,
1487        hold: Arc<std::sync::Barrier>,
1488    ) -> Self {
1489        self.hello_inside_publication_hold = Some(hold);
1490        self
1491    }
1492
1493    pub fn with_process_liveness(
1494        mut self,
1495        process_liveness: Arc<dyn ModuleProcessLiveness>,
1496    ) -> Self {
1497        self.process_liveness = Some(process_liveness);
1498        self
1499    }
1500
1501    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1502        self.supervisor = supervisor;
1503        if let Some(owner) = &self.config_runtime {
1504            self.supervisor.install_binding_retirement(owner);
1505        }
1506        self.supervisor.set_activity(self.activity.clone());
1507        self
1508    }
1509
1510    pub fn with_daemon_provenance(
1511        mut self,
1512        pid: u32,
1513        started_at_ms: u64,
1514        executable_path: Option<PathBuf>,
1515        build_git_sha: Option<String>,
1516        build_lock_digest: Option<String>,
1517    ) -> Self {
1518        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1519        let process_start_time = process_start_time(pid);
1520        self.daemon_provenance = DaemonProvenanceFacts {
1521            build: DaemonBuildProvenance {
1522                build_git_sha,
1523                build_lock_digest,
1524            },
1525            pid: Some(pid),
1526            started_at_ms: Some(started_at_ms),
1527            start_clock: None,
1528            executable_path,
1529            executable_identity,
1530            process_start_time,
1531            probe: ExecutableIdentityProbe::default(),
1532        };
1533        self
1534    }
1535
1536    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1537        self.daemon_provenance.start_clock = Some(clock);
1538        self
1539    }
1540
1541    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1542    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1543        self.scopes
1544            .write()
1545            .unwrap_or_else(|poisoned| poisoned.into_inner())
1546            .set_wall_clock(Arc::new(clock));
1547        self
1548    }
1549
1550    #[cfg(test)]
1551    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1552        self.provenance_probe_override = Some(result);
1553        self
1554    }
1555
1556    /// Install the configured module set and its reserved capability bindings.
1557    /// Bindings are configuration-scoped and may point at a provider that has not
1558    /// been installed yet, so this does not require the bound module to exist.
1559    pub fn with_capability_config(
1560        self,
1561        modules: impl IntoIterator<Item = (String, bool)>,
1562        reserved_capabilities: BTreeMap<String, String>,
1563    ) -> Self {
1564        self.capability_evaluator
1565            .configure(modules, reserved_capabilities);
1566        self
1567    }
1568
1569    /// Share the supervisor's daemon-shutdown flag with this handler, so
1570    /// requirement changes after the daemon has begun its announced shutdown
1571    /// are not reported as faults.
1572    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1573        self.daemon_shutdown = flag;
1574        self
1575    }
1576
1577    pub fn with_supervisor_rescan(
1578        mut self,
1579        supervisor: Supervisor,
1580        config_path: impl Into<PathBuf>,
1581        configured_port: Option<u16>,
1582    ) -> Self {
1583        self.rescan = Some(SupervisorRescanContext {
1584            supervisor,
1585            config_path: config_path.into(),
1586            configured_port,
1587            storage_config: self.storage_config.clone(),
1588            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1589            admission_facts_targets: self.admission_facts_targets.clone(),
1590            scope_authority_owners: self.scope_authority_owners.clone(),
1591            federated_scope_owner: self.federated_scope_owner.clone(),
1592            privileged_operator_prompt: self.privileged_operator_prompt,
1593            generation: Arc::default(),
1594            module_entries: Arc::default(),
1595        });
1596        self
1597    }
1598
1599    pub(crate) fn with_supervisor_rescan_entries(
1600        self,
1601        modules: &[crate::daemon_config::ConfiguredModule],
1602    ) -> Self {
1603        if let Some(context) = &self.rescan {
1604            let mut entries = context
1605                .module_entries
1606                .lock()
1607                .unwrap_or_else(|e| e.into_inner());
1608            entries.seed(modules);
1609        }
1610        self
1611    }
1612
1613    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1614        self.connected_clients = connected_clients;
1615        self
1616    }
1617
1618    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1619    /// an operator can see a bind failure without reading the daemon log.
1620    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1621        self.local_endpoint_unavailable = reason;
1622        self
1623    }
1624
1625    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1626        Arc::clone(&self.forwarding)
1627    }
1628
1629    pub(crate) fn counters(&self) -> DaemonCounters {
1630        self.counters.clone()
1631    }
1632
1633    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1634    /// requirement event without depending on an operator polling a status command.
1635    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1636        let handler = Arc::downgrade(&self);
1637        let evaluator = self.capability_evaluator.clone();
1638        tokio::spawn(async move {
1639            loop {
1640                evaluator.wait_for_change_or_deadline().await;
1641                let Some(handler) = handler.upgrade() else {
1642                    break;
1643                };
1644                handler.refresh_capability_requirements();
1645            }
1646        });
1647    }
1648
1649    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1650    /// deadline passed during sleep is enforced on the first tick after wake.
1651    /// While no live scope carries a deadline the loop waits for an accepted
1652    /// scope change instead of ticking, so a daemon without deadlines never
1653    /// wakes for expiry.
1654    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1655        let context = scope_expiry::ScopeExpiryContext::new(&self);
1656        let deadline_added = self.scope_deadline_added.clone();
1657        tokio::spawn(async move {
1658            loop {
1659                if !context.has_deadlines() {
1660                    deadline_added.notified().await;
1661                    continue;
1662                }
1663                tokio::time::sleep(Duration::from_secs(1)).await;
1664                if let Err(error) = context.sweep() {
1665                    warn!(%error, "scope expiry sweep failed");
1666                }
1667            }
1668        });
1669    }
1670
1671    #[cfg(test)]
1672    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1673        scope_expiry::ScopeExpiryContext::new(self).sweep()
1674    }
1675
1676    fn publish_scope_changes(
1677        &self,
1678        changes: &[crate::scopes::ScopeTagChange],
1679        expired: &[crate::scopes::ScopeExpired],
1680    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1681        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1682    }
1683
1684    fn runtime_capability_snapshot(
1685        &self,
1686    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1687        let runtime = self
1688            .supervisor
1689            .list()
1690            .into_iter()
1691            .map(|module| {
1692                let status = module.status().map_err(|err| {
1693                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1694                })?;
1695                Ok(RuntimeModule {
1696                    module_id: status.module_id,
1697                    state: status.state,
1698                    enabled: status.enabled,
1699                })
1700            })
1701            .collect::<Result<Vec<_>, RouterError>>()?;
1702        // Include every registration, published or not. The capability
1703        // evaluator counts a module as providing its capabilities as soon as it
1704        // has registered, even before `catalog.list` shows it, so a HELLO in
1705        // progress does not change other modules' required-capability
1706        // verdicts. See `Registry::list_registered_modules`.
1707        let registrations = self.registry.list_registered_modules().map_err(|err| {
1708            RouterError::backend(
1709                0,
1710                0,
1711                format!("failed to list capability registrations: {err}"),
1712            )
1713        })?;
1714        let registrations = registrations
1715            .into_iter()
1716            .map(|registration| RegisteredModule {
1717                module_id: registration.manifest.module_id,
1718                module_version: registration.manifest.module_version,
1719                capabilities: registration.manifest.capabilities,
1720            })
1721            .collect();
1722        Ok((runtime, registrations))
1723    }
1724
1725    /// The capability side effects of a module becoming the active registration
1726    /// for its id: cache its manifest (logging how it differs from the cached
1727    /// one), run the deny census when its declarations call for one, and recompute the
1728    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1729    /// candidate's does not, and the supervisor does it at promotion instead,
1730    /// through [`crate::supervise::SwapPromotionObserver`].
1731    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1732        let cached_registration = RegisteredModule {
1733            module_id: registration.manifest.module_id.clone(),
1734            module_version: registration.manifest.module_version.clone(),
1735            capabilities: registration.manifest.capabilities.clone(),
1736        };
1737        let change = self.capability_evaluator.record_hello(&cached_registration);
1738        log_manifest_change(&cached_registration.module_id, &change);
1739        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1740            self.enforce_capability_denies();
1741        }
1742        self.refresh_capability_requirements();
1743    }
1744
1745    /// Point the shared supervisor handle at this handler for swap promotions.
1746    /// Called wherever a handler is put behind the `Arc` the router serves, so
1747    /// it can be held weakly.
1748    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1749        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1750            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1751        self.supervisor.set_swap_promotion_observer(observer);
1752    }
1753
1754    pub fn refresh_capability_requirements(&self) {
1755        match self.runtime_capability_snapshot() {
1756            Ok((runtime, registrations)) => {
1757                let events = self
1758                    .capability_evaluator
1759                    .evaluate_now(&runtime, &registrations);
1760                if !events.is_empty() {
1761                    self.catalog_readiness_revision
1762                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1763                }
1764                log_requirement_events(events, &self.daemon_shutdown);
1765            }
1766            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1767        }
1768    }
1769
1770    /// Reconcile only live, attested route bindings after a capability deny edge
1771    /// or target claim was added. This is deliberately a control-plane census:
1772    /// the opaque forwarding hot path must not grow a per-frame capability check.
1773    fn enforce_capability_denies(&self) {
1774        let registrations = match self.registry.list_registered_modules() {
1775            Ok(snapshot) => snapshot,
1776            Err(err) => {
1777                warn!(error = %err, "failed to read registrations for capability deny census");
1778                return;
1779            }
1780        };
1781        let manifests = registrations
1782            .into_iter()
1783            .map(|registration| {
1784                (
1785                    registration.manifest.module_id.clone(),
1786                    registration.manifest,
1787                )
1788            })
1789            .collect::<BTreeMap<_, _>>();
1790        let census = match self.forwarding.route_census(None) {
1791            Ok(census) => census,
1792            Err(err) => {
1793                warn!(error = %err, "failed to read route census for capability deny enforcement");
1794                return;
1795            }
1796        };
1797
1798        for (target_module_id, routes) in census {
1799            let Some(target_manifest) = manifests.get(&target_module_id) else {
1800                continue;
1801            };
1802            let mut closed_routes = Vec::new();
1803            let mut goodbyes = Vec::new();
1804            for route in routes {
1805                let Principal::Reserved {
1806                    module_id: opening_module_id,
1807                } = &route.principal
1808                else {
1809                    continue;
1810                };
1811                let Some(opening_manifest) = manifests.get(opening_module_id) else {
1812                    continue;
1813                };
1814                let Some(capability) = denied_capability(
1815                    opening_manifest.capabilities.as_ref(),
1816                    target_manifest.capabilities.as_ref(),
1817                ) else {
1818                    continue;
1819                };
1820
1821                match self.forwarding.release_client_route(
1822                    route.goodbye_target.connection_id,
1823                    route.goodbye_target.channel,
1824                    route.goodbye_target.epoch,
1825                ) {
1826                    Ok(RouteRelease::Removed(module_goodbye)) => {
1827                        warn!(
1828                            opening_module_id,
1829                            target_module_id,
1830                            capability,
1831                            "force-closing route because an attested capability deny edge now matches"
1832                        );
1833                        goodbyes.push(module_goodbye);
1834                        goodbyes.push(route.goodbye_target.clone());
1835                        closed_routes.push(route);
1836                    }
1837                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
1838                    Err(err) => warn!(
1839                        opening_module_id,
1840                        target_module_id,
1841                        capability,
1842                        error = %err,
1843                        "failed to force-close capability-denied route"
1844                    ),
1845                }
1846            }
1847
1848            if closed_routes.is_empty() {
1849                continue;
1850            }
1851            send_route_control_pushes(
1852                &self.forwarding,
1853                closed_routes,
1854                ClientControlPush::RouteClosed {
1855                    module_id: target_module_id,
1856                    channels: Vec::new(),
1857                    reason: RouteCloseReason::CapabilityDenied,
1858                    drained: false,
1859                    abandoned: 0,
1860                    excluded_subscriptions: 0,
1861                    terminal: Some(false),
1862                },
1863            );
1864            // route.closed records the reason; the route GOODBYE ends the
1865            // client's handle and settles any calls still pending on it.
1866            self.emit_route_goodbyes(goodbyes);
1867        }
1868    }
1869
1870    /// Why a registered module is not accepting new route binds, or `None` when
1871    /// it is. This is the module's effective readiness: its declared readiness
1872    /// first, then every `need: required` capability it declares evaluating to
1873    /// `provided`. `route.open` and `catalog.list` both read it here so the
1874    /// catalog never reports a module routable that `route.open` would refuse.
1875    fn not_ready_reason(
1876        &self,
1877        registration: &crate::registry::ModuleRegistration,
1878    ) -> Option<NotReadyReason> {
1879        if !registration.ready {
1880            return Some(NotReadyReason {
1881                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1882                capability: None,
1883            });
1884        }
1885        self.first_unprovided_required_capability(registration)
1886            .map(|capability| NotReadyReason {
1887                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1888                capability: Some(capability),
1889            })
1890    }
1891
1892    /// The lexicographically first capability this registration declares
1893    /// `need: required` whose evaluator verdict is not `provided`.
1894    ///
1895    /// The verdicts are the capability evaluator's own; nothing here decides
1896    /// what "provided" means. The evaluator counts a capability provided as
1897    /// soon as a module claiming it has REGISTERED, not once that module is
1898    /// ready. That distinction is what keeps two modules that require each
1899    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1900    /// is ready", each would wait for the other to become ready first and
1901    /// neither ever would. Do not tighten it to readiness.
1902    ///
1903    /// A required capability with no verdict at all means this registration's
1904    /// HELLO or catalog.update landed after the last recompute; recompute once
1905    /// rather than let a missing verdict read as either answer. If it is still
1906    /// missing (the recompute itself failed) the capability counts as
1907    /// unprovided: the refusal is retryable, and routing a module whose
1908    /// required provider is unknown is the outcome this check exists to stop.
1909    fn first_unprovided_required_capability(
1910        &self,
1911        registration: &crate::registry::ModuleRegistration,
1912    ) -> Option<String> {
1913        self.first_unprovided_required_capability_for(
1914            &registration.manifest.module_id,
1915            registration.manifest.capabilities.as_ref(),
1916        )
1917    }
1918
1919    fn first_unprovided_required_capability_for(
1920        &self,
1921        module_id: &str,
1922        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1923    ) -> Option<String> {
1924        let required = capabilities
1925            .into_iter()
1926            .flat_map(|declarations| declarations.requires.iter())
1927            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1928            .map(|requirement| requirement.capability.as_str())
1929            .collect::<BTreeSet<_>>();
1930        if required.is_empty() {
1931            return None;
1932        }
1933        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1934        if required
1935            .iter()
1936            .any(|capability| verdict(capability).is_none())
1937        {
1938            self.refresh_capability_requirements();
1939        }
1940        required
1941            .into_iter()
1942            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1943            .map(str::to_string)
1944    }
1945
1946    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1947        self.capability_evaluator
1948            .statuses()
1949            .into_iter()
1950            .map(capability_requirement_status)
1951            .collect()
1952    }
1953
1954    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1955    /// registration-release watch. The signal is what the supervisor waits on
1956    /// before spawning a replacement, so it must only fire once forwarding
1957    /// teardown is also done (see [`Self::cleanup_connection`] /
1958    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1959    /// registry-only path below because publication already owns the spawn lock.
1960    fn deregister_connection(
1961        &self,
1962        connection_id: ConnectionId,
1963        reason: RegistrationEndReason,
1964    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1965        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1966            spawn.end_primary_registration();
1967        }
1968        self.registry
1969            .deregister_connection_with_reason(connection_id, reason)
1970    }
1971
1972    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1973    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1974    // or claim-bound consumers to revoke. Remove only its unpublished registry
1975    // entry without re-entering primary-registration teardown.
1976    fn rollback_unpublished_hello(
1977        &self,
1978        connection: ConnectionId,
1979    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1980        self.registry.deregister_connection_with_reason(
1981            connection,
1982            RegistrationEndReason::RegistrationFailed,
1983        )
1984    }
1985
1986    fn request_refusal_close(
1987        &self,
1988        connection: ConnectionId,
1989        sink: Option<&crate::FrameSink>,
1990        reason: CloseReason,
1991    ) {
1992        if let Some(sink) = sink {
1993            sink.terminate_ingress();
1994        }
1995        if self.claims.close_notifications_enabled() {
1996            self.forwarding.request_connection_close(connection, reason);
1997        }
1998    }
1999
2000    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
2001        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
2002            return None;
2003        }
2004        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
2005            parse_client_control_request(&frame.body)
2006        else {
2007            return None;
2008        };
2009        Some(target_module_id(&target).to_string())
2010    }
2011
2012    pub(crate) fn route_open_capacity_refusal(
2013        &self,
2014        ctx: &RouteCtx,
2015        frame: &Frame,
2016        target_module_id: &str,
2017        in_flight: usize,
2018        limit: usize,
2019    ) -> Result<Frame, RouterError> {
2020        // Sent before the request reaches `handle_route_open`, so the caller
2021        // fields come from the raw frame here.
2022        let caller = self.route_open_caller_from_frame(ctx, frame);
2023        self.route_open_admission_refusal_frame(
2024            ctx,
2025            &caller,
2026            frame,
2027            target_module_id,
2028            "open_admission_full",
2029            (in_flight, limit),
2030            format!(
2031                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
2032            ),
2033        )
2034    }
2035
2036    fn route_open_target_capacity_refusal(
2037        &self,
2038        ctx: &RouteCtx,
2039        caller: &RouteOpenCaller,
2040        frame: &Frame,
2041        target_module_id: &str,
2042        in_flight: usize,
2043    ) -> Result<Frame, RouterError> {
2044        self.route_open_admission_refusal_frame(
2045            ctx,
2046            caller,
2047            frame,
2048            target_module_id,
2049            "target_binds_full",
2050            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
2051            format!(
2052                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
2053            ),
2054        )
2055    }
2056
2057    /// Admission pressure clears as existing binds settle, so its refusal must
2058    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
2059    /// `module_reloading`, `module_warming`, `target_unavailable`, or
2060    /// `module_timeout`. `target_unavailable` is honest for an attempt that
2061    /// cannot currently reach its target; `module_timeout` would falsely claim
2062    /// that a wait expired. A new, cleaner code would be terminal to deployed
2063    /// clients, so it requires a client-tolerance rollout before daemon emission.
2064    #[allow(clippy::too_many_arguments)]
2065    fn route_open_admission_refusal_frame(
2066        &self,
2067        ctx: &RouteCtx,
2068        caller: &RouteOpenCaller,
2069        frame: &Frame,
2070        target_module_id: &str,
2071        reason: &'static str,
2072        (in_flight, limit): (usize, usize),
2073        message: impl Into<String>,
2074    ) -> Result<Frame, RouterError> {
2075        let code = error_codes::TARGET_UNAVAILABLE;
2076        self.counters.increment_route_open_refused(code);
2077        info!(
2078            target: "control",
2079            code,
2080            reason,
2081            module_id = ?target_module_id,
2082            connection_id = ctx.connection_id.get(),
2083            principal = %caller.principal,
2084            scope = %caller.scope,
2085            harness = %caller.harness,
2086            in_flight,
2087            limit,
2088            "route.open refused"
2089        );
2090        control_error_frame(frame, code, message.into())
2091    }
2092
2093    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
2094    ///
2095    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
2096    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
2097    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
2098    #[cfg(test)]
2099    pub fn handle_control(
2100        &self,
2101        connection_id: ConnectionId,
2102        frame: Frame,
2103    ) -> Result<Vec<Frame>, RouterError> {
2104        match frame.header.ty {
2105            FrameType::Ping => Ok(vec![pong(&frame)?]),
2106            FrameType::Hello => self.handle_hello(connection_id, None, frame),
2107            FrameType::Goodbye => self.handle_goodbye(connection_id),
2108            ty => Ok(vec![control_error_frame(
2109                &frame,
2110                "unsupported_control_frame",
2111                format!("unsupported channel-0 frame {ty:?}"),
2112            )?]),
2113        }
2114    }
2115
2116    pub async fn handle_control_frame(
2117        &self,
2118        ctx: &RouteCtx,
2119        frame: Frame,
2120    ) -> Result<Vec<Frame>, RouterError> {
2121        self.handle_control_frame_timed(ctx, frame, None).await
2122    }
2123
2124    #[cfg(any(test, feature = "test-support"))]
2125    pub fn with_test_operator_app_policy(
2126        mut self,
2127        policy: crate::operator_apps::TestOperatorAppPolicy,
2128    ) -> Self {
2129        self.operator_app_policy = policy.into();
2130        self
2131    }
2132
2133    /// Inject the Windows signature check for tests. The injected check
2134    /// answers the verified version string or the rejection reason; the
2135    /// daemon enforces the floor itself on the returned version.
2136    #[cfg(all(windows, any(test, feature = "test-support")))]
2137    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
2138        self.windows_verify = Some(verify);
2139        self
2140    }
2141
2142    /// Record which pids the daemon would flash for `already_running`.
2143    #[cfg(all(windows, any(test, feature = "test-support")))]
2144    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
2145        self.windows_flash = Some(flash);
2146        self
2147    }
2148
2149    /// Inject a tracking failure for tests: makes `track_launched_process`
2150    /// fail so a test can prove a launch that cannot be tracked is stopped,
2151    /// never left running.
2152    #[cfg(all(windows, any(test, feature = "test-support")))]
2153    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2154        self.windows_track = Some(track);
2155        self
2156    }
2157
2158    pub(crate) fn record_captured_peer(
2159        &self,
2160        connection: ConnectionId,
2161        peer: subc_os::local_peer::CapturedPeer,
2162    ) {
2163        self.record_observed_peer(connection, peer.observation().clone());
2164        let identity = self.operator_app_policy.config_identity(peer.clone());
2165        #[cfg(windows)]
2166        let identity = identity.or_else(|| self.config_windows_launch_identity(&peer));
2167        if let Some(identity) = identity {
2168            // Keep the connect-time launch incarnation. Looking it up afresh
2169            // from a numeric pipe-client PID could match a later reused PID.
2170            self.config_desktop_stamps
2171                .lock()
2172                .unwrap_or_else(|p| p.into_inner())
2173                .insert(connection, identity);
2174        }
2175        self.captured_peers
2176            .lock()
2177            .unwrap_or_else(|p| p.into_inner())
2178            .insert(connection, peer.clone());
2179        #[cfg(windows)]
2180        if let Some(stamp) = self.stamp_windows_launch(&peer) {
2181            self.operator_apps
2182                .lock()
2183                .unwrap_or_else(|p| p.into_inner())
2184                .insert(connection, stamp);
2185        }
2186        if let Some(stamp) = self.operator_app_policy.stamp(peer) {
2187            self.operator_apps
2188                .lock()
2189                .unwrap_or_else(|p| p.into_inner())
2190                .insert(connection, stamp);
2191        }
2192    }
2193
2194    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2195        self.local_connections
2196            .lock()
2197            .unwrap_or_else(|p| p.into_inner())
2198            .insert(connection);
2199    }
2200
2201    // Keep the connection-level delivery decision shared with route.bind. The
2202    // target's capability opt-in is separate from recognition of the caller.
2203    fn connection_operator_app(
2204        &self,
2205        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2206    ) -> Option<subc_protocol::peer::OperatorApp> {
2207        stamp
2208            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2209            .map(|stamp| stamp.app.clone())
2210    }
2211
2212    fn handle_connection_describe(
2213        &self,
2214        ctx: &RouteCtx,
2215        frame: Frame,
2216    ) -> Result<Vec<Frame>, RouterError> {
2217        if serde_json::from_slice::<subc_control::ConnectionDescribeRequest>(&frame.body).is_err() {
2218            return Ok(vec![control_error_frame(
2219                &frame,
2220                "invalid_control_body",
2221                "malformed connection.describe body",
2222            )?]);
2223        }
2224        let local = self
2225            .local_connections
2226            .lock()
2227            .unwrap_or_else(|p| p.into_inner())
2228            .contains(&ctx.connection_id);
2229        let stamps = self.operator_apps.lock().unwrap_or_else(|p| p.into_inner());
2230        let operator_app = self.connection_operator_app(stamps.get(&ctx.connection_id));
2231        Ok(vec![control_response_body_frame(
2232            &frame,
2233            &subc_control::ConnectionDescribeReply::new(local, operator_app),
2234            ops::CONNECTION_DESCRIBE,
2235        )?])
2236    }
2237
2238    pub(crate) fn record_observed_peer(
2239        &self,
2240        connection: ConnectionId,
2241        peer: subc_os::local_peer::ObservedPeer,
2242    ) {
2243        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2244        let peer = match peer {
2245            OsPeer::Unobserved => ObservedPeer::unobserved(),
2246            OsPeer::Observed(peer) => {
2247                let observed = match peer.user {
2248                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2249                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2250                };
2251                observed
2252                    .with_exe(
2253                        peer.exe
2254                            .and_then(|path| path.into_os_string().into_string().ok()),
2255                    )
2256                    .with_signing_id(peer.signing_id)
2257            }
2258        };
2259        self.observed_peers
2260            .lock()
2261            .unwrap_or_else(|p| p.into_inner())
2262            .insert(connection, peer);
2263    }
2264
2265    pub(crate) fn record_caller_endpoints(
2266        &self,
2267        connection: ConnectionId,
2268        endpoints: Option<(SocketAddr, SocketAddr)>,
2269    ) {
2270        let mut callers = self
2271            .caller_endpoints
2272            .lock()
2273            .unwrap_or_else(|p| p.into_inner());
2274        callers.remove(&connection);
2275        if let Some(endpoints) = endpoints {
2276            callers.insert(connection, endpoints);
2277        }
2278    }
2279
2280    #[cfg(test)]
2281    pub(crate) fn with_caller_lookup_for_test(
2282        mut self,
2283        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2284    ) -> Self {
2285        self.caller_lookup = Some(Arc::new(lookup));
2286        self
2287    }
2288
2289    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2290        let endpoints = self
2291            .caller_endpoints
2292            .lock()
2293            .unwrap_or_else(|p| p.into_inner())
2294            .get(&connection)
2295            .copied();
2296        #[cfg(test)]
2297        let lookup = self.caller_lookup.clone();
2298        tokio::task::spawn_blocking(move || {
2299            #[cfg(test)]
2300            if let Some(lookup) = lookup {
2301                return lookup(endpoints);
2302            }
2303            endpoints
2304                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2305                .unwrap_or_default()
2306        })
2307        .await
2308        .unwrap_or_default()
2309    }
2310
2311    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2312        frame.header.channel == 0
2313            && frame.header.ty == FrameType::Request
2314            && self
2315                .forwarding
2316                .module_endpoint_for_connection(ctx.connection_id)
2317                .is_ok_and(|endpoint| endpoint.is_none())
2318            && parse_client_control_request(&frame.body)
2319                .ok()
2320                .is_some_and(|request| privileged_operation(&request).is_some())
2321    }
2322
2323    pub(crate) async fn handle_control_frame_timed(
2324        &self,
2325        ctx: &RouteCtx,
2326        frame: Frame,
2327        dispatch_started_at: Option<StdInstant>,
2328    ) -> Result<Vec<Frame>, RouterError> {
2329        let first = ctx.egress.first_ingress_frame();
2330        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2331            .await
2332    }
2333
2334    pub(crate) async fn handle_control_frame_ingress(
2335        &self,
2336        ctx: &RouteCtx,
2337        frame: Frame,
2338        dispatch_started_at: Option<StdInstant>,
2339        first: bool,
2340    ) -> Result<Vec<Frame>, RouterError> {
2341        if ctx.egress.ingress_terminal() {
2342            return Ok(Vec::new());
2343        }
2344        #[cfg(test)]
2345        self.claims.record_dispatch(frame.header.corr);
2346        let claim_binding = self.claims.binding(ctx.connection_id);
2347        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2348            && claim_binding
2349                .as_ref()
2350                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2351        .then(|| self.prefix_hello_attempt(ctx));
2352        if claim_binding
2353            .as_ref()
2354            .is_some_and(|binding| binding.prefix_module_id().is_some())
2355        {
2356            let registered = self
2357                .forwarding
2358                .module_endpoint_for_connection(ctx.connection_id)
2359                .map_err(RouterError::Forwarding)?
2360                .is_some();
2361            if !registered && frame.header.ty != FrameType::Hello {
2362                return self
2363                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2364                    .await;
2365            }
2366            if registered && frame.header.ty == FrameType::Goodbye {
2367                ctx.egress.terminate_ingress();
2368                let result = self.handle_goodbye(ctx.connection_id);
2369                self.claims.connection_closed(ctx.connection_id);
2370                self.request_refusal_close(
2371                    ctx.connection_id,
2372                    Some(&ctx.egress),
2373                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2374                );
2375                return result;
2376            }
2377            if registered && frame.header.ty == FrameType::Request {
2378                let allowed =
2379                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2380                        matches!(
2381                            probe.op.as_str(),
2382                            "catalog.update"
2383                                | "catalog.update_role_declarations"
2384                                | "scope.describe"
2385                                | "scope.watch"
2386                                | "supervisor.live_roots"
2387                                | "activity.record"
2388                        )
2389                    });
2390                if !allowed {
2391                    return Ok(vec![control_error_frame(
2392                        &frame,
2393                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2394                        "prefix registrations have only brokered module operations",
2395                    )?]);
2396                }
2397            }
2398            if registered
2399                && frame.header.ty == FrameType::Push
2400                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2401                    .is_ok_and(|probe| probe.op == "route.status")
2402            {
2403                return Ok(vec![control_error_frame(
2404                    &frame,
2405                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2406                    "prefix registrations may push only route.status for routes they serve",
2407                )?]);
2408            }
2409        }
2410        match frame.header.ty {
2411            FrameType::Ping => Ok(vec![pong(&frame)?]),
2412            FrameType::Hello => {
2413                if claim_binding
2414                    .as_ref()
2415                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2416                {
2417                    return self
2418                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2419                        .await;
2420                }
2421                // Resolved once, here: the blocking HELLO below may outlive this
2422                // reader and run after cleanup has forgotten the channel, and it
2423                // must still be judged as this channel's HELLO.
2424                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2425                if let Some(spawn) = &channel_spawn {
2426                    spawn.wait_launch().await;
2427                    // Refused launches close the channel. Leave their pending
2428                    // HELLO unanswered instead of racing a reply against shutdown.
2429                    if !spawn.launch_ready() {
2430                        ctx.egress.terminate_ingress();
2431                        return Ok(Vec::new());
2432                    }
2433                    #[cfg(test)]
2434                    self.pause_hello_ingress_for_test().await;
2435                } else if claim_binding.is_none() {
2436                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2437                        if let (Some(module), Some(nonce)) = (
2438                            hello
2439                                .get("manifest")
2440                                .and_then(|value| value.get("module_id"))
2441                                .and_then(|value| value.as_str()),
2442                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2443                        ) {
2444                            if !self
2445                                .config_runtime
2446                                .as_ref()
2447                                .is_some_and(|owner| owner.module_is_gated(module))
2448                                && !self.supervisor.wait_program_binding(module, nonce).await
2449                            {
2450                                self.request_refusal_close(
2451                                    ctx.connection_id,
2452                                    Some(&ctx.egress),
2453                                    CloseReason::new(
2454                                        "program_refused",
2455                                        "the spawned program binding failed",
2456                                    ),
2457                                );
2458                                return Ok(vec![control_error_frame(
2459                                    &frame,
2460                                    if self
2461                                        .config_runtime
2462                                        .as_ref()
2463                                        .is_some_and(|owner| owner.is_recovering())
2464                                    {
2465                                        "config_gated"
2466                                    } else {
2467                                        "program_refused"
2468                                    },
2469                                    "the spawned program binding failed",
2470                                )?]);
2471                            }
2472                        }
2473                    }
2474                }
2475                let handler = self.clone();
2476                let connection = ctx.connection_id;
2477                let egress = ctx.egress.clone();
2478                let correlation = frame.header.corr;
2479                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2480                let span = tracing::Span::current();
2481                let hello_binding = claim_binding.clone();
2482                let replies = tokio::task::spawn_blocking(move || {
2483                    tracing::dispatcher::with_default(&dispatcher, || {
2484                        span.in_scope(|| {
2485                            handler.handle_hello_checked(
2486                                connection,
2487                                Some(egress),
2488                                frame,
2489                                true,
2490                                hello_binding,
2491                                channel_spawn,
2492                            )
2493                        })
2494                    })
2495                })
2496                .await
2497                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2498                #[cfg(test)]
2499                if prefix_attempt.is_some() {
2500                    self.claims.pause_prefix_commit_for_test(false).await;
2501                }
2502                if let Some(attempt) = &mut prefix_attempt {
2503                    let accepted = !replies
2504                        .iter()
2505                        .any(|reply| reply.header.ty == FrameType::Error)
2506                        && self
2507                            .registry
2508                            .get_module_by_connection(ctx.connection_id)
2509                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2510                            .is_some();
2511                    if accepted {
2512                        attempt.accepted = true;
2513                    } else {
2514                        ctx.egress.terminate_ingress();
2515                        for reply in replies {
2516                            ctx.egress.send_flushed(reply).await?;
2517                        }
2518                        return Ok(Vec::new());
2519                    }
2520                }
2521                Ok(replies)
2522            }
2523            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2524            FrameType::Cancel => {
2525                // Channel-0 cancellation withdraws approvals and subscriptions
2526                // and fences pending agent declarations;
2527                // successful cancellation has no ordinary reply.
2528                // A config Apply may also own an OS prompt. Cancel that prompt
2529                // before config cancellation can report the request handled.
2530                if self
2531                    .agent_declarations
2532                    .cancel(ctx.connection_id, frame.header.corr)
2533                    || self
2534                        .forwarding
2535                        .operator_confirms()
2536                        .cancel(ctx.connection_id, frame.header.corr)
2537                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2538                    || self
2539                        .supervisor
2540                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2541                    || self.cancel_activity_subscription(ctx, &frame)?
2542                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2543                    || self
2544                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2545                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2546                {
2547                    Ok(Vec::new())
2548                } else {
2549                    Ok(vec![control_error_frame(
2550                        &frame,
2551                        "unknown_subscription",
2552                        "no subscription has this correlation id",
2553                    )?])
2554                }
2555            }
2556            FrameType::Request => {
2557                // This additive operation is not part of the existing exhaustive
2558                // module-control enum. Probe the op before decoding that enum.
2559                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2560                if let Some(probe) = &op {
2561                    self.record_control_usage(ctx.connection_id, &probe.op);
2562                }
2563                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2564                if let Some(refusal) = self
2565                    .recovery_request_refusal(
2566                        ctx,
2567                        &frame,
2568                        op.as_ref().map(|probe| probe.op.as_str()),
2569                    )
2570                    .await?
2571                {
2572                    if claim_present {
2573                        self.reclaim_presented_expiry(&frame);
2574                        return self
2575                            .refuse_claim_connection(ctx, &frame, "config_gated")
2576                            .await;
2577                    }
2578                    return Ok(vec![refusal]);
2579                }
2580                if claim_present {
2581                    return self.handle_claim_present(ctx, &frame, first).await;
2582                }
2583                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2584                    return self.handle_claim_mint(ctx, &frame).await;
2585                }
2586                if let Some(refusal) = self.registration_operation_refusal(
2587                    ctx,
2588                    &frame,
2589                    op.as_ref().map(|probe| probe.op.as_str()),
2590                )? {
2591                    return Ok(vec![refusal]);
2592                }
2593                if op
2594                    .as_ref()
2595                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2596                {
2597                    return self.handle_catalog_watch(ctx, frame);
2598                }
2599                if op
2600                    .as_ref()
2601                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2602                {
2603                    return self.handle_scope_watch(ctx, frame);
2604                }
2605                if op
2606                    .as_ref()
2607                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2608                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2609                        .unwrap_or(false)
2610                {
2611                    return Ok(vec![control_error_frame(
2612                        &frame,
2613                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2614                        "provider_declarations are fixed at HELLO; restart the module to change them",
2615                    )?]);
2616                }
2617                if let Some(probe) = op
2618                    .as_ref()
2619                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2620                {
2621                    return self
2622                        .handle_module_config_request(ctx, frame, &probe.op)
2623                        .await;
2624                }
2625                if op
2626                    .as_ref()
2627                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2628                {
2629                    return self.handle_config_gate_request(ctx, frame).await;
2630                }
2631                if op
2632                    .as_ref()
2633                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2634                {
2635                    return self.handle_activity_record(ctx, frame).await;
2636                }
2637                if op.as_ref().is_some_and(|probe| {
2638                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2639                }) {
2640                    return self.handle_activity_read(ctx, frame).await;
2641                }
2642                if op
2643                    .as_ref()
2644                    .is_some_and(|probe| probe.op == "operator.confirm")
2645                {
2646                    return self.handle_operator_confirm(ctx, frame);
2647                }
2648                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2649                    return self
2650                        .observe_control_wait(
2651                            ctx,
2652                            None,
2653                            ops::APP_OPEN,
2654                            self.handle_app_open(ctx, frame),
2655                        )
2656                        .await;
2657                }
2658                if op
2659                    .as_ref()
2660                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2661                {
2662                    return self.handle_connection_describe(ctx, frame);
2663                }
2664                if op
2665                    .as_ref()
2666                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2667                {
2668                    return self.handle_scope_served_by(ctx.connection_id, frame);
2669                }
2670                if self
2671                    .forwarding
2672                    .module_endpoint_for_connection(ctx.connection_id)
2673                    .map_err(RouterError::Forwarding)?
2674                    .is_some()
2675                {
2676                    if !is_known_module_request_op(&frame.body) {
2677                        return Ok(vec![control_error_frame(
2678                            &frame,
2679                            "unsupported_control_frame",
2680                            "module-originated channel-0 REQUEST is not supported",
2681                        )?]);
2682                    }
2683                    let request = match parse_module_control_request_from_module(&frame.body) {
2684                        Ok(request) => request,
2685                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2686                            return Ok(vec![control_error_frame(
2687                                &frame,
2688                                "unsupported_control_frame",
2689                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2690                            )?])
2691                        }
2692                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2693                            return Ok(vec![control_error_frame(
2694                                &frame,
2695                                "invalid_control_body",
2696                                format!("malformed module control body: {err}"),
2697                            )?])
2698                        }
2699                    };
2700                    let op = module_control_request_op(&request);
2701                    let corr = frame.header.corr;
2702                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2703                    if let ModuleControlRequestFromModule::AgentCommands {
2704                        started,
2705                        finished,
2706                        known,
2707                    } = request
2708                    {
2709                        return self
2710                            .agent_declarations
2711                            .enqueue(
2712                                self,
2713                                ctx,
2714                                frame,
2715                                crate::resource_totals::Declaration {
2716                                    started,
2717                                    finished,
2718                                    known,
2719                                },
2720                            )
2721                            .await;
2722                    }
2723                    let result =
2724                        self.handle_module_control_request(ctx.connection_id, frame, request);
2725                    log_slow_control_dispatch(
2726                        dispatch_started_at,
2727                        op,
2728                        ctx.connection_id,
2729                        corr,
2730                        None,
2731                    );
2732                    return result;
2733                }
2734
2735                if is_known_module_request_op(&frame.body) {
2736                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2737                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2738                    let code = if is_agents {
2739                        "not_supervised"
2740                    } else if op
2741                        .as_ref()
2742                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2743                    {
2744                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2745                    } else {
2746                        "not_registered"
2747                    };
2748                    return Ok(vec![control_error_frame(
2749                        &frame,
2750                        code,
2751                        "module-originated control requests require the module's own registered connection",
2752                    )?]);
2753                }
2754
2755                let request = match parse_client_control_request(&frame.body) {
2756                    Ok(request) => request,
2757                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2758                        return Ok(vec![control_error_frame(
2759                            &frame,
2760                            "unknown_control_op",
2761                            format!("unknown client control op: {err}"),
2762                        )?])
2763                    }
2764                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2765                        return Ok(vec![control_error_frame(
2766                            &frame,
2767                            "invalid_control_body",
2768                            format!("malformed client control body: {err}"),
2769                        )?])
2770                    }
2771                };
2772                let op = client_control_request_op(&request);
2773                let corr = frame.header.corr;
2774                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2775                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2776                #[cfg(test)]
2777                if let Some(delay) = self.control_dispatch_delay {
2778                    tokio::time::sleep(delay).await;
2779                }
2780                let result = self
2781                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2782                    .await;
2783                if let Some(timings) = route_open_timings.as_mut() {
2784                    timings.finish();
2785                }
2786                log_slow_control_dispatch(
2787                    dispatch_started_at,
2788                    op,
2789                    ctx.connection_id,
2790                    corr,
2791                    route_open_timings.as_ref(),
2792                );
2793                result
2794            }
2795            FrameType::Push => {
2796                let Some(endpoint) = self
2797                    .forwarding
2798                    .module_endpoint_for_connection(ctx.connection_id)
2799                    .map_err(RouterError::Forwarding)?
2800                else {
2801                    return Ok(vec![control_error_frame(
2802                        &frame,
2803                        "unsupported_control_frame",
2804                        "client-originated channel-0 PUSH is not supported",
2805                    )?]);
2806                };
2807                self.handle_status_update(endpoint, frame)
2808            }
2809            FrameType::Response | FrameType::Error
2810                if self
2811                    .forwarding
2812                    .module_endpoint_for_connection(ctx.connection_id)
2813                    .map_err(RouterError::Forwarding)?
2814                    .is_some() =>
2815            {
2816                self.handle_module_relay_response(ctx.connection_id, frame)
2817            }
2818            ty => Ok(vec![control_error_frame(
2819                &frame,
2820                "unsupported_control_frame",
2821                format!("unsupported channel-0 frame {ty:?}"),
2822            )?]),
2823        }
2824    }
2825
2826    #[cfg(test)]
2827    fn pause_cleanup_for_test(&self, stage: u8) {
2828        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2829        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2830            let (_, (reached, release)) = slot.take().unwrap();
2831            drop(slot);
2832            let _ = reached.send(());
2833            let _ = release.recv_timeout(Duration::from_secs(5));
2834        }
2835    }
2836
2837    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2838    /// right after the nonce is resolved.
2839    #[cfg(all(test, unix, feature = "test-support"))]
2840    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2841        *self
2842            .after_nonce_attestation
2843            .lock()
2844            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2845    }
2846
2847    #[cfg(test)]
2848    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2849        let hook = self
2850            .after_nonce_attestation
2851            .lock()
2852            .unwrap_or_else(|p| p.into_inner())
2853            .take();
2854        if let Some(hook) = hook {
2855            hook();
2856        }
2857    }
2858
2859    #[cfg(test)]
2860    async fn pause_hello_ingress_for_test(&self) {
2861        let pause = self
2862            .hello_ingress_pause
2863            .lock()
2864            .unwrap_or_else(|p| p.into_inner())
2865            .take();
2866        if let Some((reached, release)) = pause {
2867            let _ = reached.send(());
2868            let _ = release.await;
2869        }
2870    }
2871
2872    pub fn cleanup_connection(
2873        &self,
2874        connection_id: ConnectionId,
2875    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2876        // The server loop joins its offloaded request tasks (route opens,
2877        // privileged requests and activity reads) before this cleanup runs, and
2878        // inline dispatch has ended. Two kinds of work are not joined. Agent
2879        // command declarations run on their queue's detached worker, so the
2880        // queue is closed first: every declaration still queued or validating
2881        // has its commit fence cancelled before anything below can change how
2882        // the connection resolves. A HELLO whose reader was dropped keeps
2883        // running on its blocking thread. It carries the channel spawn its
2884        // reader resolved at ingress instead of re-reading the index forgotten
2885        // below, so it is still judged as that channel's HELLO: the retired
2886        // spawn refuses it before it records anything, and a channel HELLO
2887        // never records a launch nonce, so it cannot leave this connection any
2888        // nonce authority.
2889        self.agent_declarations.close(connection_id);
2890        self.close_catalog_subscriptions(connection_id);
2891        self.close_config_settings_subscriptions(connection_id);
2892        self.close_scope_subscriptions(connection_id);
2893        #[cfg(test)]
2894        self.pause_cleanup_for_test(0);
2895        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2896            spawn.retire_registration_channel();
2897        }
2898        self.supervisor
2899            .forget_registration_connection(connection_id);
2900        #[cfg(test)]
2901        self.pause_cleanup_for_test(1);
2902        self.local_connections
2903            .lock()
2904            .unwrap_or_else(|p| p.into_inner())
2905            .remove(&connection_id);
2906        self.caller_endpoints
2907            .lock()
2908            .unwrap_or_else(|p| p.into_inner())
2909            .remove(&connection_id);
2910        self.build_class_warned
2911            .lock()
2912            .unwrap_or_else(|p| p.into_inner())
2913            .remove(&connection_id);
2914        self.observed_peers
2915            .lock()
2916            .unwrap_or_else(|p| p.into_inner())
2917            .remove(&connection_id);
2918        self.captured_peers
2919            .lock()
2920            .unwrap_or_else(|p| p.into_inner())
2921            .remove(&connection_id);
2922        self.config_desktop_stamps
2923            .lock()
2924            .unwrap_or_else(|p| p.into_inner())
2925            .remove(&connection_id);
2926        self.operator_apps
2927            .lock()
2928            .unwrap_or_else(|p| p.into_inner())
2929            .remove(&connection_id);
2930        self.forwarding
2931            .operator_confirms()
2932            .connection_closed(connection_id);
2933        let cleanup = self.cleanup_connection_with_end_reason(
2934            connection_id,
2935            RegistrationEndReason::ConnectionClosed,
2936        );
2937        // A draining writer can still be reached by a route until forwarding
2938        // cleanup finishes. Keep its claim sink visible to launch retirement.
2939        self.claims.connection_closed(connection_id);
2940        cleanup
2941    }
2942
2943    fn cleanup_connection_with_end_reason(
2944        &self,
2945        connection_id: ConnectionId,
2946        requested_reason: RegistrationEndReason,
2947    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2948        #[cfg(test)]
2949        if let Some(pause) = self
2950            .activity_request_pause
2951            .lock()
2952            .unwrap()
2953            .as_ref()
2954            .filter(|pause| pause.connection == connection_id)
2955        {
2956            pause
2957                .cleanup_started
2958                .store(true, std::sync::atomic::Ordering::Release);
2959        }
2960        if let Some(runtime) = &self.config_runtime {
2961            runtime.disconnected(connection_id);
2962        }
2963        self.agent_declarations.close(connection_id);
2964        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2965            self.registry
2966                .get_module_by_connection(connection_id)?
2967                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2968                .and_then(|module| module.registration_end_reason().ok().flatten())
2969                .unwrap_or(requested_reason)
2970        } else {
2971            requested_reason
2972        };
2973        let crash_closed = self
2974            .registry
2975            .get_module_by_connection(connection_id)?
2976            .and_then(|registration| {
2977                self.forwarding
2978                    .module_endpoint_for_connection(connection_id)
2979                    .ok()
2980                    .flatten()
2981                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2982                    .map(|routes| (registration.manifest.module_id, routes))
2983            });
2984        let crash_closed = crash_closed.map(|(module_id, routes)| {
2985            let terminal = match self.supervisor.get(&module_id) {
2986                None => false,
2987                Some(module) => match module.will_recover_after_connection_loss() {
2988                    Ok(will_recover) => !will_recover,
2989                    Err(err) => {
2990                        warn!(
2991                            %module_id,
2992                            error = %err,
2993                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2994                        );
2995                        false
2996                    }
2997                },
2998            };
2999            // The forwarding table gates all providers at the start of daemon
3000            // shutdown, before their connections are closed. An ordinary
3001            // module disconnect still reports crash if that gate is not set.
3002            let (reason, drained) = match self
3003                .forwarding
3004                .daemon_drain_result_for_connection(connection_id)
3005            {
3006                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
3007                Ok(None) => (RouteCloseReason::Crash, false),
3008                Err(err) => {
3009                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
3010                    (RouteCloseReason::Crash, false)
3011                }
3012            };
3013            (module_id, routes, reason, drained, terminal)
3014        });
3015        let registrations = self.deregister_connection(connection_id, end_reason);
3016        // Read before teardown: the spawn whose registration this connection
3017        // was. Its registration ending is an authority change for it.
3018        let ended_authority = self
3019            .forwarding
3020            .target_authority_for_connection(connection_id)
3021            .ok()
3022            .flatten();
3023        let cleanup = if crash_closed.is_some() {
3024            self.forwarding.cleanup_connection_counted(connection_id)
3025        } else {
3026            // A module connection's teardown needs the count of abandoned
3027            // route.bind relays for its route.closed notice below. Any other
3028            // connection, such as a client's, sends no such notice and needs
3029            // only its routes released, so it uses the route-only wrapper and
3030            // reports zero.
3031            self.forwarding
3032                .cleanup_connection(connection_id)
3033                .map(|released| crate::forwarding::ConnectionCleanup {
3034                    released,
3035                    abandoned_relays: 0,
3036                })
3037        };
3038        // The route.closed push waits for forwarding teardown because only
3039        // teardown knows how many pending route.bind relays it aborted. It still
3040        // goes out before the GOODBYEs for the released routes, and its targets
3041        // were captured above, before teardown removed those routes.
3042        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
3043            let abandoned = cleanup
3044                .as_ref()
3045                .map_or(0, |cleanup| cleanup.abandoned_relays);
3046            send_route_control_pushes(
3047                &self.forwarding,
3048                routes,
3049                ClientControlPush::RouteClosed {
3050                    module_id,
3051                    channels: Vec::new(),
3052                    reason,
3053                    drained,
3054                    abandoned,
3055                    excluded_subscriptions: 0,
3056                    terminal: Some(terminal),
3057                },
3058            );
3059        }
3060        if let Ok(cleanup) = cleanup {
3061            self.emit_route_goodbyes(cleanup.released);
3062        }
3063        if let Some(record) = ended_authority {
3064            self.change_spawn_authority(&record);
3065        }
3066        // Signal the registration-release watch only now that BOTH registry and
3067        // forwarding teardown are done, so a supervisor waiting to spawn a
3068        // replacement never observes release while old routes still exist.
3069        if matches!(&registrations, Ok(r) if !r.is_empty()) {
3070            crate::supervise::notify_registration_release();
3071            self.capability_evaluator.wake_deadline_loop();
3072            self.refresh_capability_requirements();
3073        }
3074        self.supervisor.remove_spawn_subscribers(connection_id);
3075        self.activity_streams
3076            .lock()
3077            .unwrap_or_else(|p| p.into_inner())
3078            .retain(|(id, _), task| {
3079                if *id == connection_id {
3080                    task.abort();
3081                    false
3082                } else {
3083                    true
3084                }
3085            });
3086        // Sync authority dies with its connection, so the owner's next
3087        // connection can take it; the owner's scopes stay as they are.
3088        self.hello_launch_nonces
3089            .lock()
3090            .unwrap_or_else(|poisoned| poisoned.into_inner())
3091            .forget(connection_id);
3092        self.scopes
3093            .write()
3094            .unwrap_or_else(|poisoned| poisoned.into_inner())
3095            .release_connection(connection_id);
3096        registrations
3097    }
3098
3099    pub(crate) fn handle_route_goodbye(
3100        &self,
3101        connection_id: ConnectionId,
3102        route_channel: u16,
3103        route_epoch: u32,
3104    ) -> Result<bool, RouterError> {
3105        debug!(
3106            connection_id = connection_id.get(),
3107            route_channel, route_epoch, "handling route GOODBYE"
3108        );
3109        let RouteRelease::Removed(released_route) = self
3110            .forwarding
3111            .release_client_route(connection_id, route_channel, route_epoch)
3112            .map_err(RouterError::Forwarding)?
3113        else {
3114            return Ok(false);
3115        };
3116        self.emit_route_goodbyes(vec![released_route]);
3117        Ok(true)
3118    }
3119
3120    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
3121        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
3122    }
3123
3124    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
3125    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
3126    /// own commit failed after the module had already accepted). Without this, a
3127    /// module that accepts late keeps a binding subc has torn down, so a later
3128    /// frame on that module channel could misdeliver if the channel is reused.
3129    ///
3130    /// Never closes the shared module connection on failure: a dropped notification
3131    /// only wastes a bounded amount of warm module-side state, which the module's
3132    /// own idle reaper reclaims. Only call this once the route.bind relay was
3133    /// actually enqueued to the module — if the relay send itself failed, the
3134    /// module never created a binding and there is nothing to tear down.
3135    fn send_abandoned_route_bind_goodbye(
3136        &self,
3137        module_sink: &crate::FrameSink,
3138        negotiated_ver: u8,
3139        module_channel: u16,
3140        module_epoch: u32,
3141    ) {
3142        let frame = match Frame::build_with_version(
3143            negotiated_ver,
3144            FrameType::Goodbye,
3145            control_flags(),
3146            module_channel,
3147            module_epoch,
3148            0,
3149            Vec::new(),
3150        ) {
3151            Ok(frame) => frame,
3152            Err(err) => {
3153                warn!(
3154                    route_channel = module_channel,
3155                    error = %err,
3156                    "failed to build GOODBYE for abandoned route.bind"
3157                );
3158                return;
3159            }
3160        };
3161        crate::forwarding::send_module_route_goodbye(
3162            &self.counters,
3163            module_sink,
3164            frame,
3165            None,
3166            "abandoned route.bind",
3167        );
3168    }
3169
3170    #[cfg(test)]
3171    fn handle_hello(
3172        &self,
3173        connection_id: ConnectionId,
3174        egress: Option<crate::router::FrameSink>,
3175        frame: Frame,
3176    ) -> Result<Vec<Frame>, RouterError> {
3177        let binding = self.claims.binding(connection_id);
3178        let channel_spawn = self.supervisor.registration_spawn(connection_id);
3179        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
3180    }
3181
3182    fn handle_hello_checked(
3183        &self,
3184        connection_id: ConnectionId,
3185        sink: Option<crate::FrameSink>,
3186        frame: Frame,
3187        wait_for_gate: bool,
3188        prefix_binding: Option<claims::ClaimBinding>,
3189        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3190    ) -> Result<Vec<Frame>, RouterError> {
3191        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
3192        #[cfg(test)]
3193        if prefix_binding.is_some() {
3194            self.claims.pause_prefix_hello_for_test(5);
3195            match self.claims.take_prefix_hello_failure_for_test() {
3196                Some("error") => {
3197                    return Err(RouterError::backend(
3198                        0,
3199                        frame.header.corr,
3200                        "injected HELLO failure",
3201                    ))
3202                }
3203                Some("panic") => panic!("injected HELLO task panic"),
3204                _ => {}
3205            }
3206        }
3207        if let Some(binding) = &prefix_binding {
3208            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3209            let module = value
3210                .as_ref()
3211                .and_then(|value| value["manifest"]["module_id"].as_str());
3212            if !binding.admit_prefix_hello(module)
3213                || !self.prefix_binding_live(binding, connection_id)
3214                || !module.is_some_and(|module| {
3215                    self.supervisor
3216                        .prefix_claim_authorized(&binding.registration.module_id, module)
3217                })
3218                || binding.registration.check().is_err()
3219            {
3220                return Ok(vec![control_error_frame(
3221                    &frame,
3222                    "claim_prefix_refused",
3223                    "HELLO must name the prefix claim's exact module id once",
3224                )?]);
3225            }
3226        }
3227        struct RefuseUnregisteredChannel {
3228            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3229            sink: Option<crate::FrameSink>,
3230        }
3231        impl Drop for RefuseUnregisteredChannel {
3232            fn drop(&mut self) {
3233                if let Some(spawn) = &self.spawn {
3234                    if !spawn.registered() {
3235                        if let Some(sink) = &self.sink {
3236                            sink.terminate_ingress();
3237                        }
3238                        spawn.retire_registration_channel();
3239                    }
3240                }
3241            }
3242        }
3243        let _channel_attempt = RefuseUnregisteredChannel {
3244            spawn: channel_spawn.clone(),
3245            sink: sink.clone(),
3246        };
3247        if let Some(spawn) = &channel_spawn {
3248            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3249            if let Err(code) = spawn.admit_hello(
3250                value
3251                    .as_ref()
3252                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3253            ) {
3254                return Ok(vec![control_error_frame(
3255                    &frame,
3256                    code,
3257                    "registration channel HELLO refused",
3258                )?]);
3259            }
3260        }
3261        debug!(
3262            connection_id = connection_id.get(),
3263            corr = frame.header.corr,
3264            "handling HELLO"
3265        );
3266        // A module connection has one identity for its entire lifetime. A second
3267        // registration would leave the old registry owner behind while replacing
3268        // its forwarding endpoint and launch nonce.
3269        if self
3270            .registry
3271            .get_module_by_connection(connection_id)
3272            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3273            .is_some()
3274        {
3275            return Ok(vec![control_error_frame(
3276                &frame,
3277                "invalid_hello",
3278                "connection is already registered as a module",
3279            )?]);
3280        }
3281        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3282            Ok(value) => value,
3283            Err(err) => {
3284                return Ok(vec![control_error_frame(
3285                    &frame,
3286                    "invalid_hello",
3287                    format!("malformed HELLO body: {err}"),
3288                )?])
3289            }
3290        };
3291        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3292            return Ok(vec![control_error_frame(
3293                &frame,
3294                error_codes::INVALID_PROVIDER_DECLARATIONS,
3295                detail,
3296            )?]);
3297        }
3298        if let Some(module) = hello_value
3299            .get("manifest")
3300            .and_then(|value| value.get("module_id"))
3301            .and_then(|value| value.as_str())
3302        {
3303            let recovering = self
3304                .config_runtime
3305                .as_ref()
3306                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3307            // Defence in depth: RuntimeOwner::module_is_gated in
3308            // config_gate/admission.rs already gates every id during recovery.
3309            // A registration channel still never uses the nonce fallback.
3310            if recovering
3311                && channel_spawn.as_ref().is_none_or(|spawn| {
3312                    !self.supervisor.has_live_verified_channel_binding(spawn)
3313                        || spawn.check().is_err()
3314                })
3315                && !(channel_spawn.is_none()
3316                    && hello_value
3317                        .get("launch_nonce")
3318                        .and_then(|value| value.as_str())
3319                        .is_some_and(|nonce| {
3320                            self.supervisor.spawned_consumer_authorized(module, nonce)
3321                                && self
3322                                    .supervisor
3323                                    .has_live_verified_program_binding(module, nonce)
3324                        }))
3325            {
3326                return Ok(vec![control_error_frame(
3327                    &frame,
3328                    "config_gated",
3329                    "recovery admits only previously bound supervised launches",
3330                )?]);
3331            }
3332            if self
3333                .config_runtime
3334                .as_ref()
3335                .is_some_and(|owner| owner.module_is_gated(module))
3336                && (channel_spawn
3337                    .as_ref()
3338                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3339                    || self.config_runtime.as_ref().is_some_and(|owner| {
3340                        !recovering && owner.check_module_hold(module).is_err()
3341                    }))
3342            {
3343                return Ok(vec![control_error_frame(
3344                    &frame,
3345                    "reserved_module",
3346                    "a gated identity belongs only to its supervised child",
3347                )?]);
3348            }
3349        }
3350        if channel_spawn.is_none() {
3351            if let (Some(module), Some(nonce)) = (
3352                hello_value
3353                    .get("manifest")
3354                    .and_then(|value| value.get("module_id"))
3355                    .and_then(|value| value.as_str()),
3356                hello_value
3357                    .get("launch_nonce")
3358                    .and_then(|value| value.as_str()),
3359            ) {
3360                let binding = self.supervisor.has_program_binding_record(module, nonce);
3361                let required = self
3362                    .config_runtime
3363                    .as_ref()
3364                    .is_some_and(|owner| owner.module_is_gated(module));
3365                if let Some(error) = (binding || required)
3366                    .then(|| {
3367                        self.supervisor
3368                            .check_current_program_binding(module, nonce)
3369                            .err()
3370                    })
3371                    .flatten()
3372                {
3373                    let code = if error.code == "program_refused" {
3374                        "program_refused"
3375                    } else {
3376                        "config_delivery_deferred"
3377                    };
3378                    self.request_refusal_close(
3379                        connection_id,
3380                        sink.as_ref(),
3381                        CloseReason::new(code, error.detail.clone()),
3382                    );
3383                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3384                }
3385            }
3386        }
3387        if let Err(err) = validate_hello_display_name(&hello_value) {
3388            return Ok(vec![control_error_frame(
3389                &frame,
3390                "invalid_manifest",
3391                err.to_string(),
3392            )?]);
3393        }
3394        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3395            return Ok(vec![control_error_frame(
3396                &frame,
3397                "invalid_capability_grammar",
3398                err.to_string(),
3399            )?]);
3400        }
3401        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3402            return Ok(vec![control_error_frame(
3403                &frame,
3404                "invalid_manifest",
3405                err.to_string(),
3406            )?]);
3407        }
3408        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3409            return Ok(vec![control_error_frame(
3410                &frame,
3411                "invalid_event_declaration",
3412                err.to_string(),
3413            )?]);
3414        }
3415        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3416            return Ok(vec![control_error_frame(
3417                &frame,
3418                "invalid_manifest",
3419                err.to_string(),
3420            )?]);
3421        }
3422        if let Some(provenance) = hello_value
3423            .get("manifest")
3424            .and_then(|manifest| manifest.get("provenance"))
3425        {
3426            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3427                return Ok(vec![control_error_frame(
3428                    &frame,
3429                    "invalid_manifest",
3430                    format!("malformed manifest provenance: {err}"),
3431                )?]);
3432            }
3433        }
3434        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3435            let module_id = hello_value["manifest"]["module_id"]
3436                .as_str()
3437                .unwrap_or("<unknown>");
3438            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3439        }
3440        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3441            let module_id = hello_value
3442                .get("manifest")
3443                .and_then(|m| m.get("module_id"))
3444                .and_then(serde_json::Value::as_str)
3445                .unwrap_or("unknown");
3446            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3447        }
3448        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3449            let module_id = hello_value["manifest"]["module_id"]
3450                .as_str()
3451                .unwrap_or("<unknown>");
3452            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3453        }
3454        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3455            let module_id = hello_value["manifest"]["module_id"]
3456                .as_str()
3457                .unwrap_or("<unknown>");
3458            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3459        }
3460        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3461            Ok(hello) => hello,
3462            Err(err) => {
3463                return Ok(vec![control_error_frame(
3464                    &frame,
3465                    "invalid_hello",
3466                    format!("malformed HELLO body: {err}"),
3467                )?])
3468            }
3469        };
3470
3471        if hello.protocol_ver != hello.manifest.protocol_ver {
3472            return Ok(vec![control_error_frame(
3473                &frame,
3474                "invalid_manifest",
3475                format!(
3476                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3477                    hello.protocol_ver, hello.manifest.protocol_ver
3478                ),
3479            )?]);
3480        }
3481
3482        if hello.manifest.module_id.trim().is_empty() {
3483            return Ok(vec![control_error_frame(
3484                &frame,
3485                "invalid_manifest",
3486                "manifest module_id must not be empty",
3487            )?]);
3488        }
3489
3490        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3491            Ok(negotiated_ver) => negotiated_ver,
3492            Err(message) => {
3493                return Ok(vec![control_error_frame(
3494                    &frame,
3495                    "version_unsupported",
3496                    message,
3497                )?])
3498            }
3499        };
3500
3501        // Registration and forwarding publication use the same module gate as
3502        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3503        // precede those transitions. A program-refusal hold blocks future
3504        // spawns, but does not take this gate or revoke a HELLO whose supervised
3505        // child's image has already passed the check.
3506        let _publication_gate = if let Some(owner) = &self.config_runtime {
3507            let gate = owner
3508                .module_gate(&hello.manifest.module_id)
3509                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3510            Some(if wait_for_gate {
3511                gate.blocking_lock_owned()
3512            } else {
3513                match gate.try_lock_owned() {
3514                    Ok(guard) => guard,
3515                    Err(_) => {
3516                        return Ok(vec![control_error_frame(
3517                            &frame,
3518                            "config_delivery_deferred",
3519                            "module admission is busy",
3520                        )?])
3521                    }
3522                }
3523            })
3524        } else {
3525            None
3526        };
3527        #[cfg(test)]
3528        if let Some(hold) = &self.hello_before_publication_hold {
3529            hold.wait();
3530            hold.wait();
3531        }
3532        let module = &hello.manifest.module_id;
3533        let required = self
3534            .config_runtime
3535            .as_ref()
3536            .is_some_and(|owner| owner.module_is_gated(module));
3537        let recovering = self
3538            .config_runtime
3539            .as_ref()
3540            .is_some_and(|owner| owner.is_recovering());
3541        // Both entry paths (handle_control -> handle_hello and
3542        // handle_control_frame_timed -> spawn_blocking) enter this same
3543        // handle_hello_checked function. Its fresh, fail-closed store check
3544        // precedes parsing and this publication-gate check; this cached read
3545        // also observes any recovery transition published during that work.
3546        // The nonce-connection-only fallback is defence in depth alongside
3547        // RuntimeOwner::module_is_gated's all-id recovery gate.
3548        if recovering
3549            && channel_spawn.as_ref().is_none_or(|spawn| {
3550                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3551            })
3552            && !(channel_spawn.is_none()
3553                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3554                    self.supervisor.spawned_consumer_authorized(module, nonce)
3555                        && self
3556                            .supervisor
3557                            .has_live_verified_program_binding(module, nonce)
3558                }))
3559        {
3560            return Ok(vec![control_error_frame(
3561                &frame,
3562                "config_gated",
3563                "recovery admits only previously bound supervised launches",
3564            )?]);
3565        }
3566        if required
3567            && (channel_spawn
3568                .as_ref()
3569                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3570                || self
3571                    .config_runtime
3572                    .as_ref()
3573                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3574        {
3575            return Ok(vec![control_error_frame(
3576                &frame,
3577                "reserved_module",
3578                "gated admission requires the current supervised child's registration channel and verified image binding",
3579            )?]);
3580        }
3581        if let Some(spawn) = &channel_spawn {
3582            if let Err(code) = spawn.check() {
3583                return Ok(vec![control_error_frame(
3584                    &frame,
3585                    code,
3586                    "registration launch is no longer live",
3587                )?]);
3588            }
3589        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3590            if required || self.supervisor.has_program_binding_record(module, nonce) {
3591                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3592                    let code = if error.code == "program_refused" {
3593                        "program_refused"
3594                    } else {
3595                        "config_delivery_deferred"
3596                    };
3597                    self.request_refusal_close(
3598                        connection_id,
3599                        sink.as_ref(),
3600                        CloseReason::new(code, error.detail.clone()),
3601                    );
3602                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3603                }
3604            }
3605        }
3606
3607        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3608        // swap is open for this id, the only HELLO admitted as a second process
3609        // is the one carrying the candidate's launch nonce (the swap token), and
3610        // it registers into the candidate slot rather than being refused as a
3611        // duplicate. Run after the reserved gate, a reserved module's candidate
3612        // would be refused `reserved_module` for presenting a nonce that gate
3613        // does not know. See `SupervisorHandle::swap_hello_admission`.
3614        let swap_admission = match &channel_spawn {
3615            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3616            Some(_) => SwapHelloAdmission::NotSwapping,
3617            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3618            None => self
3619                .supervisor
3620                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3621        };
3622        if swap_admission == SwapHelloAdmission::ProtocolNone {
3623            warn!(
3624                module_id = %hello.manifest.module_id,
3625                connection_id = connection_id.get(),
3626                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3627            );
3628            // The code stays `swap_token_invalid` for existing callers; only the
3629            // explanation names the actual reason.
3630            return Ok(vec![control_error_frame(
3631                &frame,
3632                "swap_token_invalid",
3633                format!(
3634                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3635                    hello.manifest.module_id
3636                ),
3637            )?]);
3638        }
3639        if swap_admission == SwapHelloAdmission::ChannelRequired {
3640            warn!(
3641                module_id = %hello.manifest.module_id,
3642                connection_id = connection_id.get(),
3643                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3644            );
3645            // The code stays `swap_token_invalid` for existing callers; only the
3646            // explanation names the actual reason.
3647            return Ok(vec![control_error_frame(
3648                &frame,
3649                "swap_token_invalid",
3650                format!(
3651                    "module_id '{}' is gated; it must register over its supervised registration channel",
3652                    hello.manifest.module_id
3653                ),
3654            )?]);
3655        }
3656        if swap_admission == SwapHelloAdmission::Refused {
3657            warn!(
3658                module_id = %hello.manifest.module_id,
3659                connection_id = connection_id.get(),
3660                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3661            );
3662            return Ok(vec![control_error_frame(
3663                &frame,
3664                "swap_token_invalid",
3665                format!(
3666                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3667                    hello.manifest.module_id
3668                ),
3669            )?]);
3670        }
3671        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3672
3673        // A swap candidate proves its identity with the candidate nonce above.
3674        // Other registrations receive this catalog fact only when reserved-module
3675        // policy required and accepted a nonce; unreserved registrations require
3676        // no nonce check.
3677        let verification = if swap_candidate && channel_spawn.is_none() {
3678            ReservedHelloVerification {
3679                nonce_verified: true,
3680                prefix_owner: None,
3681            }
3682        } else {
3683            let verification = if let Some(binding) = &prefix_binding {
3684                if !self.supervisor.prefix_claim_authorized(
3685                    &binding.registration.module_id,
3686                    &hello.manifest.module_id,
3687                ) {
3688                    return Ok(vec![control_error_frame(
3689                        &frame,
3690                        "claim_prefix_refused",
3691                        "prefix ownership changed",
3692                    )?]);
3693                }
3694                Ok(ReservedHelloVerification {
3695                    nonce_verified: true,
3696                    prefix_owner: Some(binding.registration.module_id.clone()),
3697                })
3698            } else if channel_spawn.is_some() {
3699                self.supervisor
3700                    .channel_hello_verification(&hello.manifest.module_id)
3701            } else {
3702                self.supervisor.reserved_hello_verification(
3703                    &hello.manifest.module_id,
3704                    hello.launch_nonce.as_deref(),
3705                )
3706            };
3707            match verification {
3708                Ok(verified) => verified,
3709                Err(rejection) => {
3710                    let message = match rejection {
3711                        ReservedHelloRejection::Exact { module_id } => format!(
3712                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3713                        ),
3714                        ReservedHelloRejection::Prefix {
3715                            prefix,
3716                            owner_module_id,
3717                        } => format!(
3718                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3719                            hello.manifest.module_id
3720                        ),
3721                    };
3722                    return Ok(vec![control_error_frame(
3723                        &frame,
3724                        "reserved_module",
3725                        message,
3726                    )?]);
3727                }
3728            }
3729        };
3730
3731        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3732            &hello.manifest.module_id,
3733            hello.manifest.capabilities.as_ref(),
3734        );
3735        if let Some(refusal) = reserved_capability_refusals.first() {
3736            let capability = refusal.capability.clone();
3737            let bound_module = refusal.claimants[0].clone();
3738            log_duplicate_claim_events(reserved_capability_refusals);
3739            return Ok(vec![control_error_frame(
3740                &frame,
3741                "reserved_capability",
3742                format!(
3743                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3744                    capability, bound_module, hello.manifest.module_id
3745                ),
3746            )?]);
3747        }
3748
3749        // A connection that already opened client routes must not also register as
3750        // a module: cleanup would then release only one side and leak the other.
3751        if self
3752            .forwarding
3753            .connection_has_client_routes(connection_id)
3754            .map_err(RouterError::Forwarding)?
3755        {
3756            return Ok(vec![control_error_frame(
3757                &frame,
3758                "invalid_hello",
3759                "connection has open client routes and cannot also register as a module",
3760            )?]);
3761        }
3762
3763        // Kept for scope sync authority, which goes only to the connection that
3764        // presented the module's current launch nonce. Recorded before the
3765        // registration is attempted: a connection whose registration then fails
3766        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3767        // A registration channel's authority is the channel itself, never a
3768        // nonce it also presented, and a prefix registration's is its claim:
3769        // neither records one, so neither can fall back to nonce authority.
3770        self.hello_launch_nonces
3771            .lock()
3772            .unwrap_or_else(|poisoned| poisoned.into_inner())
3773            .record(
3774                connection_id,
3775                if prefix_binding.is_some() || channel_spawn.is_some() {
3776                    None
3777                } else {
3778                    hello.launch_nonce.as_deref()
3779                },
3780            );
3781        let control_ops = effective_module_control_ops(hello.control_ops);
3782        let prefix_submodule = verification.prefix_owner.is_some();
3783        // Built before anything is registered so an encoding failure leaves no
3784        // registry or forwarding state behind.
3785        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3786        #[cfg(test)]
3787        struct PublicationFinished(Arc<std::sync::Barrier>);
3788        #[cfg(test)]
3789        impl Drop for PublicationFinished {
3790            fn drop(&mut self) {
3791                self.0.wait();
3792            }
3793        }
3794        #[cfg(test)]
3795        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3796            hold.wait();
3797            hold.wait();
3798            PublicationFinished(hold.clone())
3799        });
3800        let publication_spawn = channel_spawn
3801            .as_ref()
3802            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3803        #[cfg(test)]
3804        if prefix_binding.is_some() {
3805            self.claims.pause_prefix_hello_for_test(7);
3806        }
3807        let _registration_publication = match publication_spawn {
3808            Some(spawn) => Some(match spawn.begin_publication() {
3809                Ok(guard) => guard,
3810                Err(code) => {
3811                    return Ok(vec![control_error_frame(
3812                        &frame,
3813                        code,
3814                        "registration ended before HELLO publication",
3815                    )?])
3816                }
3817            }),
3818            None => None,
3819        };
3820        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3821            let live = self.claims.lock_prefix_binding(binding, connection_id);
3822            let ownership = self.supervisor.prefix_claim_publication(
3823                &binding.registration.module_id,
3824                &hello.manifest.module_id,
3825            );
3826            if live.is_none()
3827                || ownership.is_none()
3828                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3829                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3830            {
3831                return Ok(vec![control_error_frame(
3832                    &frame,
3833                    "claim_prefix_refused",
3834                    "prefix authority ended before publication",
3835                )?]);
3836            }
3837            (live, ownership)
3838        } else {
3839            (None, None)
3840        };
3841        if let Some(spawn) = publication_spawn {
3842            self.forwarding
3843                .bind_spawn(connection_id, spawn)
3844                .map_err(RouterError::Forwarding)?;
3845        }
3846        // The spawn whose own registration this HELLO is, for `target` on
3847        // the route.open reply: its channel, or the launch its nonce was
3848        // minted for. A prefix child's HELLO names no spawn of its own. It is
3849        // only looked up here. The connection is bound to it and its
3850        // requested declarations are frozen once the registry has accepted
3851        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3852        // duplicate, or for any other reason, leaves the spawn untouched: its
3853        // closing connection is then no registration of the spawn and ends
3854        // none of the spawn's routes.
3855        let hello_authority = match (&channel_spawn, &prefix_binding) {
3856            (Some(spawn), _) => Some(spawn.authority.clone()),
3857            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3858                self.supervisor
3859                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3860            }),
3861            (None, Some(_)) => None,
3862        }
3863        .map(|record| HelloAuthority {
3864            record,
3865            requested: hello
3866                .manifest
3867                .provider_declarations
3868                .clone()
3869                .unwrap_or_default(),
3870            froze: Default::default(),
3871        });
3872        #[cfg(test)]
3873        if prefix_binding.is_some() {
3874            self.claims.pause_prefix_hello_for_test(8);
3875        }
3876        if swap_candidate {
3877            let module_id = hello.manifest.module_id.clone();
3878            let mut differing_declarations = Default::default();
3879            let reply = self.register_swap_candidate(
3880                connection_id,
3881                sink,
3882                &frame,
3883                hello.manifest,
3884                negotiated_ver,
3885                control_ops,
3886                hello_ack,
3887                hello_authority.as_ref(),
3888                &mut differing_declarations,
3889                #[cfg(windows)]
3890                hello.launch_nonce.as_deref(),
3891            )?;
3892            if let Some(spawn) = &channel_spawn {
3893                if self
3894                    .registry
3895                    .get_module_by_connection(connection_id)
3896                    .ok()
3897                    .flatten()
3898                    .is_some()
3899                {
3900                    if let Some(sink) = primary_sink {
3901                        spawn.bind_primary_sink(sink);
3902                    }
3903                    spawn.hello_accepted();
3904                }
3905            } else if self
3906                .registry
3907                .get_module_by_connection(connection_id)
3908                .ok()
3909                .flatten()
3910                .is_some()
3911            {
3912                self.supervisor
3913                    .retire_unused_registration_channel(&module_id, true);
3914            }
3915            if self
3916                .registry
3917                .get_module_by_connection(connection_id)
3918                .ok()
3919                .flatten()
3920                .is_some()
3921            {
3922                self.file_development_widening(
3923                    hello_authority.map(|authority| authority.record),
3924                    differing_declarations,
3925                );
3926            }
3927            return Ok(reply);
3928        }
3929        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3930        // is refused, but `catalog.list` does not show the module and the
3931        // catalog generation does not move until it is published below, once
3932        // its forwarding endpoint exists. Listing it now would advertise a
3933        // module that `route.open` still refuses for having no forwarding
3934        // connection.
3935        let registration = match self
3936            .registry
3937            .register_unpublished_verified_with_control_ops(
3938                hello.manifest,
3939                negotiated_ver,
3940                connection_id,
3941                control_ops,
3942                verification.nonce_verified,
3943            ) {
3944            Ok(registration) => registration,
3945            Err(RegistryError::DuplicateModuleId { module_id }) => {
3946                return Ok(vec![control_error_frame(
3947                    &frame,
3948                    "duplicate_module_id",
3949                    format!(
3950                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3951                    ),
3952                )?])
3953            }
3954            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3955                return Ok(vec![control_error_frame(
3956                    &frame,
3957                    "invalid_module_id",
3958                    err.to_string(),
3959                )?])
3960            }
3961            Err(err) => {
3962                return Ok(vec![control_error_frame(
3963                    &frame,
3964                    "registry_error",
3965                    err.to_string(),
3966                )?])
3967            }
3968        };
3969        let differing_declarations =
3970            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3971                Ok(differing) => differing,
3972                Err(err) => {
3973                    if matches!(
3974                        self.rollback_unpublished_hello(connection_id),
3975                        Ok(r) if !r.is_empty()
3976                    ) {
3977                        crate::supervise::notify_registration_release();
3978                    }
3979                    return Err(RouterError::Forwarding(err));
3980                }
3981            };
3982        #[cfg(test)]
3983        self.hold_between_registry_and_forwarding();
3984
3985        let mut reply = Vec::new();
3986        // Registry readers must wait from before the ACK can be read until
3987        // publication. Nest forwarding inside the registry lock, never reverse.
3988        let publication = self
3989            .registry
3990            .publish_registration_after(connection_id, || {
3991                if let Some(sink) = sink {
3992                    // The forwarding table's module store is also the daemon-to-module
3993                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3994                    // manifest has no routable provider role. Non-routable modules still
3995                    // cannot receive route.bind in production: `handle_route_open` checks
3996                    // the registry manifest with `target_has_required_role` before the
3997                    // only production call to `begin_route_bind_relay_for` below that
3998                    // route.open path. The remaining direct relay callers are unit tests
3999                    // and benchmark harnesses that construct forwarding state explicitly.
4000                    //
4001                    // The HELLO_ACK is queued by the forwarding table itself, before the
4002                    // endpoint becomes visible, and is NOT returned as a reply. A module
4003                    // reads HELLO_ACK first and exits on anything else; a reply is only
4004                    // written after this handler returns, by which time a route.open on
4005                    // another connection could already have queued a route.bind request
4006                    // for this module ahead of it.
4007                    let concurrency = manifest_concurrency(&registration.manifest);
4008                    self.forwarding.register_module_connection_acked(
4009                        connection_id,
4010                        registration.manifest.module_id.clone(),
4011                        negotiated_ver,
4012                        concurrency,
4013                        sink,
4014                        crate::forwarding::ModuleHelloAck {
4015                            frame: hello_ack,
4016                            verified_prefix_owner: verification.prefix_owner,
4017                        },
4018                    )?;
4019                } else {
4020                    // No sink means no forwarding endpoint, so nothing can be routed
4021                    // ahead of the ack; it goes out as the reply.
4022                    reply.push(hello_ack);
4023                }
4024                #[cfg(test)]
4025                self.hold_between_ack_and_publication();
4026                Ok(())
4027            })
4028            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4029        let published = match publication {
4030            Ok(published) => published,
4031            Err(err) => {
4032                // The registry lock has been released, so rollback can take it
4033                // again. No forwarding endpoint or route was published. Keep
4034                // forwarding's weak connection-to-spawn association until the
4035                // connection's read loop ends and removes its remaining routes.
4036                // Removing this unpublished entry does not advance the catalog
4037                // generation.
4038                if matches!(
4039                    self.rollback_unpublished_hello(connection_id),
4040                    Ok(r) if !r.is_empty()
4041                ) {
4042                    crate::supervise::notify_registration_release();
4043                }
4044                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
4045                return Ok(vec![control_error_frame(
4046                    &frame,
4047                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
4048                        "invalid_hello"
4049                    } else {
4050                        forwarding_error_code(&err)
4051                    },
4052                    err.to_string(),
4053                )?]);
4054            }
4055        };
4056        if !published {
4057            debug!(
4058                module_id = %registration.manifest.module_id,
4059                connection_id = connection_id.get(),
4060                "registration was removed before it could be published"
4061            );
4062            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
4063            return Ok(reply);
4064        }
4065
4066        drop(_prefix_ownership);
4067        drop(_prefix_live);
4068
4069        // Exposure over assumption: Concurrency's serde default is pinned to the
4070        // pre-field behavior (ModuleManaged), so a management surface that is
4071        // genuinely Serial and just never declared it inherits concurrent
4072        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
4073        // turns "no module has been bitten yet" into the checkable claim "no
4074        // module is exposed" -- one read of the boot log instead of a fleet
4075        // audit. Detected from the raw HELLO bytes because the serde default
4076        // deliberately erases the absent/declared distinction from the type.
4077        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
4078            info!(
4079                module_id = %registration.manifest.module_id,
4080                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
4081            );
4082        }
4083        if registration.manifest.registration_channel == Some(false)
4084            && self
4085                .supervisor
4086                .module_is_gated(&registration.manifest.module_id)
4087            && self
4088                .config_runtime
4089                .as_ref()
4090                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
4091                .as_deref()
4092                == Some("declared")
4093        {
4094            warn!(module_id = %registration.manifest.module_id,
4095                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
4096        }
4097
4098        self.apply_registration_capabilities(&registration);
4099
4100        self.supervisor
4101            .record_activity_registration(&registration.manifest.module_id);
4102
4103        info!(
4104            module_id = %registration.manifest.module_id,
4105            module_version = %registration.manifest.module_version,
4106            negotiated_ver,
4107            routable_provider = manifest_provides_routable_role(&registration.manifest),
4108            connection_id = connection_id.get(),
4109            "module registered"
4110        );
4111
4112        if let Some(spawn) = &channel_spawn {
4113            if let Some(sink) = primary_sink {
4114                spawn.bind_primary_sink(sink);
4115            }
4116            spawn.hello_accepted();
4117        } else if !prefix_submodule {
4118            self.supervisor
4119                .retire_unused_registration_channel(&registration.manifest.module_id, false);
4120        }
4121        self.file_development_widening(
4122            hello_authority.map(|authority| authority.record),
4123            differing_declarations,
4124        );
4125        #[cfg(windows)]
4126        if let Some(nonce) = hello.launch_nonce.as_deref() {
4127            self.supervisor
4128                .program_hello_accepted(&registration.manifest.module_id, nonce);
4129        }
4130
4131        #[cfg(test)]
4132        if let Some(hold) = &self.hello_inside_publication_hold {
4133            hold.wait();
4134            hold.wait();
4135        }
4136
4137        Ok(reply)
4138    }
4139
4140    /// Register a HELLO the swap gate admitted into the candidate slot of the
4141    /// registry and of forwarding, where it is reachable over its own
4142    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
4143    /// nothing routes to it until the supervisor cuts over.
4144    ///
4145    /// Registry first (unpublished), then forwarding, then publication, the
4146    /// same order as an ordinary HELLO; a forwarding failure removes the
4147    /// registry entry again. The swap supervisor treats a published, ready
4148    /// candidate as registered and promotes it, and promotion needs the
4149    /// candidate's forwarding endpoint, so the candidate is published only
4150    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
4151    /// recompute capability verdicts or run the capability deny census
4152    /// (`enforce_capability_denies`): both are about the module in the active
4153    /// slot, which `route.open` can target. A candidate sits in the candidate
4154    /// slot, so it neither provides capabilities to other modules nor can be
4155    /// routed to until promotion moves it into the active slot.
4156    #[allow(clippy::too_many_arguments)]
4157    fn register_swap_candidate(
4158        &self,
4159        connection_id: ConnectionId,
4160        sink: Option<crate::FrameSink>,
4161        frame: &Frame,
4162        manifest: ModuleManifest,
4163        negotiated_ver: u8,
4164        control_ops: Vec<String>,
4165        hello_ack: Frame,
4166        hello_authority: Option<&HelloAuthority>,
4167        differing_declarations: &mut ProviderDeclarations,
4168        #[cfg(windows)] launch_nonce: Option<&str>,
4169    ) -> Result<Vec<Frame>, RouterError> {
4170        let module_id = manifest.module_id.clone();
4171        // Closing a swap and publishing its candidate must be ordered. The
4172        // spawn role proves which slot is intended, not that the slot is open.
4173        self.supervisor
4174            .with_swap_candidate_admission(&module_id, || {
4175                let reply = self.publish_swap_candidate(
4176                    connection_id,
4177                    sink,
4178                    frame,
4179                    manifest,
4180                    negotiated_ver,
4181                    control_ops,
4182                    hello_ack,
4183                    hello_authority,
4184                    differing_declarations,
4185                    #[cfg(windows)]
4186                    launch_nonce,
4187                );
4188                let admitted = self
4189                    .registry
4190                    .get_candidate(&module_id)
4191                    .ok()
4192                    .flatten()
4193                    .is_some_and(|candidate| candidate.connection_id == connection_id);
4194                (reply, admitted)
4195            })
4196            .unwrap_or_else(|| {
4197                Ok(vec![control_error_frame(
4198                    frame,
4199                    "swap_token_invalid",
4200                    "swap ended before candidate HELLO publication",
4201                )?])
4202            })
4203    }
4204
4205    #[allow(clippy::too_many_arguments)]
4206    fn publish_swap_candidate(
4207        &self,
4208        connection_id: ConnectionId,
4209        sink: Option<crate::FrameSink>,
4210        frame: &Frame,
4211        manifest: ModuleManifest,
4212        negotiated_ver: u8,
4213        control_ops: Vec<String>,
4214        hello_ack: Frame,
4215        hello_authority: Option<&HelloAuthority>,
4216        differing_declarations: &mut ProviderDeclarations,
4217        #[cfg(windows)] launch_nonce: Option<&str>,
4218    ) -> Result<Vec<Frame>, RouterError> {
4219        let module_id = manifest.module_id.clone();
4220        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4221            manifest,
4222            negotiated_ver,
4223            connection_id,
4224            control_ops,
4225        ) {
4226            Ok(registration) => registration,
4227            Err(RegistryError::DuplicateModuleId { module_id }) => {
4228                return Ok(vec![control_error_frame(
4229                    frame,
4230                    "duplicate_module_id",
4231                    format!(
4232                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4233                    ),
4234                )?])
4235            }
4236            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4237                return Ok(vec![control_error_frame(
4238                    frame,
4239                    "invalid_module_id",
4240                    err.to_string(),
4241                )?])
4242            }
4243            Err(err) => {
4244                return Ok(vec![control_error_frame(
4245                    frame,
4246                    "registry_error",
4247                    err.to_string(),
4248                )?])
4249            }
4250        };
4251        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4252            Ok(differing) => differing,
4253            Err(err) => {
4254                if matches!(
4255                    self.rollback_unpublished_hello(connection_id),
4256                    Ok(r) if !r.is_empty()
4257                ) {
4258                    crate::supervise::notify_registration_release();
4259                }
4260                return Err(RouterError::Forwarding(err));
4261            }
4262        };
4263        #[cfg(test)]
4264        self.hold_between_registry_and_forwarding();
4265        let mut reply = Vec::new();
4266        let publication = self
4267            .registry
4268            .publish_registration_after(connection_id, || {
4269                if let Some(sink) = sink {
4270                    // Same ordering as an ordinary HELLO: queue the ACK before
4271                    // inserting the endpoint, and keep registry readers excluded
4272                    // until the candidate is published.
4273                    let concurrency = manifest_concurrency(&registration.manifest);
4274                    self.forwarding.register_candidate_module_connection_acked(
4275                        connection_id,
4276                        module_id.clone(),
4277                        negotiated_ver,
4278                        concurrency,
4279                        sink,
4280                        hello_ack,
4281                    )?;
4282                } else {
4283                    reply.push(hello_ack);
4284                }
4285                #[cfg(test)]
4286                self.hold_between_ack_and_publication();
4287                Ok(())
4288            })
4289            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4290        let published = match publication {
4291            Ok(published) => published,
4292            Err(err) => {
4293                if matches!(
4294                    self.rollback_unpublished_hello(connection_id),
4295                    Ok(r) if !r.is_empty()
4296                ) {
4297                    crate::supervise::notify_registration_release();
4298                }
4299                self.refuse_hello_authority(connection_id, hello_authority);
4300                return Ok(vec![control_error_frame(
4301                    frame,
4302                    forwarding_error_code(&err),
4303                    err.to_string(),
4304                )?]);
4305            }
4306        };
4307        if !published {
4308            debug!(
4309                module_id = %module_id,
4310                connection_id = connection_id.get(),
4311                "swap candidate registration was removed before it could be published"
4312            );
4313            self.refuse_hello_authority(connection_id, hello_authority);
4314            return Ok(reply);
4315        }
4316        info!(
4317            module_id = %module_id,
4318            module_version = %registration.manifest.module_version,
4319            negotiated_ver,
4320            ready = registration.ready,
4321            connection_id = connection_id.get(),
4322            "swap candidate registered; not routable until cutover"
4323        );
4324        #[cfg(windows)]
4325        if let Some(nonce) = launch_nonce {
4326            self.supervisor.program_hello_accepted(&module_id, nonce);
4327        }
4328        Ok(reply)
4329    }
4330
4331    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4332    /// spawn's requested provider declarations. Runs only once the registry
4333    /// has accepted the HELLO, before its endpoint is published, so a route
4334    /// reserved on the endpoint always finds the spawn. Returns the requested
4335    /// entries that differ from the saved approvals, for a widening request.
4336    fn admit_hello_authority(
4337        &self,
4338        connection: ConnectionId,
4339        authority: Option<&HelloAuthority>,
4340    ) -> Result<ProviderDeclarations, ForwardingError> {
4341        let Some(authority) = authority else {
4342            return Ok(ProviderDeclarations::new());
4343        };
4344        let froze = authority
4345            .record
4346            .freeze_declarations(authority.requested.clone());
4347        authority
4348            .froze
4349            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4350        self.forwarding
4351            .bind_target_authority(connection, authority.record.clone())
4352            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4353        Ok(froze.unwrap_or_default())
4354    }
4355
4356    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4357    /// registry accepted it, so the refused connection is no registration of
4358    /// the spawn and the spawn's declarations are left for the HELLO that
4359    /// does register it to freeze.
4360    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4361        let Some(authority) = authority else {
4362            return;
4363        };
4364        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4365            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4366        }
4367        if authority
4368            .froze
4369            .swap(false, std::sync::atomic::Ordering::Relaxed)
4370        {
4371            authority.record.unfreeze_refused_declarations();
4372        }
4373    }
4374
4375    fn build_hello_ack(
4376        &self,
4377        frame: &Frame,
4378        negotiated_ver: u8,
4379        module_id: &str,
4380    ) -> Result<Frame, RouterError> {
4381        let ack = ModuleHelloAckBody {
4382            negotiated_ver,
4383            subc_ops: module_subc_ops(),
4384            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4385            storage: self
4386                .storage_config
4387                .as_ref()
4388                .map(|cfg| cfg.descriptor_for(module_id)),
4389            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4390        };
4391        let body = serde_json::to_vec(&ack).map_err(|err| {
4392            RouterError::backend(
4393                0,
4394                frame.header.corr,
4395                format!("failed to encode HELLO_ACK: {err}"),
4396            )
4397        })?;
4398
4399        Frame::build_with_version(
4400            negotiated_ver,
4401            FrameType::HelloAck,
4402            control_flags(),
4403            0,
4404            0,
4405            frame.header.corr,
4406            body,
4407        )
4408        .map_err(RouterError::FrameBuild)
4409    }
4410
4411    async fn handle_client_control_request(
4412        &self,
4413        ctx: &RouteCtx,
4414        frame: Frame,
4415        request: ClientControlRequest,
4416        route_open_timings: &mut Option<RouteOpenTimings>,
4417    ) -> Result<Vec<Frame>, RouterError> {
4418        if let Some(owner) = &self.config_runtime {
4419            let module = match &request {
4420                ClientControlRequest::SupervisorRestart { module_id, .. }
4421                | ClientControlRequest::SupervisorReload { module_id }
4422                | ClientControlRequest::SupervisorSwap { module_id, .. }
4423                | ClientControlRequest::SupervisorSetEnabled {
4424                    module_id,
4425                    enabled: true,
4426                } => Some(module_id.as_str()),
4427                _ => None,
4428            };
4429            let rescan = matches!(
4430                &request,
4431                ClientControlRequest::SupervisorRescan { preview: false }
4432                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4433            );
4434            let held = if module.is_some() || rescan {
4435                let module = module.map(str::to_owned);
4436                owner
4437                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4438                    .await
4439            } else {
4440                Ok(())
4441            };
4442            if let Err(error) = held {
4443                if error.code != "config_delivery_deferred" {
4444                    let code = if error.code == "store_tampered" {
4445                        "store_tampered"
4446                    } else {
4447                        "config_gated"
4448                    };
4449                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4450                }
4451            }
4452        }
4453        if let Some(operation) = privileged_operation(&request) {
4454            let caller = self.resolve_caller(ctx.connection_id).await;
4455            let op = client_control_request_op(&request);
4456            let text = prompt_text(operation, &caller);
4457            match self.privileged_operator_prompt {
4458                PrivilegedOperatorPrompt::Log => {
4459                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4460                        target = ?operation, caller = %caller.description(), summary = %text,
4461                        "privileged request would prompt the operator");
4462                }
4463                PrivilegedOperatorPrompt::Enforce => {
4464                    let key =
4465                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4466                    let stamp = self
4467                        .operator_apps
4468                        .lock()
4469                        .unwrap_or_else(|p| p.into_inner())
4470                        .get(&ctx.connection_id)
4471                        .cloned();
4472                    let shortcut = crate::operator_confirm::ShortcutContext::eligible_stamp(
4473                        &self.operator_app_policy,
4474                        &self.launch_table,
4475                        stamp.as_ref(),
4476                    )
4477                    .then(|| self.shortcut_context(stamp, None, None));
4478                    let outcome = self
4479                        .forwarding
4480                        .operator_confirms()
4481                        .approve_privileged_with_shortcut(
4482                            ctx,
4483                            &frame,
4484                            op,
4485                            text,
4486                            caller.description(),
4487                            key,
4488                            shortcut,
4489                        )
4490                        .await;
4491                    if outcome.code != "confirmed" {
4492                        return Ok(vec![outcome.frame(&frame)]);
4493                    }
4494                }
4495            }
4496        }
4497        match request {
4498            ClientControlRequest::DaemonShutdownIntent { intent } => {
4499                if intent.as_str() != Some("restart") {
4500                    return Ok(vec![control_error_frame(
4501                        &frame,
4502                        "invalid_params",
4503                        "intent must be 'restart'",
4504                    )?]);
4505                }
4506                // A stamped daemon boots a newer approved generation only from a
4507                // durable restart intent, written here before the daemon exits.
4508                // Failing to write it never blocks the restart: the next start
4509                // then boots the last active generation and the newer one waits.
4510                if let Some(owner) = &self.config_runtime {
4511                    match owner
4512                        .on_blocking(|owner| owner.assign_daemon_restart())
4513                        .await
4514                    {
4515                        Ok(Some(generation)) => {
4516                            info!(
4517                                generation,
4518                                "daemon restart will warm up approved generation"
4519                            )
4520                        }
4521                        Ok(None) => {}
4522                        Err(error) => warn!(
4523                            %error,
4524                            "daemon restart intent not recorded; the next start boots the last active generation"
4525                        ),
4526                    }
4527                }
4528                let response = ClientControlResponse::DaemonShutdownIntent {
4529                    intent: "restart".to_owned(),
4530                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4531                };
4532                Ok(vec![control_response_body_frame(
4533                    &frame,
4534                    &response,
4535                    "ClientControlResponse::DaemonShutdownIntent",
4536                )?])
4537            }
4538            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4539            ClientControlRequest::CatalogList { module_id } => {
4540                self.handle_catalog_list(frame, module_id)
4541            }
4542            ClientControlRequest::RouteOpen {
4543                target,
4544                identity,
4545                consumer_identity,
4546                consumer_capabilities,
4547                role_versions,
4548                busy_refusals,
4549                admission_facts,
4550                scope,
4551                ..
4552            } => {
4553                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4554                    &frame.body,
4555                ) {
4556                    Ok(extensions) => extensions,
4557                    Err(err) => {
4558                        return Ok(vec![control_error_frame(
4559                            &frame,
4560                            "invalid_control_body",
4561                            format!("malformed route.open extensions: {err}"),
4562                        )?]);
4563                    }
4564                };
4565                self.handle_route_open(
4566                    ctx,
4567                    frame,
4568                    RouteOpenRequest {
4569                        target,
4570                        identity,
4571                        consumer_identity,
4572                        consumer_capabilities,
4573                        role_versions,
4574                        busy_refusals,
4575                        admission_facts,
4576                        scope,
4577                        accepts_close_reasons: extensions.accepts_close_reasons,
4578                    },
4579                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4580                )
4581                .await
4582            }
4583            ClientControlRequest::RoutePoll {
4584                route_channel,
4585                route_epoch,
4586                kind,
4587            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4588            ClientControlRequest::SupervisorList {} => {
4589                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4590                    self.agent_declarations.refuse(
4591                        self,
4592                        ctx,
4593                        control_error_frame(
4594                            &frame,
4595                            "busy",
4596                            "supervisor list work is at capacity; retry",
4597                        )?,
4598                    );
4599                    return Ok(Vec::new());
4600                };
4601                // Filesystem-backed diagnostics must not hold up this connection's reader.
4602                let handler = self.clone();
4603                let sink = ctx.egress.clone();
4604                tokio::spawn(
4605                    async move {
4606                        let _permit = permit;
4607                        let result = handler.handle_supervisor_list(frame.clone()).await;
4608                        let replies = match result {
4609                            Ok(replies) => replies,
4610                            Err(error) => {
4611                                control_error_frame(&frame, "backend_error", error.to_string())
4612                                    .into_iter()
4613                                    .collect()
4614                            }
4615                        };
4616                        for reply in replies {
4617                            if !matches!(
4618                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4619                                    .await,
4620                                Ok(Ok(()))
4621                            ) {
4622                                break;
4623                            }
4624                        }
4625                    }
4626                    .with_current_subscriber(),
4627                );
4628                Ok(Vec::new())
4629            }
4630            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4631                self.handle_supervisor_spawn_snapshot(frame)
4632            }
4633            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4634                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4635            }
4636            ClientControlRequest::SupervisorRestart {
4637                module_id,
4638                drain_timeout_ms,
4639            } => {
4640                self.log_supervisor_request_received(
4641                    ctx,
4642                    frame.header.corr,
4643                    ops::SUPERVISOR_RESTART,
4644                    Some(&module_id),
4645                    None,
4646                )?;
4647                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4648                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4649                    .await
4650            }
4651            ClientControlRequest::SupervisorSwap {
4652                module_id,
4653                ready_timeout_ms,
4654            } => {
4655                self.log_supervisor_request_received(
4656                    ctx,
4657                    frame.header.corr,
4658                    ops::SUPERVISOR_SWAP,
4659                    Some(&module_id),
4660                    None,
4661                )?;
4662                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4663                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4664                    .await
4665            }
4666            ClientControlRequest::SupervisorReload { module_id } => {
4667                self.log_supervisor_request_received(
4668                    ctx,
4669                    frame.header.corr,
4670                    ops::SUPERVISOR_RELOAD,
4671                    Some(&module_id),
4672                    None,
4673                )?;
4674                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4675                self.handle_supervisor_reload(frame, module_id, requester)
4676                    .await
4677            }
4678            ClientControlRequest::SupervisorRescan { preview } => {
4679                if !preview {
4680                    self.log_supervisor_request_received(
4681                        ctx,
4682                        frame.header.corr,
4683                        ops::SUPERVISOR_RESCAN,
4684                        None,
4685                        None,
4686                    )?;
4687                }
4688                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4689                let operation = self.handle_supervisor_rescan(
4690                    frame,
4691                    if preview {
4692                        RescanMode::Preview
4693                    } else {
4694                        RescanMode::Execute
4695                    },
4696                    requester,
4697                );
4698                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4699                    .await
4700            }
4701            ClientControlRequest::SupervisorRescanChecked {
4702                preview,
4703                candidate,
4704                expect,
4705            } => {
4706                self.observe_control_wait(
4707                    ctx,
4708                    None,
4709                    ops::SUPERVISOR_RESCAN,
4710                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4711                )
4712                .await
4713            }
4714            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4715                self.log_supervisor_request_received(
4716                    ctx,
4717                    frame.header.corr,
4718                    ops::SUPERVISOR_RELEASE_RESERVED,
4719                    Some(&module_id),
4720                    None,
4721                )?;
4722                self.handle_supervisor_release_reserved(frame, module_id)
4723                    .await
4724            }
4725            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4726                self.log_supervisor_request_received(
4727                    ctx,
4728                    frame.header.corr,
4729                    ops::SUPERVISOR_SET_ENABLED,
4730                    Some(&module_id),
4731                    Some(enabled),
4732                )?;
4733                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4734                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4735                    .await
4736            }
4737            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4738                self.handle_supervisor_health_probe(ctx, frame, module_id)
4739                    .await
4740            }
4741            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4742            ClientControlRequest::SupervisorRoutes { module_id } => {
4743                self.handle_supervisor_routes(frame, module_id)
4744            }
4745            ClientControlRequest::SupervisorProvenance { module_id } => {
4746                self.handle_supervisor_provenance(ctx, frame, module_id)
4747                    .await
4748            }
4749            ClientControlRequest::SupervisorStderrTail {
4750                module_id,
4751                max_lines,
4752                max_bytes,
4753            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4754            ClientControlRequest::SupervisorTerminals { module_id } => {
4755                self.handle_supervisor_terminals(ctx, frame, module_id)
4756                    .await
4757            }
4758        }
4759    }
4760
4761    fn log_supervisor_request_received(
4762        &self,
4763        ctx: &RouteCtx,
4764        corr: u64,
4765        op: &'static str,
4766        module_id: Option<&str>,
4767        enabled: Option<bool>,
4768    ) -> Result<(), RouterError> {
4769        let caller = self.supervisor_requester(ctx, corr)?;
4770        let caller = principal_label(&caller);
4771        // `Option` fields are recorded only when present, so a request with no
4772        // module id (rescan) or no enabled flag simply omits that field.
4773        info!(
4774            target: "control",
4775            op,
4776            module_id,
4777            enabled,
4778            connection_id = ctx.connection_id.get(),
4779            caller = %caller,
4780            "supervisor request received"
4781        );
4782        Ok(())
4783    }
4784
4785    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4786        Ok(self
4787            .registry
4788            .get_module_by_connection(ctx.connection_id)
4789            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4790            .map(|registration| Principal::Reserved {
4791                module_id: registration.manifest.module_id,
4792            })
4793            .unwrap_or(Principal::Direct))
4794    }
4795
4796    fn handle_module_control_request(
4797        &self,
4798        connection_id: ConnectionId,
4799        frame: Frame,
4800        request: ModuleControlRequestFromModule,
4801    ) -> Result<Vec<Frame>, RouterError> {
4802        match request {
4803            ModuleControlRequestFromModule::RouteAuthorize {
4804                principal,
4805                scope,
4806                target,
4807                expected,
4808            } => self.handle_route_authorize(
4809                connection_id,
4810                frame,
4811                principal,
4812                scope,
4813                target,
4814                expected,
4815            ),
4816            ModuleControlRequestFromModule::CatalogUpdate {
4817                provides,
4818                capabilities,
4819                ready,
4820            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4821            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4822                self.handle_catalog_update_role_declarations(
4823                    connection_id,
4824                    frame,
4825                    role_declarations,
4826                )
4827            }
4828            ModuleControlRequestFromModule::LiveRoots {} => {
4829                let registered = self
4830                    .registry
4831                    .get_module_by_connection(connection_id)
4832                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4833                let Some(registration) = registered else {
4834                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4835                };
4836                let response = self
4837                    .forwarding
4838                    .live_roots(&registration.manifest.module_id)
4839                    .map_err(RouterError::Forwarding)?;
4840                Ok(vec![control_response_body_frame(
4841                    &frame,
4842                    &response,
4843                    "ModuleControlResponseToModule::LiveRoots",
4844                )?])
4845            }
4846            ModuleControlRequestFromModule::AgentCommands {
4847                started,
4848                finished,
4849                known,
4850            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4851            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4852                self.handle_scope_sync(connection_id, frame, generation, scopes)
4853            }
4854            ModuleControlRequestFromModule::ScopeApply {
4855                generation,
4856                upsert,
4857                end,
4858            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4859            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4860                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4861            }
4862            _ => Ok(vec![control_error_frame(
4863                &frame,
4864                "unsupported_control_frame",
4865                "unsupported module control operation",
4866            )?]),
4867        }
4868    }
4869
4870    fn handle_scope_served_by(
4871        &self,
4872        connection_id: ConnectionId,
4873        frame: Frame,
4874    ) -> Result<Vec<Frame>, RouterError> {
4875        let registered = self
4876            .registry
4877            .get_module_by_connection(connection_id)
4878            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4879        let Some(registered) = registered else {
4880            return Ok(vec![control_error_frame(
4881                &frame,
4882                "not_registered",
4883                "scope.served_by requires an active module registration owned by this connection",
4884            )?]);
4885        };
4886        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4887        {
4888            Ok(request) => request,
4889            Err(err) => {
4890                return Ok(vec![control_error_frame(
4891                    &frame,
4892                    "invalid_control_body",
4893                    format!("malformed scope.served_by body: {err}"),
4894                )?])
4895            }
4896        };
4897        let answer = self
4898            .scopes
4899            .read()
4900            .unwrap_or_else(|poisoned| poisoned.into_inner())
4901            .served_by(
4902                &registered.manifest.module_id,
4903                &request.scope_ref,
4904                request.scope_epoch,
4905                &request.module_id,
4906            );
4907        let reply = subc_control::ScopeServedByReply::new(
4908            answer,
4909            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4910        );
4911        Ok(vec![control_response_body_frame(
4912            &frame,
4913            &reply,
4914            "ScopeServedByReply",
4915        )?])
4916    }
4917
4918    fn handle_operator_confirm(
4919        &self,
4920        ctx: &RouteCtx,
4921        frame: Frame,
4922    ) -> Result<Vec<Frame>, RouterError> {
4923        use crate::operator_confirm::{audit, Outcome};
4924        let registration = self
4925            .registry
4926            .get_module_by_connection(ctx.connection_id)
4927            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4928        let Some(registration) = registration else {
4929            let outcome = Outcome::refusal("not_registered");
4930            audit("", "", "", &outcome, Duration::ZERO, Duration::ZERO, false);
4931            return Ok(vec![outcome.frame(&frame)]);
4932        };
4933        let request = match serde_json::from_slice::<OperatorConfirmRequest>(&frame.body) {
4934            Ok(request) => request,
4935            Err(_) => {
4936                let outcome = Outcome::refusal("invalid_control_body");
4937                audit("", "", "", &outcome, Duration::ZERO, Duration::ZERO, false);
4938                return Ok(vec![outcome.frame(&frame)]);
4939            }
4940        };
4941        let declared = matches!(
4942            request.kind,
4943            Some(subc_protocol::session::OperatorConfirmKind::Operation)
4944        ) && request.operation.as_ref().is_some_and(|operation| {
4945            registration
4946                .manifest
4947                .confirm_operations
4948                .as_ref()
4949                .is_some_and(|operations| operations.contains(operation))
4950        });
4951        let module_id = registration.manifest.module_id;
4952        // Read the launch nonce (under its own lock) before taking the forwarding
4953        // table's lock below: holding forwarding while waiting on another daemon
4954        // lock risks a lock-order deadlock with paths that take them the other way.
4955        let nonce = self
4956            .hello_launch_nonces
4957            .lock()
4958            .unwrap_or_else(|p| p.into_inner())
4959            .nonce(ctx.connection_id)
4960            .map(str::to_owned);
4961        // A registration channel proves its own spawn; only a connection that
4962        // registered over the launch nonce falls back to the nonce.
4963        let nonce_proven = self
4964            .confirm_channel_proven(ctx.connection_id, &module_id)
4965            .unwrap_or_else(|| {
4966                nonce.as_deref().is_some_and(|nonce| {
4967                    self.supervisor
4968                        .spawned_consumer_authorized(&module_id, nonce)
4969                })
4970            });
4971        let confirms = self.forwarding.operator_confirms();
4972        self.forwarding
4973            .with_operator_route(
4974                ctx.connection_id,
4975                request.route_channel,
4976                request.route_epoch,
4977                |binding| {
4978                    let shortcut = binding
4979                        .filter(|binding| {
4980                            nonce_proven
4981                                && crate::operator_confirm::valid_summary(&request.summary)
4982                                && declared
4983                                && crate::operator_confirm::ShortcutContext::route_eligible(
4984                                    &self.operator_app_policy,
4985                                    &self.launch_table,
4986                                    binding,
4987                                )
4988                        })
4989                        .map(|binding| {
4990                            let phone = crate::operator_confirm::ShortcutContext::phone_fingerprint(
4991                                &self.operator_app_policy,
4992                                binding,
4993                            );
4994                            let stamp = if phone.is_some() {
4995                                None
4996                            } else {
4997                                binding.operator_app.clone()
4998                            };
4999                            self.shortcut_context(
5000                                stamp,
5001                                phone,
5002                                Some((request.route_channel, request.route_epoch)),
5003                            )
5004                        });
5005                    confirms.admit_with_shortcut(
5006                        ctx,
5007                        frame,
5008                        module_id,
5009                        nonce_proven,
5010                        request,
5011                        binding,
5012                        shortcut,
5013                    )
5014                },
5015            )
5016            .map_err(RouterError::Forwarding)
5017    }
5018
5019    fn shortcut_context(
5020        &self,
5021        stamp: Option<crate::operator_apps::OperatorAppStamp>,
5022        phone_fingerprint: Option<String>,
5023        route: Option<(u16, u32)>,
5024    ) -> crate::operator_confirm::ShortcutContext {
5025        crate::operator_confirm::ShortcutContext {
5026            ledger: self.activity.clone(),
5027            forwarding: self.forwarding.clone(),
5028            launches: self.launch_table.clone(),
5029            stamp,
5030            phone_fingerprint,
5031            route,
5032            connections: self.operator_apps.clone(),
5033            #[cfg(test)]
5034            hooks: Default::default(),
5035        }
5036    }
5037
5038    /// Explicit test-only phone policy; daemon configuration cannot select it.
5039    #[cfg(any(test, feature = "test-support"))]
5040    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
5041        self.operator_app_policy.phone_enabled = enabled;
5042        self
5043    }
5044
5045    /// Resolve folders before taking the scope-table lock: a slow filesystem
5046    /// must not hold up admissions for unrelated scoped routes.
5047    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
5048        let mut scopes = ScopeRecords::from(scopes);
5049        for (index, record) in scopes.records.iter_mut().enumerate() {
5050            if let Some(refusal) = Self::canonicalize_workdir(record) {
5051                scopes.refusals.insert(index, refusal);
5052            }
5053        }
5054        scopes
5055    }
5056
5057    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
5058        let workdir = record.workdir.as_mut()?;
5059        let path = std::path::Path::new(workdir);
5060        if !path.is_absolute() {
5061            return Some((
5062                error_codes::INVALID_WORKDIR,
5063                "workdir must be absolute".to_string(),
5064            ));
5065        }
5066        match ProjectRootId::from_path_allowing_missing(path) {
5067            Ok(root) => match root.as_path().to_str() {
5068                Some(canonical) => {
5069                    *workdir = canonical.to_string();
5070                    None
5071                }
5072                None => Some((
5073                    error_codes::INVALID_WORKDIR,
5074                    "canonical workdir is not UTF-8".to_string(),
5075                )),
5076            },
5077            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
5078        }
5079    }
5080
5081    /// `scope.sync`: the owner is the module registered on this connection.
5082    /// A connection with no registration (every client connection, `direct`
5083    /// included) is refused `not_registered` before the table is consulted.
5084    fn handle_scope_sync(
5085        &self,
5086        connection_id: ConnectionId,
5087        frame: Frame,
5088        generation: u64,
5089        scopes: Vec<ScopeRecord>,
5090    ) -> Result<Vec<Frame>, RouterError> {
5091        self.handle_scope_change(connection_id, frame, generation, scopes, None)
5092    }
5093
5094    fn handle_scope_change(
5095        &self,
5096        connection_id: ConnectionId,
5097        frame: Frame,
5098        generation: u64,
5099        scopes: Vec<ScopeRecord>,
5100        end: Option<Vec<ScopeEnd>>,
5101    ) -> Result<Vec<Frame>, RouterError> {
5102        let is_apply = end.is_some();
5103        let Some(registration) = self
5104            .registry
5105            .get_module_by_connection(connection_id)
5106            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5107        else {
5108            return Ok(vec![control_error_frame(
5109                &frame,
5110                "not_registered",
5111                "scope.sync and scope.apply require an active module registration owned by this connection",
5112            )?]);
5113        };
5114        let owner = registration.manifest.module_id;
5115        let scopes = Self::prepare_scope_records(scopes);
5116        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
5117        let is_current_launch = |connection: ConnectionId| {
5118            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
5119        };
5120        // Lock order is the scope table, then the forwarding table: the new
5121        // tags are published, and the routes the change closes are selected,
5122        // while the scope table is still write-locked, so no admission can read
5123        // a record whose tag is not yet published.
5124        let mut table = self
5125            .scopes
5126            .write()
5127            .unwrap_or_else(|poisoned| poisoned.into_inner());
5128        let outcome = match end {
5129            Some(end) => table.apply(
5130                &owner,
5131                connection_id,
5132                is_current_launch,
5133                generation,
5134                scopes,
5135                end,
5136            ),
5137            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
5138        };
5139        let drained = match &outcome {
5140            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
5141            Err(_) => Vec::new(),
5142        };
5143        let has_deadlines = outcome.is_ok() && table.has_deadlines();
5144        drop(table);
5145        if has_deadlines {
5146            self.scope_deadline_added.notify_one();
5147        }
5148        match outcome {
5149            Ok(applied) => {
5150                let counts = ScopeOutcomeCounts::of(&applied.results);
5151                info!(
5152                    owner = %owner,
5153                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
5154                    generation,
5155                    records = applied.results.len(),
5156                    created = counts.created,
5157                    replaced = counts.replaced,
5158                    updated = counts.updated,
5159                    unchanged = counts.unchanged,
5160                    refused = counts.refused,
5161                    ended = applied.ended.len(),
5162                    tag_changes = applied.tag_changes.len(),
5163                    routes_closed = drained.len(),
5164                    "scope change accepted"
5165                );
5166                // An accepted scope change can still refuse individual records, and the
5167                // owner is the only party that sees the reply. Name them here so
5168                // an operator can tell a refused session from a missing one
5169                // without the owner's logs. Capped so a call that refuses
5170                // thousands cannot flood the log; the count above is complete.
5171                for refused in applied
5172                    .results
5173                    .iter()
5174                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
5175                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
5176                {
5177                    warn!(
5178                        owner = %owner,
5179                        generation,
5180                        scope_ref = %refused.scope_ref,
5181                        scope_epoch = refused.scope_epoch,
5182                        code = refused.code.as_deref().unwrap_or(""),
5183                        "scope record refused"
5184                    );
5185                }
5186                self.close_scope_drained_routes(drained);
5187                let response = if is_apply {
5188                    ModuleControlResponseToModule::ScopeApply {
5189                        generation,
5190                        results: applied.results,
5191                        end_results: applied.end_results,
5192                        ended: applied.ended,
5193                    }
5194                } else {
5195                    ModuleControlResponseToModule::ScopeSync {
5196                        generation,
5197                        results: applied.results,
5198                        ended: applied.ended,
5199                    }
5200                };
5201                Ok(vec![control_response_body_frame(
5202                    &frame,
5203                    &response,
5204                    "scope change response",
5205                )?])
5206            }
5207            Err(refusal) => {
5208                info!(
5209                    owner = %owner,
5210                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
5211                    generation,
5212                    code = refusal.code,
5213                    "scope change refused"
5214                );
5215                Ok(vec![control_error_frame(
5216                    &frame,
5217                    refusal.code,
5218                    refusal.message,
5219                )?])
5220            }
5221        }
5222    }
5223
5224    /// Notify both endpoints of routes drained by a scope change.
5225    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
5226        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
5227    }
5228
5229    /// Re-authorize a stored source on a principal the module supplies.
5230    ///
5231    /// That principal carries no spawn or authority epoch, so this reply never
5232    /// conveys a caller attestation or a first-party mark, and a provider must
5233    /// not apply automatic grants on anything it authorizes.
5234    fn handle_route_authorize(
5235        &self,
5236        connection_id: ConnectionId,
5237        frame: Frame,
5238        principal: Principal,
5239        scope: subc_protocol::scope::RouteAuthorizeScope,
5240        target: String,
5241        expected: subc_protocol::scope::RouteAuthorizeExpected,
5242    ) -> Result<Vec<Frame>, RouterError> {
5243        use crate::scopes::admission::{admit_route, AdmissionMode};
5244        use subc_protocol::scope::{
5245            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
5246        };
5247        let registry = self
5248            .registry
5249            .route_admission_snapshot()
5250            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5251        let owner_configured = match &scope.owner {
5252            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5253            _ => false,
5254        };
5255        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
5256        let answer = {
5257            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
5258            let permitted = registry
5259                .iter()
5260                .find(|r| r.connection_id == connection_id)
5261                .is_some_and(|r| {
5262                    scopes.is_federated_owner(&Principal::Reserved {
5263                        module_id: r.module_id.clone(),
5264                    }) && r.capabilities.as_ref().is_some_and(|caps| {
5265                        caps.provides
5266                            .iter()
5267                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
5268                    })
5269                });
5270            if !permitted {
5271                drop(scopes);
5272                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
5273                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
5274            }
5275            admit_route(
5276                &scopes,
5277                &registry,
5278                &principal,
5279                &target,
5280                Some(&selector),
5281                owner_configured,
5282                AdmissionMode::Authorize(&expected),
5283            )
5284        };
5285        let response = match answer {
5286            Ok(admission) => {
5287                let mut response = RouteAuthorizeResponse::new(
5288                    RouteAuthorizeOutcome::Authorized,
5289                    "route admission authorized",
5290                );
5291                response.content_version = admission.content_version;
5292                response
5293            }
5294            Err(refusal) => refusal.response(),
5295        };
5296        Ok(vec![control_response_body_frame(
5297            &frame,
5298            &response,
5299            "RouteAuthorizeResponse",
5300        )?])
5301    }
5302
5303    /// `scope.describe`: any registered module may read any scope, because a
5304    /// provider must read the scope a route it serves is stamped with.
5305    fn handle_scope_describe(
5306        &self,
5307        connection_id: ConnectionId,
5308        frame: Frame,
5309        owner: Principal,
5310        scope_ref: String,
5311    ) -> Result<Vec<Frame>, RouterError> {
5312        let registered = self
5313            .registry
5314            .get_module_by_connection(connection_id)
5315            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5316        let Some(registered) = registered else {
5317            return Ok(vec![control_error_frame(
5318                &frame,
5319                "not_registered",
5320                "scope.describe requires an active module registration owned by this connection",
5321            )?]);
5322        };
5323        let scopes = self
5324            .scopes
5325            .read()
5326            .unwrap_or_else(|poisoned| poisoned.into_inner());
5327        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5328            return Ok(vec![control_error_frame(
5329                &frame,
5330                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5331                "scope.describe of the federated owner requires scope-federated/v1",
5332            )?]);
5333        }
5334        let mut description = scopes.describe(&owner, &scope_ref);
5335        drop(scopes);
5336        if owner
5337            != (Principal::Reserved {
5338                module_id: registered.manifest.module_id.clone(),
5339            })
5340        {
5341            if let Some(facts) = description
5342                .stamp
5343                .as_mut()
5344                .and_then(|stamp| stamp.attributes.federated.as_mut())
5345            {
5346                facts.stamp_required = false;
5347            }
5348        }
5349        // Describe readers also decode strict ScopeAttributes. Attribution is
5350        // safe to omit unless the requesting module declares it understands it.
5351        if !registered
5352            .manifest
5353            .capabilities
5354            .as_ref()
5355            .is_some_and(|caps| {
5356                caps.provides
5357                    .iter()
5358                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5359            })
5360        {
5361            if let Some(stamp) = description.stamp.as_mut() {
5362                stamp.attributes.on_behalf_of_agent = None;
5363            }
5364        }
5365        if !registered
5366            .manifest
5367            .capabilities
5368            .as_ref()
5369            .is_some_and(|caps| {
5370                caps.provides
5371                    .iter()
5372                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5373            })
5374        {
5375            if let Some(stamp) = description.stamp.as_mut() {
5376                stamp.attributes.flow_version = None;
5377                stamp.attributes.flow_code_hash = None;
5378                stamp.attributes.flow_install_id = None;
5379            }
5380        }
5381        let owner_configured = match &owner {
5382            // Ask whether the owner is configured (`is_configured`), not
5383            // whether it is on the roster (`get(..).is_some()`): a supervised
5384            // module's process can register and describe a scope before the
5385            // supervisor has put it on the roster.
5386            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5387            _ => false,
5388        };
5389        let response = ModuleControlResponseToModule::ScopeDescribe {
5390            status: description.status,
5391            scope_epoch: description.scope_epoch,
5392            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5393            owner_synced: description.owner_synced,
5394            owner_configured,
5395            scope: description.stamp,
5396        };
5397        Ok(vec![control_response_body_frame(
5398            &frame,
5399            &response,
5400            "ModuleControlResponseToModule::ScopeDescribe",
5401        )?])
5402    }
5403
5404    fn handle_catalog_update_role_declarations(
5405        &self,
5406        connection_id: ConnectionId,
5407        frame: Frame,
5408        role_declarations: serde_json::Value,
5409    ) -> Result<Vec<Frame>, RouterError> {
5410        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5411            return Ok(vec![control_error_frame(
5412                &frame,
5413                "invalid_role_declarations",
5414                err.to_string(),
5415            )?]);
5416        }
5417        let declarations = serde_json::from_value(role_declarations)
5418            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5419        if self
5420            .registry
5421            .replace_role_declarations_for_connection(connection_id, declarations)
5422            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5423            .is_none()
5424        {
5425            return Ok(vec![control_error_frame(
5426                &frame,
5427                "not_registered",
5428                "catalog.update_role_declarations requires an active module registration owned by this connection",
5429            )?]);
5430        }
5431        control_response_body_frame(
5432            &frame,
5433            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5434            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5435        )
5436        .map(|frame| vec![frame])
5437    }
5438
5439    fn handle_catalog_update(
5440        &self,
5441        connection_id: ConnectionId,
5442        frame: Frame,
5443        provides: Vec<ProviderRole>,
5444        capabilities: Option<CapabilityDeclarations>,
5445        ready: Option<bool>,
5446    ) -> Result<Vec<Frame>, RouterError> {
5447        self.refresh_capability_requirements();
5448        let Some(registration) = self
5449            .registry
5450            .get_module_by_connection(connection_id)
5451            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5452        else {
5453            return Ok(vec![control_error_frame(
5454                &frame,
5455                "not_registered",
5456                "catalog.update requires an active module registration owned by this connection",
5457            )?]);
5458        };
5459
5460        if let Some(message) =
5461            catalog_update_frozen_field_message(&registration.manifest, &provides)
5462        {
5463            return Ok(vec![control_error_frame(
5464                &frame,
5465                "catalog_update_frozen_field",
5466                message,
5467            )?]);
5468        }
5469
5470        let mut candidate = registration.manifest.clone();
5471        candidate.provides = provides.clone();
5472        candidate.capabilities = capabilities
5473            .clone()
5474            .or_else(|| registration.manifest.capabilities.clone());
5475        if let Some(rich_ui) = &candidate.rich_ui {
5476            if let Err(err) = rich_ui.validate() {
5477                return Ok(vec![control_error_frame(
5478                    &frame,
5479                    "invalid_manifest",
5480                    err.to_string(),
5481                )?]);
5482            }
5483        }
5484        if let Err(err) = candidate.validate_capability_grammar() {
5485            return Ok(vec![control_error_frame(
5486                &frame,
5487                "invalid_capability_grammar",
5488                err.to_string(),
5489            )?]);
5490        }
5491
5492        // Updates must honor the same reserved owner as initial registration;
5493        // otherwise an empty HELLO could acquire the claim after admission.
5494        let mut conflicts = self
5495            .capability_evaluator
5496            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5497        if let Some(conflict) = conflicts.first() {
5498            let message = format!(
5499                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5500                conflict.capability, conflict.claimants[0], candidate.module_id
5501            );
5502            for conflict in &mut conflicts {
5503                conflict.source = DuplicateClaimSource::CatalogUpdate;
5504            }
5505            log_duplicate_claim_events(conflicts);
5506            return Ok(vec![control_error_frame(
5507                &frame,
5508                "reserved_capability",
5509                message,
5510            )?]);
5511        }
5512
5513        let updated = match self.registry.replace_catalog_for_connection(
5514            connection_id,
5515            provides,
5516            capabilities,
5517            ready,
5518        ) {
5519            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5520                return Ok(vec![control_error_frame(
5521                    &frame,
5522                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5523                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5524                )?])
5525            }
5526            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5527                return Ok(vec![control_error_frame(
5528                    &frame,
5529                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5530                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5531                )?])
5532            }
5533            result => {
5534                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5535            }
5536        };
5537        if updated.is_none() {
5538            return Ok(vec![control_error_frame(
5539                &frame,
5540                "not_registered",
5541                "catalog.update requires an active module registration owned by this connection",
5542            )?]);
5543        }
5544        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5545            log_duplicate_claim_events(
5546                self.capability_evaluator
5547                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5548            );
5549        }
5550        if capability_census_trigger(
5551            registration.manifest.capabilities.as_ref(),
5552            updated
5553                .as_ref()
5554                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5555        ) {
5556            self.enforce_capability_denies();
5557        }
5558        self.refresh_capability_requirements();
5559
5560        let response = ModuleControlResponseToModule::CatalogUpdate {};
5561        control_response_body_frame(
5562            &frame,
5563            &response,
5564            "ModuleControlResponseToModule::CatalogUpdate",
5565        )
5566        .map(|frame| vec![frame])
5567    }
5568
5569    pub(crate) fn with_activity_ledger_config(
5570        mut self,
5571        run_dir: &Path,
5572        incarnation: String,
5573        config: crate::activity::ActivityConfig,
5574    ) -> Self {
5575        self.activity = Some(crate::activity::ActivityLedger::open_config(
5576            run_dir.join("activity.jsonl"),
5577            incarnation,
5578            config,
5579        ));
5580        self.supervisor.set_activity(self.activity.clone());
5581        self
5582    }
5583
5584    pub(crate) async fn configure_activity(
5585        &self,
5586        config: crate::activity::ActivityConfig,
5587    ) -> Result<(), &'static str> {
5588        match &self.activity {
5589            Some(ledger) => ledger.configure(config).await,
5590            None => Ok(()),
5591        }
5592    }
5593
5594    fn cancel_activity_subscription(
5595        &self,
5596        ctx: &RouteCtx,
5597        frame: &Frame,
5598    ) -> Result<bool, RouterError> {
5599        let task = self
5600            .activity_streams
5601            .lock()
5602            .unwrap_or_else(|p| p.into_inner())
5603            .remove(&(ctx.connection_id, frame.header.corr));
5604        let Some(task) = task else {
5605            return Ok(false);
5606        };
5607        task.abort();
5608        let end = Frame::build_with_version(
5609            response_version(frame),
5610            FrameType::StreamEnd,
5611            control_flags(),
5612            0,
5613            0,
5614            frame.header.corr,
5615            Vec::new(),
5616        )
5617        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5618        let sink = ctx.egress.clone();
5619        tokio::spawn(async move {
5620            let _ = sink.send(end).await;
5621        });
5622        Ok(true)
5623    }
5624
5625    async fn handle_activity_read(
5626        &self,
5627        ctx: &RouteCtx,
5628        frame: Frame,
5629    ) -> Result<Vec<Frame>, RouterError> {
5630        #[cfg(test)]
5631        {
5632            let pause = self
5633                .activity_request_pause
5634                .lock()
5635                .unwrap()
5636                .clone()
5637                .filter(|pause| pause.connection == ctx.connection_id);
5638            if let Some(pause) = pause {
5639                let _cancelled = ActivityRequestCancellation(pause.clone());
5640                pause.started.notify_one();
5641                std::future::pending::<()>().await;
5642            }
5643        }
5644        use subc_control::{
5645            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5646            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5647        };
5648        #[derive(Deserialize)]
5649        struct Identity {
5650            #[serde(default)]
5651            consumer_identity: Option<ConsumerIdentity>,
5652        }
5653        // A registration channel or claim-bound connection carries its module in
5654        // its binding, so no request field can name another principal, and its
5655        // subscription ends when the bound spawn's authority does.
5656        let mut bound_spawn = None;
5657        let legacy = match self.activity_reader(ctx.connection_id) {
5658            channel_operations::ActivityReader::Module { module_id, spawn } => {
5659                bound_spawn = Some(spawn);
5660                Some(Ok(Principal::Reserved { module_id }))
5661            }
5662            // Refused outright: falling back to `direct` would admit it.
5663            channel_operations::ActivityReader::Refused => {
5664                return Ok(vec![control_error_frame(
5665                    &frame,
5666                    ACTIVITY_READ_FORBIDDEN,
5667                    "helper, relay and retired connections cannot read activity",
5668                )?]);
5669            }
5670            channel_operations::ActivityReader::Legacy => None,
5671        };
5672        // A registered module connection already identifies its caller. Ignore
5673        // consumer_identity there so a module cannot borrow a mirror's identity.
5674        // Only separate consumer connections use the Direct/nonce trust boundary.
5675        let principal = match legacy {
5676            Some(principal) => principal,
5677            None => match self
5678                .forwarding
5679                .module_id_for_connection(ctx.connection_id)
5680                .map_err(RouterError::Forwarding)?
5681            {
5682                Some(module_id) => Ok(Principal::Reserved { module_id }),
5683                None => {
5684                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5685                        Ok(identity) => identity,
5686                        Err(_) => {
5687                            return Ok(vec![control_error_frame(
5688                                &frame,
5689                                ACTIVITY_MALFORMED,
5690                                "malformed activity read",
5691                            )?])
5692                        }
5693                    };
5694                    self.route_open_principal(
5695                        ctx.connection_id,
5696                        &frame,
5697                        identity.consumer_identity,
5698                    )?
5699                }
5700            },
5701        };
5702        let admitted = matches!(principal, Ok(Principal::Direct))
5703            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5704        if !admitted {
5705            return Ok(vec![control_error_frame(
5706                &frame,
5707                ACTIVITY_READ_FORBIDDEN,
5708                "activity reads require an operator or trusted mirror principal",
5709            )?]);
5710        }
5711        let Some(ledger) = &self.activity else {
5712            return Ok(vec![control_error_frame(
5713                &frame,
5714                ACTIVITY_UNAVAILABLE,
5715                "activity ledger unavailable",
5716            )?]);
5717        };
5718        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5719            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5720        {
5721            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5722                Ok(request) => ledger.query(request).await,
5723                Err(_) => Err(ACTIVITY_MALFORMED),
5724            };
5725            return match result {
5726                Ok(reply) => Ok(vec![control_response_body_frame(
5727                    &frame,
5728                    &reply,
5729                    ops::ACTIVITY_QUERY,
5730                )?]),
5731                Err(code) => Ok(vec![control_error_frame(
5732                    &frame,
5733                    code,
5734                    "activity query refused",
5735                )?]),
5736            };
5737        }
5738        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5739            Ok(request) => request,
5740            Err(_) => {
5741                return Ok(vec![control_error_frame(
5742                    &frame,
5743                    ACTIVITY_MALFORMED,
5744                    "malformed activity subscription",
5745                )?])
5746            }
5747        };
5748        let mut subscription = match ledger.subscribe(request.since).await {
5749            Ok(subscription) => subscription,
5750            Err(code) => {
5751                return Ok(vec![control_error_frame(
5752                    &frame,
5753                    code,
5754                    "activity subscription refused",
5755                )?])
5756            }
5757        };
5758        let key = (ctx.connection_id, frame.header.corr);
5759        let sink = ctx.egress.clone();
5760        let mut streams = self
5761            .activity_streams
5762            .lock()
5763            .unwrap_or_else(|p| p.into_inner());
5764        streams.retain(|_, task| !task.is_finished());
5765        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5766            return Ok(vec![control_error_frame(
5767                &frame,
5768                "duplicate_subscription",
5769                "activity subscription correlation id already in use",
5770            )?]);
5771        }
5772        let stream = async move {
5773            loop {
5774                let entry = if let Some(entry) = subscription.replay.pop_front() {
5775                    Some(entry)
5776                } else {
5777                    subscription.receiver.recv().await
5778                };
5779                let Some(entry) = entry else {
5780                    break;
5781                };
5782                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5783                    return;
5784                };
5785                let Ok(next) = Frame::build_with_version(
5786                    response_version(&frame),
5787                    FrameType::StreamData,
5788                    control_flags(),
5789                    0,
5790                    0,
5791                    frame.header.corr,
5792                    body,
5793                ) else {
5794                    return;
5795                };
5796                if sink.send(next).await.is_err() {
5797                    return;
5798                }
5799            }
5800            // Dropping a full subscriber's sender drains its accepted entries
5801            // before the terminal error, preserving their order on the wire.
5802            if let Some(code) = subscription.terminal_code() {
5803                if let Ok(end) =
5804                    control_error_frame(&frame, code, "activity subscriber fell behind")
5805                {
5806                    let _ = sink.send(end).await;
5807                }
5808            }
5809        };
5810        // The spawn's retirement revokes this connection's authority. End the
5811        // subscription then, rather than when the connection's close is
5812        // eventually processed or the next entry fails to send.
5813        let task = tokio::spawn(async move {
5814            match bound_spawn {
5815                Some(spawn) => {
5816                    tokio::select! {
5817                        () = stream => {}
5818                        () = spawn.wait_closed() => {}
5819                    }
5820                }
5821                None => stream.await,
5822            }
5823        });
5824        streams.insert(key, task.abort_handle());
5825        Ok(Vec::new())
5826    }
5827
5828    async fn handle_activity_record(
5829        &self,
5830        ctx: &RouteCtx,
5831        frame: Frame,
5832    ) -> Result<Vec<Frame>, RouterError> {
5833        use subc_control::{
5834            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5835            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5836        };
5837        let result = async {
5838            let module = self
5839                .forwarding
5840                .module_id_for_connection(ctx.connection_id)
5841                .ok()
5842                .flatten()
5843                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5844            let request: ActivityRecordRequest =
5845                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5846            crate::activity::validate(&module, &request)?;
5847            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5848            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5849            let at_ms = std::time::SystemTime::now()
5850                .duration_since(std::time::UNIX_EPOCH)
5851                .unwrap_or_default()
5852                .as_millis() as u64;
5853            ledger.record(module, request, actor, at_ms).await
5854        }
5855        .await;
5856        match result {
5857            Ok(entry) => Ok(vec![control_response_body_frame(
5858                &frame,
5859                &ActivityRecordResponse { seq: entry.seq },
5860                "activity.record",
5861            )?]),
5862            Err(code) => Ok(vec![control_error_frame(
5863                &frame,
5864                code,
5865                "activity recording refused",
5866            )?]),
5867        }
5868    }
5869
5870    fn activity_actor(
5871        &self,
5872        connection: ConnectionId,
5873        module: &str,
5874        on: Option<&subc_control::ActivityOn>,
5875    ) -> Result<subc_control::ActivityActor, &'static str> {
5876        use crate::forwarding::{DataRoute, DataRouteState};
5877        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5878        let principal = |id: &str| Principal::Reserved {
5879            module_id: id.to_owned(),
5880        };
5881        let mut actor = ActivityActor {
5882            principal: principal(module),
5883            scope_owner: None,
5884            agent_id: None,
5885            run_id: None,
5886            flow_id: None,
5887            project_root: None,
5888            workdir: None,
5889            project_id: None,
5890        };
5891        let scope = match on {
5892            None => return Ok(actor),
5893            Some(ActivityOn::Scope(scope)) => {
5894                let selector = subc_protocol::scope::ScopeSelector::new(
5895                    principal(module),
5896                    scope.scope_ref.clone(),
5897                    Some(scope.epoch),
5898                );
5899                self.scopes
5900                    .read()
5901                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5902                    .attribute(&principal(module), module, &selector, true)
5903                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5904            }
5905            Some(ActivityOn::Route(route)) => {
5906                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5907                    .forwarding
5908                    .lookup_data_route(connection, route.channel, route.epoch)
5909                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5910                else {
5911                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5912                };
5913                if binding.module_id != module {
5914                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5915                }
5916                actor.principal = binding.principal.clone();
5917                actor.project_root = binding
5918                    .project_root
5919                    .as_ref()
5920                    .map(|root| root.as_path().to_path_buf());
5921                let Some(bound) = &binding.scope else {
5922                    return Ok(actor);
5923                };
5924                let owner = principal(&bound.owner);
5925                let selector = subc_protocol::scope::ScopeSelector::new(
5926                    owner.clone(),
5927                    bound.scope_ref.clone(),
5928                    Some(bound.tag.scope_epoch),
5929                );
5930                let admitted = self
5931                    .scopes
5932                    .read()
5933                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5934                    .attribute(&owner, module, &selector, true)
5935                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5936                if admitted.tag != bound.tag {
5937                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5938                }
5939                admitted
5940            }
5941        };
5942        actor.scope_owner = Some(scope.stamp.owner);
5943        actor.agent_id = scope.stamp.attributes.agent_id;
5944        actor.run_id = scope.stamp.attributes.run_id;
5945        actor.flow_id = scope.stamp.attributes.flow_id;
5946        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5947        actor.project_id = scope.stamp.project_id;
5948        Ok(actor)
5949    }
5950
5951    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5952        let module_id = self
5953            .claims
5954            .binding(connection)
5955            .filter(|binding| {
5956                binding.consumer_live(connection) && binding.registration.authority.alive()
5957            })
5958            .map(|binding| binding.registration.module_id.clone())
5959            .or_else(|| {
5960                self.registry
5961                    .module_id_for_connection(connection)
5962                    .ok()
5963                    .flatten()
5964            });
5965        let principal = module_id
5966            .map(|module_id| format!("reserved:{module_id}"))
5967            .unwrap_or_else(|| "direct".to_owned());
5968        self.control_usage
5969            .lock()
5970            .unwrap_or_else(|poisoned| poisoned.into_inner())
5971            .record(op, &principal);
5972    }
5973
5974    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5975        self.refresh_capability_requirements();
5976        // A bare connection count is ambiguous between many clients holding a
5977        // route each and one client accumulating hundreds, so publish the
5978        // concentration alongside it. Route state is best-effort here: a
5979        // diagnostic endpoint must still answer if the forwarding lock is
5980        // contended.
5981        let mut counters = self.counters.snapshot();
5982        if let Some(obj) = counters.as_object_mut() {
5983            obj.insert(
5984                "control_usage".into(),
5985                self.control_usage
5986                    .lock()
5987                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5988                    .snapshot(),
5989            );
5990        }
5991        let losses = self.resource_tracker.loss_diagnostics();
5992        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5993            if let Some(obj) = counters.as_object_mut() {
5994                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5995            }
5996        }
5997        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5998            obj.insert(
5999                "activity_unparseable_lines".into(),
6000                ledger.read_errors().into(),
6001            );
6002            obj.insert(
6003                "activity_lifecycle_append_failures".into(),
6004                ledger.lifecycle_failures().into(),
6005            );
6006            obj.insert(
6007                "activity_started_digest_skips".into(),
6008                ledger.lifecycle_digest_skips().into(),
6009            );
6010        }
6011        if let (Ok((connections_with_routes, max)), Some(obj)) = (
6012            self.forwarding.client_route_concentration(),
6013            counters.as_object_mut(),
6014        ) {
6015            obj.insert(
6016                "client_connections_with_routes".into(),
6017                connections_with_routes.into(),
6018            );
6019            obj.insert("max_routes_on_one_connection".into(), max.into());
6020        }
6021        // A module that is being fast-refused and a module that is fine look
6022        // identical from a client that retries and succeeds, so name the open
6023        // breakers here. This rides the existing free-form counters object
6024        // rather than a new wire field, so no sibling that deserializes
6025        // `ServerDescribe` has to be rebuilt to keep reading it.
6026        if let (Some(open_breakers), Some(obj)) = (
6027            self.route_bind_breakers.open_snapshot(),
6028            counters.as_object_mut(),
6029        ) {
6030            obj.insert("route_bind_breakers_open".into(), open_breakers);
6031        }
6032        // A daemon whose local endpoint could not be bound keeps serving TCP,
6033        // and the connection file names no endpoint. Name the reason here, in
6034        // the free-form counters object, so an operator reading daemon facts
6035        // sees it without searching the log, and no wire field changes.
6036        if let (Some(reason), Some(obj)) = (
6037            self.local_endpoint_unavailable.clone(),
6038            counters.as_object_mut(),
6039        ) {
6040            obj.insert("local_endpoint_unavailable".into(), reason.into());
6041        }
6042        let response = ClientControlResponse::ServerDescribe {
6043            protocol_ver: PROTOCOL_VERSION,
6044            subc_ops: subc_ops(),
6045            capabilities: self.describe_capabilities(),
6046            connected_clients: self.connected_clients.count(),
6047            counters: Some(counters),
6048            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
6049            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
6050            capability_requirements: self.capability_requirement_statuses(),
6051            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
6052            config_path: self
6053                .rescan
6054                .as_ref()
6055                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
6056        };
6057        Ok(vec![control_response_body_frame(
6058            &frame,
6059            &response,
6060            "ClientControlResponse::ServerDescribe",
6061        )?])
6062    }
6063
6064    fn handle_catalog_list(
6065        &self,
6066        frame: Frame,
6067        module_id: Option<String>,
6068    ) -> Result<Vec<Frame>, RouterError> {
6069        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
6070        Ok(vec![Frame::build_with_version(
6071            response_version(&frame),
6072            FrameType::Response,
6073            control_flags(),
6074            0,
6075            0,
6076            frame.header.corr,
6077            body,
6078        )
6079        .map_err(RouterError::FrameBuild)?])
6080    }
6081
6082    #[cfg(test)]
6083    fn uncached_catalog_list(
6084        &self,
6085        corr: u64,
6086        module_id: Option<&str>,
6087    ) -> Result<ClientControlResponse, RouterError> {
6088        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
6089    }
6090
6091    fn catalog_list_snapshot(
6092        &self,
6093        corr: u64,
6094        module_id: Option<&str>,
6095        include_declarations: bool,
6096    ) -> Result<ClientControlResponse, RouterError> {
6097        let (generation, modules) = self
6098            .registry
6099            .list_modules_with_nonce_verification()
6100            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
6101        let entries = modules
6102            .into_iter()
6103            .filter(|(registration, _)| {
6104                module_id
6105                    .map(|wanted| registration.manifest.module_id == wanted)
6106                    .unwrap_or(true)
6107            })
6108            .map(|(registration, nonce_verified)| {
6109                let entry = self
6110                    .catalog_discovery_entry(&registration, include_declarations)
6111                    .map_err(|err| RouterError::backend(0, corr, err))?;
6112                let not_ready = self.not_ready_reason(&registration);
6113                let mut entry = entry;
6114                entry.roles = registration.manifest.provides;
6115                entry.control_ops = registration.control_ops;
6116                Ok(entry
6117                    .with_ready(not_ready.is_none())
6118                    .with_display_name(registration.manifest.display_name)
6119                    .with_not_ready(not_ready)
6120                    .with_module_version(Some(registration.manifest.module_version))
6121                    .with_provenance(registration.manifest.provenance)
6122                    .with_capabilities(registration.manifest.capabilities)
6123                    .with_self_signals(registration.manifest.self_signals)
6124                    .with_events(registration.manifest.events)
6125                    .with_operation_delivery(registration.manifest.operation_delivery)
6126                    .with_operation_payload(registration.manifest.operation_payload)
6127                    .with_flow_operations(registration.manifest.flow_operations)
6128                    .with_operation_deferral(registration.manifest.operation_deferral)
6129                    .with_confirm_operations(registration.manifest.confirm_operations)
6130                    .with_rich_ui(registration.manifest.rich_ui)
6131                    .with_role_declarations(registration.manifest.role_declarations)
6132                    .with_nonce_verified(nonce_verified))
6133            })
6134            .collect::<Result<Vec<_>, RouterError>>()?;
6135        Ok(ClientControlResponse::CatalogList {
6136            generation,
6137            modules: entries,
6138            subc_ops: subc_ops(),
6139        })
6140    }
6141
6142    /// The caller fields for a refusal that only has the raw request frame,
6143    /// such as the connection-level admission refusal sent before the request
6144    /// reaches [`Self::handle_route_open`].
6145    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
6146        let Ok(ClientControlRequest::RouteOpen {
6147            identity,
6148            consumer_identity,
6149            scope,
6150            ..
6151        }) = parse_client_control_request(&frame.body)
6152        else {
6153            return RouteOpenCaller::unknown();
6154        };
6155        let principal = self
6156            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
6157            .map(|attested| attested.principal);
6158        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
6159    }
6160
6161    fn route_open_principal(
6162        &self,
6163        connection_id: ConnectionId,
6164        frame: &Frame,
6165        consumer_identity: Option<ConsumerIdentity>,
6166    ) -> Result<Result<Principal, Frame>, RouterError> {
6167        let attested = self
6168            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
6169            .map(|attested| attested.principal);
6170        self.route_open_principal_attested(frame, consumer_identity, attested)
6171    }
6172
6173    /// [`Self::route_open_principal`] with `attested` already taken by
6174    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
6175    /// claim or launch nonce once.
6176    fn route_open_principal_attested(
6177        &self,
6178        frame: &Frame,
6179        consumer_identity: Option<ConsumerIdentity>,
6180        attested: Option<Principal>,
6181    ) -> Result<Result<Principal, Frame>, RouterError> {
6182        if let Some(principal) = attested {
6183            return Ok(Ok(principal));
6184        }
6185        Ok(Err(control_error_frame(
6186            frame,
6187            "bad_consumer_identity",
6188            consumer_identity.map_or_else(
6189                || "connection claim is no longer authorized for routes".to_string(),
6190                |identity| format!(
6191                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
6192                    identity.module_id
6193                ),
6194            ),
6195        )?))
6196    }
6197
6198    /// Ordinary `route.open` refusals go through here; admission and breaker
6199    /// refusals log separately with their capacity or breaker state. The daemon can
6200    /// attest which code it sent: without the event, a client's "the daemon
6201    /// refused me" and the daemon's own view could only be reconciled by
6202    /// argument. Malformed input (`invalid_project_root`) does not come here;
6203    /// rejecting a request that was never a valid open is not a refusal of one.
6204    #[allow(clippy::too_many_arguments)]
6205    fn route_open_refusal_frame(
6206        &self,
6207        ctx: &RouteCtx,
6208        caller: &RouteOpenCaller,
6209        frame: &Frame,
6210        module_id: &str,
6211        reason: &'static str,
6212        code: &'static str,
6213        message: impl Into<String>,
6214    ) -> Result<Frame, RouterError> {
6215        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
6216        let detail = if matches!(
6217            reason,
6218            "registration_not_active"
6219                | "supervisor_not_live"
6220                | "no_forwarding_connection"
6221                | "reloading"
6222        ) {
6223            // A planned restart, reload or swap is already replacing the
6224            // process; it does not need a slot in the crash-restart budget.
6225            let expected_back = (reason == "reloading").then_some(true);
6226            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
6227        } else {
6228            None
6229        };
6230        control_error_body_frame(
6231            frame,
6232            ErrorBody {
6233                code: code.to_string(),
6234                message: message.into(),
6235                detail,
6236            },
6237        )
6238    }
6239
6240    fn route_open_recovery_detail(
6241        &self,
6242        module_id: &str,
6243        corr: u64,
6244        detail: Option<serde_json::Value>,
6245        expected_back: Option<bool>,
6246    ) -> Result<Option<serde_json::Value>, RouterError> {
6247        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
6248            return Ok(detail);
6249        };
6250        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
6251        detail["state"] = serde_json::json!(status.state.to_string());
6252        if let Some(expected_back) = expected_back {
6253            detail["expected_back"] = serde_json::json!(expected_back);
6254        } else if let Some(module) = self.supervisor.get(module_id) {
6255            match module.will_recover_after_connection_loss() {
6256                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
6257                Err(err) => warn!(
6258                    %module_id,
6259                    error = %err,
6260                    "failed to read route.open recovery verdict; omitting expected_back"
6261                ),
6262            }
6263        }
6264        Ok(Some(detail))
6265    }
6266
6267    /// Answer a waiting `route.open` whose relayed bind was refused.
6268    ///
6269    /// `daemon_authored` is provenance, not a code match: the daemon
6270    /// synthesized the refusal itself (a drain, a late reply, a scope that
6271    /// ended mid-bind) or the module refused the bind with its own body. A
6272    /// daemon refusal carries the daemon-origin bit; a module's own
6273    /// rejection is relayed with the bit clear, so a module that refuses
6274    /// with `module_reloading` still cannot mint a daemon refusal.
6275    #[allow(clippy::too_many_arguments)]
6276    fn route_bind_rejection(
6277        &self,
6278        ctx: &RouteCtx,
6279        caller: &RouteOpenCaller,
6280        frame: &Frame,
6281        target_module_id: &str,
6282        body: ErrorBody,
6283        daemon_authored: bool,
6284    ) -> Result<Vec<Frame>, RouterError> {
6285        // The daemon's own commit re-check refused the bind because the
6286        // scope ended or changed after admission. The module accepted;
6287        // counting it as a module rejection would blame the module. This
6288        // branch only runs for daemon-synthesized bodies: a module that
6289        // refuses with a scope code is answered as a module rejection below.
6290        if daemon_authored {
6291            let scope_code = match body.code.as_str() {
6292                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
6293                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
6294                _ => None,
6295            };
6296            if let Some(code) = scope_code {
6297                self.observe_route_open_refusal(
6298                    ctx,
6299                    caller,
6300                    target_module_id,
6301                    "scope_changed_before_commit",
6302                    code,
6303                );
6304                return Ok(vec![control_error_body_frame(frame, body)?]);
6305            }
6306        }
6307        self.counters
6308            .increment_route_open_refused("module_rejected");
6309        info!(
6310            target: "control",
6311            code = "module_rejected",
6312            module_code = ?body.code,
6313            module_id = ?target_module_id,
6314            connection_id = ctx.connection_id.get(),
6315            principal = %caller.principal,
6316            scope = %caller.scope,
6317            harness = %caller.harness,
6318            "route.open refused"
6319        );
6320        let refusal = if daemon_authored {
6321            control_error_body_frame(frame, body)?
6322        } else {
6323            control_relayed_error_body_frame(frame, body)?
6324        };
6325        Ok(vec![refusal])
6326    }
6327
6328    /// Refuse a `route.open` because the target module's bind-relay breaker is
6329    /// open, without attempting the relay.
6330    ///
6331    /// The wire code is `module_timeout`, which is the truth (the module has
6332    /// not been answering binds) and which both SDKs already classify as
6333    /// retryable with capped backoff. Reusing it is what keeps this change out
6334    /// of both SDKs; the daemon-side distinction lives in the counter key
6335    /// instead.
6336    ///
6337    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6338    /// While a breaker is open this fires on every open to that module, and the
6339    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6340    /// produced 261 lines about a single module inside 3000 lines of daemon
6341    /// log. The rare transitions are logged at warn/info instead and the volume
6342    /// is carried by the counter, so the evidence survives without the flood.
6343    /// The debug line keeps a per-refusal record reachable for whoever turns
6344    /// the level up.
6345    #[allow(clippy::too_many_arguments)]
6346    fn route_open_breaker_refusal_frame(
6347        &self,
6348        ctx: &RouteCtx,
6349        caller: &RouteOpenCaller,
6350        frame: &Frame,
6351        module_id: &str,
6352        consecutive_timeouts: u32,
6353        retry_in: Duration,
6354        probe_in_flight: bool,
6355    ) -> Result<Frame, RouterError> {
6356        self.counters
6357            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6358        debug!(
6359            target: "control",
6360            code = "module_timeout",
6361            module_id = ?module_id,
6362            connection_id = ctx.connection_id.get(),
6363            principal = %caller.principal,
6364            scope = %caller.scope,
6365            harness = %caller.harness,
6366            consecutive_timeouts,
6367            retry_in_ms = retry_in.as_millis() as u64,
6368            probe_in_flight,
6369            "route.open refused by open bind-relay breaker"
6370        );
6371        // Say what a caller can act on. An open bind-relay breaker means the
6372        // module timed out accepting several new routes in a row. The module
6373        // is still running and its established routes keep working; only new
6374        // route.open requests are refused until the cooldown ends and one
6375        // test route (the probe) gets through. A message that only counts
6376        // failed relays reads as "the module is down" to a worker that sees it.
6377        let detail = if probe_in_flight {
6378            "one test route is already being tried; retry once it settles".to_string()
6379        } else {
6380            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6381        };
6382        control_error_frame(
6383            frame,
6384            "module_timeout",
6385            format!(
6386                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6387                 timed out in a row); {detail}; its established routes are unaffected"
6388            ),
6389        )
6390    }
6391
6392    /// `code` is daemon vocabulary and prints plainly; `module_id` is the
6393    /// requester's bytes (an unknown target is whatever the client sent) and
6394    /// is Debug-formatted so control characters land in the log escaped
6395    /// rather than as terminal sequences for whoever tails it.
6396    ///
6397    /// `reason` names the check that refused, because one wire code has
6398    /// several senders: after a module registers, `target_unavailable` can
6399    /// come from a missing role, an inactive registration, a supervisor that
6400    /// has not marked the process live, a missing forwarding connection, or a
6401    /// failed relay, and a log that records only the code cannot say which of
6402    /// them fired. It is a static, daemon-chosen label per branch, so it is
6403    /// safe to print plainly and stays a closed set.
6404    fn observe_route_open_refusal(
6405        &self,
6406        ctx: &RouteCtx,
6407        caller: &RouteOpenCaller,
6408        module_id: &str,
6409        reason: &'static str,
6410        code: &'static str,
6411    ) {
6412        self.counters.increment_route_open_refused(code);
6413        info!(
6414            target: "control",
6415            code,
6416            reason,
6417            module_id = ?module_id,
6418            connection_id = ctx.connection_id.get(),
6419            principal = %caller.principal,
6420            scope = %caller.scope,
6421            harness = %caller.harness,
6422            "route.open refused"
6423        );
6424        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6425            self.route_outages.record_not_serving(module_id, reason);
6426        }
6427    }
6428
6429    /// Record an ACCEPTED route.open.
6430    ///
6431    /// Refusals have been logged and counted since the attestation work; accepts
6432    /// were invisible, so the daemon knew every principal it stamped and wrote
6433    /// none of them down. The party that attests the identity was the only party
6434    /// not recording it, which left a credential vault unable to name the sender
6435    /// of a call that reached it (claustrum #43) and left the launch-nonce
6436    /// concurrency question unanswerable from the outside.
6437    ///
6438    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6439    /// `code`/`module_id`/`connection_id` returns both directions of the same
6440    /// decision rather than two shapes a reader has to join by hand.
6441    ///
6442    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6443    /// and the difference carries information rather than being an
6444    /// inconsistency. This line is only reachable after a successful bind to a
6445    /// REGISTERED module, so the value has already passed HELLO validation
6446    /// including the path-hazard refusal and cannot contain control bytes. A
6447    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6448    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6449    ///
6450    /// Bare is also what every other daemon line already emits (`module
6451    /// registered`, `configured module supervised`). Shipping `?module_id` here
6452    /// made this instrument the only one in the file whose ids did not answer
6453    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6454    /// line whose whole purpose is being grepped beside its sibling.
6455    ///
6456    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6457    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6458    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6459    /// one are recorded identically. A test written against that harness passes
6460    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6461    /// green assertion that cannot fail. The same limit applies to the escaping
6462    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6463    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6464    /// Fencing either needs the real formatter, not the capture layer.
6465    ///
6466    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6467    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6468    /// to record. The ephemeral port would decay within minutes and answer only a
6469    /// live question. The identity question is instead answered by counting
6470    /// distinct live connections presenting one module's `consumer_identity` --
6471    /// "is anyone else holding this secret" rather than "is this the right
6472    /// process".
6473    fn observe_route_open_accept(
6474        &self,
6475        ctx: &RouteCtx,
6476        module_id: &str,
6477        principal: &str,
6478        scope: &str,
6479    ) {
6480        self.route_outages.record_accepted(module_id);
6481        self.counters.increment_route_open_accepted(principal);
6482        debug!(
6483            target: "control",
6484            principal,
6485            module_id,
6486            connection_id = ctx.connection_id.get(),
6487            scope = %scope,
6488            "route.open accepted"
6489        );
6490    }
6491
6492    fn supervised_absent_route_open_refusal_frame(
6493        &self,
6494        ctx: &RouteCtx,
6495        caller: &RouteOpenCaller,
6496        frame: &Frame,
6497        module_id: &str,
6498        code: &'static str,
6499        status: &crate::supervise::ModuleStatus,
6500    ) -> Result<Frame, RouterError> {
6501        self.counters.increment_route_open_refused(code);
6502        info!(
6503            target: "control",
6504            code,
6505            reason = "supervised_not_registered",
6506            module_id = ?module_id,
6507            connection_id = ctx.connection_id.get(),
6508            principal = %caller.principal,
6509            scope = %caller.scope,
6510            harness = %caller.harness,
6511            state = %status.state,
6512            enabled = status.enabled,
6513            live = status.live,
6514            "route.open refused"
6515        );
6516        // A supervised module whose process has not registered is not
6517        // serving, whatever the reason; the supervisor knows this id, so it is
6518        // safe to track.
6519        self.route_outages
6520            .record_not_serving(module_id, "supervised_not_registered");
6521        let message = if let Some(pid) = status.waiting_for_previous_pid {
6522            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6523                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6524            })
6525        } else {
6526            format!(
6527                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6528                status.state, status.enabled, status.live
6529            )
6530        };
6531        // `module_warming` here means the process is starting, running or
6532        // being restarted and has not registered yet. Nothing has to be
6533        // restarted for it to serve, so the crash budget does not decide it.
6534        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6535        control_error_body_frame(
6536            frame,
6537            ErrorBody {
6538                code: code.to_string(),
6539                message,
6540                detail: self.route_open_recovery_detail(
6541                    module_id,
6542                    frame.header.corr,
6543                    None,
6544                    expected_back,
6545                )?,
6546            },
6547        )
6548    }
6549
6550    async fn handle_route_open(
6551        &self,
6552        ctx: &RouteCtx,
6553        frame: Frame,
6554        request: RouteOpenRequest,
6555        timings: &mut RouteOpenTimings,
6556    ) -> Result<Vec<Frame>, RouterError> {
6557        let RouteOpenRequest {
6558            target,
6559            mut identity,
6560            consumer_identity,
6561            consumer_capabilities,
6562            role_versions,
6563            busy_refusals,
6564            admission_facts,
6565            scope,
6566            accepts_close_reasons,
6567        } = request;
6568        let target_module_id = target_module_id(&target).to_string();
6569        timings.module_id.clone_from(&target_module_id);
6570        if self
6571            .registry
6572            .get_module_by_connection(ctx.connection_id)
6573            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6574            .is_some()
6575        {
6576            return Ok(vec![control_error_frame(
6577                &frame,
6578                "invalid_request",
6579                "module connections cannot open client routes",
6580            )?]);
6581        }
6582        debug!(
6583            connection_id = ctx.connection_id.get(),
6584            corr = frame.header.corr,
6585            module_id = %target_module_id,
6586            "handling route.open"
6587        );
6588
6589        // The caller's attested principal, requested scope and harness, for
6590        // every `route.open refused` line below. The connection's claim
6591        // binding or launch nonce is checked here, once, and the answer is
6592        // reused where the principal is enforced further down, so the order
6593        // of refusals is unchanged.
6594        let attested =
6595            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6596        let mut caller = RouteOpenCaller::new(
6597            attested.as_ref().map(|attested| &attested.principal),
6598            scope.as_ref(),
6599            &identity,
6600        );
6601
6602        // A malformed declaration is refused first, before anything about the
6603        // target is looked up: the same body would be refused against any
6604        // module, so the caller learns nothing by retrying or waiting. An empty
6605        // map declares nothing and travels as no field at all, so a provider
6606        // only ever sees a missing field or a non-empty one.
6607        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6608        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6609            self.observe_route_open_refusal(
6610                ctx,
6611                &caller,
6612                &target_module_id,
6613                "invalid_role_versions",
6614                error_codes::INVALID_REQUEST,
6615            );
6616            return Ok(vec![control_error_body_frame(
6617                &frame,
6618                ErrorBody {
6619                    code: error_codes::INVALID_REQUEST.to_string(),
6620                    message: error.to_string(),
6621                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6622                },
6623            )?]);
6624        }
6625
6626        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6627            if status.waiting_for_previous_pid.is_some() {
6628                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6629                    ctx,
6630                    &caller,
6631                    &frame,
6632                    &target_module_id,
6633                    "module_warming",
6634                    &status,
6635                )?]);
6636            }
6637        }
6638
6639        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6640        // opposite. Below, a caller learns whether a module is unregistered,
6641        // supervised-but-down (with state/enabled/live), or registered without the
6642        // requested role. Elsewhere that is an enumeration leak: a probe learning
6643        // the shape of a fleet it cannot otherwise see.
6644        //
6645        // It is not one here, and the reason is the ACCESS MODEL rather than
6646        // anything about these errors. Reaching route.open requires the
6647        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6648        // connection file, so any caller who completes it already runs as this
6649        // user -- and can read subc.jsonc for the module list and `ck module
6650        // status` for live state. The reply discloses nothing the caller cannot
6651        // read more easily from disk, while the precision is load-bearing:
6652        // `unknown_module` is retryable and a missing role is not.
6653        //
6654        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6655        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6656        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6657        let admission_registry = self
6658            .registry
6659            .route_admission_snapshot()
6660            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6661        let Some(registration) =
6662            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6663        else {
6664            if let Some((status, warming)) =
6665                self.supervisor_status(&target_module_id, frame.header.corr)?
6666            {
6667                // BEFORE the two availability codes below, because for a module
6668                // that speaks no subc wire both of them are false comfort: they
6669                // say "not right now" and are retried, and this module will
6670                // never register no matter how long the caller waits. The
6671                // absence here is the declaration being honoured, not a module
6672                // that is late.
6673                if status.protocol == ModuleProtocol::None {
6674                    return Ok(vec![self.route_open_refusal_frame(
6675                        ctx,
6676                        &caller,
6677                        &frame,
6678                        &target_module_id,
6679                        "protocol_none",
6680                        error_codes::MODULE_NO_PROTOCOL,
6681                        format!(
6682                            "module_id '{target_module_id}' is declared protocol: none; \
6683                             it speaks no subc wire and serves no routes"
6684                        ),
6685                    )?]);
6686                }
6687                let code = if warming {
6688                    "module_warming"
6689                } else {
6690                    "target_unavailable"
6691                };
6692                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6693                    ctx,
6694                    &caller,
6695                    &frame,
6696                    &target_module_id,
6697                    code,
6698                    &status,
6699                )?]);
6700            }
6701            if let Some(removed_ago_ms) =
6702                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6703            {
6704                return Ok(vec![self.route_open_refusal_frame(
6705                    ctx,
6706                    &caller,
6707                    &frame,
6708                    &target_module_id,
6709                    "removed",
6710                    error_codes::MODULE_REMOVED,
6711                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6712                )?]);
6713            }
6714            return Ok(vec![self.route_open_refusal_frame(
6715                ctx,
6716                &caller,
6717                &frame,
6718                &target_module_id,
6719                "not_registered",
6720                error_codes::UNKNOWN_MODULE,
6721                format!("module_id '{target_module_id}' is not registered"),
6722            )?]);
6723        };
6724
6725        // Best-effort only: registry readiness and forwarding reservation use
6726        // different locks, so a module can flip readiness between this read and
6727        // the relay. Modules must still tolerate an `on_bind` while not ready.
6728        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6729            .is_err()
6730        {
6731            self.counters
6732                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6733            info!(
6734                target: "control",
6735                code = error_codes::MODULE_WARMING,
6736                module_id = ?target_module_id,
6737                connection_id = ctx.connection_id.get(),
6738                principal = %caller.principal,
6739                scope = %caller.scope,
6740                harness = %caller.harness,
6741                reason = "declared_not_ready",
6742                "route.open refused"
6743            );
6744            // The module is registered but says it cannot take work, which is
6745            // an outage from the caller's side even though its process is up.
6746            self.route_outages
6747                .record_not_serving(&target_module_id, "declared_not_ready");
6748            // The registered process can declare itself ready without a
6749            // restart, so an exhausted crash budget does not prevent serving.
6750            return Ok(vec![control_error_body_frame(
6751                &frame,
6752                ErrorBody {
6753                    code: error_codes::MODULE_WARMING.to_string(),
6754                    message: format!(
6755                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6756                    ),
6757                    detail: self.route_open_recovery_detail(
6758                        &target_module_id,
6759                        frame.header.corr,
6760                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6761                        Some(true),
6762                    )?,
6763                },
6764            )?]);
6765        }
6766
6767        // Effective readiness, second half: a module that declares a capability
6768        // `need: required` is not routable while that capability has no
6769        // registered provider. It is enforced HERE, as a retryable routing
6770        // refusal, and deliberately not as spawn ordering or a boot block. The
6771        // module is still started and registered and can make its own calls;
6772        // spawn ordering is a promise that cannot be kept once a provider
6773        // crashes at runtime, and refusing to boot would stop the whole
6774        // machine, including the tools needed to fix its configuration.
6775        //
6776        // "Provided" is the evaluator's verdict, which counts a provider as
6777        // soon as it has REGISTERED, not once it is ready. Two modules that
6778        // require each other's capabilities are therefore both routable once
6779        // both register; counting readiness instead would deadlock them.
6780        //
6781        // Only new opens are refused. Routes already bound when a provider
6782        // goes away stay bound: nothing here tears them down, and the module
6783        // answers them as it can. Like the readiness read above this is
6784        // best-effort against a provider registering or leaving concurrently.
6785        if let Some(capability) = self.first_unprovided_required_capability_for(
6786            &registration.module_id,
6787            registration.capabilities.as_ref(),
6788        ) {
6789            self.counters
6790                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6791            info!(
6792                target: "control",
6793                code = error_codes::MODULE_WARMING,
6794                module_id = ?target_module_id,
6795                connection_id = ctx.connection_id.get(),
6796                principal = %caller.principal,
6797                scope = %caller.scope,
6798                harness = %caller.harness,
6799                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6800                capability = %capability,
6801                "route.open refused"
6802            );
6803            return Ok(vec![control_error_body_frame(
6804                &frame,
6805                ErrorBody {
6806                    code: error_codes::MODULE_WARMING.to_string(),
6807                    message: format!(
6808                        "module_id '{target_module_id}' requires capability '{capability}', \
6809                         which no registered module provides; retry"
6810                    ),
6811                    detail: Some(serde_json::json!({
6812                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6813                        "capability": capability,
6814                    })),
6815                },
6816            )?]);
6817        }
6818
6819        if !target_has_required_role(&target, &registration.roles) {
6820            return Ok(vec![self.route_open_refusal_frame(
6821                ctx,
6822                &caller,
6823                &frame,
6824                &target_module_id,
6825                "role_not_provided",
6826                "target_unavailable",
6827                format!("module_id '{target_module_id}' does not provide the requested target"),
6828            )?]);
6829        }
6830
6831        if registration.state != ChannelState::Active {
6832            return Ok(vec![self.route_open_refusal_frame(
6833                ctx,
6834                &caller,
6835                &frame,
6836                &target_module_id,
6837                "registration_not_active",
6838                "target_unavailable",
6839                format!("module_id '{target_module_id}' is not active"),
6840            )?]);
6841        }
6842
6843        if self
6844            .forwarding
6845            .module_is_draining(&target_module_id)
6846            .map_err(RouterError::Forwarding)?
6847        {
6848            return Ok(vec![self.route_open_refusal_frame(
6849                ctx,
6850                &caller,
6851                &frame,
6852                &target_module_id,
6853                "reloading",
6854                "module_reloading",
6855                format!("module_id '{target_module_id}' is reloading"),
6856            )?]);
6857        }
6858
6859        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6860            process_liveness.process_live(&target_module_id) == Some(false)
6861        }) {
6862            // A module the supervisor is restarting or reloading can still hold
6863            // a registration: the old process before its connection closes, or
6864            // a new one that registered while the supervisor was draining. The
6865            // forwarding table does not see that as draining, but the consumer
6866            // should still be told to retry soon, exactly as for the drain
6867            // above, rather than that the target is unavailable.
6868            if process_liveness.process_replacing(&target_module_id) {
6869                return Ok(vec![self.route_open_refusal_frame(
6870                    ctx,
6871                    &caller,
6872                    &frame,
6873                    &target_module_id,
6874                    "reloading",
6875                    "module_reloading",
6876                    format!("module_id '{target_module_id}' is reloading"),
6877                )?]);
6878            }
6879            return Ok(vec![self.route_open_refusal_frame(
6880                ctx,
6881                &caller,
6882                &frame,
6883                &target_module_id,
6884                "supervisor_not_live",
6885                "target_unavailable",
6886                format!("module_id '{target_module_id}' is not live"),
6887            )?]);
6888        }
6889
6890        if !self
6891            .forwarding
6892            .has_live_module_connection(&target_module_id)
6893            .map_err(RouterError::Forwarding)?
6894        {
6895            return Ok(vec![self.route_open_refusal_frame(
6896                ctx,
6897                &caller,
6898                &frame,
6899                &target_module_id,
6900                "no_forwarding_connection",
6901                "target_unavailable",
6902                format!("module_id '{target_module_id}' has no live forwarding connection"),
6903            )?]);
6904        }
6905
6906        if let Some(error) =
6907            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6908        {
6909            self.observe_route_open_refusal(
6910                ctx,
6911                &caller,
6912                &target_module_id,
6913                "op_not_allowed",
6914                "op_not_allowed",
6915            );
6916            return Ok(vec![error]);
6917        }
6918
6919        let principal = match (&attested, consumer_identity.is_some()) {
6920            // A claim-bound connection whose launch ended attests nothing,
6921            // and it must never fall back to opening as `direct`.
6922            (None, false) => {
6923                self.observe_route_open_refusal(
6924                    ctx,
6925                    &caller,
6926                    &target_module_id,
6927                    "registration_channel_closed",
6928                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6929                );
6930                return Ok(vec![control_error_frame(
6931                    &frame,
6932                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6933                    "the claim binding's launch has ended",
6934                )?]);
6935            }
6936            _ => match self.route_open_principal_attested(
6937                &frame,
6938                consumer_identity,
6939                attested.as_ref().map(|attested| attested.principal.clone()),
6940            )? {
6941                Ok(principal) => principal,
6942                Err(error) => {
6943                    self.observe_route_open_refusal(
6944                        ctx,
6945                        &caller,
6946                        &target_module_id,
6947                        "bad_consumer_identity",
6948                        "bad_consumer_identity",
6949                    );
6950                    return Ok(vec![error]);
6951                }
6952            },
6953        };
6954        let attested = attested.expect("an attested principal was resolved above");
6955        timings.principal = principal_label(&principal);
6956
6957        // The opener's spawn authority, read once here and carried with the
6958        // relay; nothing below reads its record again.
6959        let Ok(mut caller_capture) = attested.capture() else {
6960            self.observe_route_open_refusal(
6961                ctx,
6962                &caller,
6963                &target_module_id,
6964                "registration_channel_closed",
6965                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6966            );
6967            return Ok(vec![control_error_frame(
6968                &frame,
6969                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6970                "the opener's launch has ended",
6971            )?]);
6972        };
6973        // The caller-side checks below read the opener's own spawn: its
6974        // module from its record and its manifest from its own registration,
6975        // never another launch's active registration under the same id.
6976        let caller_module_id = match &attested.spawn {
6977            Some((record, _)) => Some(record.module_id().to_owned()),
6978            None => match &principal {
6979                Principal::Reserved { module_id } => Some(module_id.clone()),
6980                _ => None,
6981            },
6982        };
6983
6984        // Only Callosum can attest a production phone build. Consume the raw
6985        // claim here; opted-in targets receive only the honoured peer fact.
6986        let build_class = identity.build_class.take().filter(|build_class| {
6987            if caller_module_id.as_deref() == Some("callosum") {
6988                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6989            } else {
6990                if self
6991                    .build_class_warned
6992                    .lock()
6993                    .unwrap_or_else(|p| p.into_inner())
6994                    .insert(ctx.connection_id)
6995                {
6996                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6997                        "ignoring build_class from a non-Callosum opener");
6998                }
6999                false
7000            }
7001        });
7002
7003        // This is attested, control-plane policy for supervised module origins.
7004        // Keep it before route reservation and out of the opaque forwarding hot
7005        // path: data frames must never acquire a per-frame capability check.
7006        if let Some(opening_registration) = self.caller_registration(&attested, &admission_registry)
7007        {
7008            let opening_module_id = opening_registration.module_id.as_str();
7009            if let Some(capability) = denied_capability(
7010                opening_registration.capabilities.as_ref(),
7011                registration.capabilities.as_ref(),
7012            ) {
7013                warn!(
7014                    opening_module_id,
7015                    target_module_id,
7016                    capability,
7017                    "refusing route.open because an attested capability deny edge matches"
7018                );
7019                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
7020                    &frame,
7021                    &target_module_id,
7022                    "capability_deny_edge",
7023                    "capability_forbidden",
7024                    format!(
7025                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
7026                    ),
7027                )?]);
7028            }
7029        }
7030
7031        if admission_facts.is_some() {
7032            let carrier_matches = caller_module_id.is_some()
7033                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
7034            if !carrier_matches {
7035                return Ok(vec![self.route_open_refusal_frame(
7036                    ctx,
7037                    &caller,
7038                    &frame,
7039                    &target_module_id,
7040                    "admission_facts_carrier_not_permitted",
7041                    "admission_facts_not_permitted",
7042                    "admission facts may only be carried by the configured reserved module",
7043                )?]);
7044            }
7045
7046            let target_allowed = self
7047                .admission_facts_targets
7048                .as_ref()
7049                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
7050            if !target_allowed {
7051                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
7052                    &frame,
7053                    &target_module_id,
7054                    "admission_facts_target_not_listed",
7055                    "admission_facts_target_not_allowed",
7056                    format!(
7057                        "admission facts are not permitted for target module_id '{target_module_id}'"
7058                    ),
7059                )?]);
7060            }
7061
7062            // Keep the value opaque to subc. The downstream admission validator owns
7063            // schema and semantic checks; this daemon only enforces carrier authority
7064            // and the configured destination allowlist.
7065        }
7066
7067        // Scope admission, on the attested principal above and never on the
7068        // request body. The tag read here travels with the pending bind and is
7069        // compared with the published one at commit, so a sync between here
7070        // and the module's ack refuses the open instead of binding a stamp
7071        // that is no longer true.
7072        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
7073            None => (None, None, false),
7074            Some(selector) => {
7075                let owner_configured = match &selector.owner {
7076                    // A reserved owner counts as configured from before its
7077                    // process is spawned (see `SupervisorHandle::is_configured`).
7078                    // So an owner that has not synced its scopes yet is refused
7079                    // as retryable (`scope_not_synced`), not as one that will
7080                    // never sync.
7081                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
7082                    _ => false,
7083                };
7084                let mut scopes = self
7085                    .scopes
7086                    .write()
7087                    .unwrap_or_else(|poisoned| poisoned.into_inner());
7088                let admitted = crate::scopes::admission::admit_route(
7089                    &scopes,
7090                    &admission_registry,
7091                    &principal,
7092                    &target_module_id,
7093                    Some(selector),
7094                    owner_configured,
7095                    crate::scopes::admission::AdmissionMode::Open,
7096                )
7097                .map(|route| {
7098                    let admission = route.scope.expect("scoped admission");
7099                    let bound = scopes.reserve_bind(
7100                        &admission,
7101                        &principal,
7102                        ctx.connection_id,
7103                        selector.hold_presence,
7104                    );
7105                    (admission, bound)
7106                });
7107                match admitted {
7108                    Ok((admission, bound)) => {
7109                        (Some(bound), Some(admission.stamp), admission.stamp_required)
7110                    }
7111                    Err(refusal) => {
7112                        return Ok(vec![self.route_open_refusal_frame(
7113                            ctx,
7114                            &caller,
7115                            &frame,
7116                            &target_module_id,
7117                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
7118                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
7119                            refusal.message,
7120                        )?]);
7121                    }
7122                }
7123            }
7124        };
7125        // From here on a refusal names the scope by the stamp admission
7126        // issued, exactly as the `route.open accepted` line does.
7127        if let Some(stamp) = &scope_stamp {
7128            caller.scope = route_open_scope_label(stamp);
7129        }
7130        // Decided from the admitted stamp, before any field of it is stripped
7131        // for a target that lacks the capability to read it.
7132        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
7133            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
7134        }
7135
7136        // Allow resolvable missing-tail paths so a vanished directory does not
7137        // prevent reopening an existing session for cleanup. Binding does not
7138        // authorize creation of durable provider state.
7139        //
7140        // Resolve real paths rather than lexical cleanup: canonicalize the
7141        // longest existing ancestor and append the missing tail, retaining the
7142        // path's real existing ancestry even when a leaf is missing.
7143        timings.enter(RouteOpenPhase::ProjectRoot);
7144        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
7145            Ok(project) => project,
7146            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
7147        };
7148        timings.enter(RouteOpenPhase::Admission);
7149        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
7150            Ok(root) => root,
7151            Err(err) => {
7152                return Ok(vec![control_error_frame(
7153                    &frame,
7154                    "invalid_project_root",
7155                    err.to_string(),
7156                )?])
7157            }
7158        };
7159        // Compute compatibility project fields before stripping optional stamp
7160        // members. Preserve the canonical opener root and its project ID,
7161        // including absence. For rootless openers, use stamp workdir or `/`, and
7162        // opener ID, else stamp ID, else no ID. Emit these identity fields only
7163        // to targets without bind-no-project/v1.
7164        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
7165
7166        // Last gate before any relay work, and deliberately after the cheap
7167        // registry and availability checks above: those name a more precise
7168        // condition (unknown, removed, reloading) and a caller is better served
7169        // by the precise code than by this one.
7170        //
7171        // Everything below this point costs an egress permit, a reserved handle
7172        // pair and, if the module does not answer, the whole relay budget. The
7173        // reader no longer waits for that budget, so cap each target explicitly;
7174        // serial dispatch used to provide the accidental cap of one relay per
7175        // connection. Admission is a mutex-protected count and never waits.
7176        let _concurrency_guard = match self
7177            .route_bind_concurrency
7178            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
7179        {
7180            Ok(guard) => guard,
7181            Err(in_flight) => {
7182                return Ok(vec![self.route_open_target_capacity_refusal(
7183                    ctx,
7184                    &caller,
7185                    &frame,
7186                    &target_module_id,
7187                    in_flight,
7188                )?]);
7189            }
7190        };
7191
7192        // A module that has already burned the whole budget `threshold` times
7193        // in a row does not get to charge it again until a probe says it recovered.
7194        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
7195            RouteBindAdmission::Admitted { guard, probe } => {
7196                if probe {
7197                    info!(
7198                        module_id = %target_module_id,
7199                        connection_id = ctx.connection_id.get(),
7200                        "route.bind breaker half-open: admitting one probe"
7201                    );
7202                }
7203                guard
7204            }
7205            RouteBindAdmission::Refused {
7206                consecutive_timeouts,
7207                retry_in,
7208                probe_in_flight,
7209            } => {
7210                return Ok(vec![self.route_open_breaker_refusal_frame(
7211                    ctx,
7212                    &caller,
7213                    &frame,
7214                    &target_module_id,
7215                    consecutive_timeouts,
7216                    retry_in,
7217                    probe_in_flight,
7218                )?]);
7219            }
7220        };
7221
7222        // Resolve the per-module budget here so the wait matches the operator's
7223        // intent for this specific target. A per-module override in
7224        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
7225        // daemons) wins over the daemon-wide default.
7226        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
7227        let relay_deadline = Instant::now() + route_bind_relay_timeout;
7228        let operator_app = self
7229            .operator_apps
7230            .lock()
7231            .unwrap_or_else(|p| p.into_inner())
7232            .get(&ctx.connection_id)
7233            .cloned();
7234        let production_peer_build =
7235            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
7236        timings.enter(RouteOpenPhase::EgressReservation);
7237        let pending = match self
7238            .forwarding
7239            .begin_route_bind_relay_for(
7240                ctx.connection_id,
7241                ctx.egress.clone(),
7242                response_version(&frame),
7243                frame.header.corr,
7244                &target_module_id,
7245                principal.clone(),
7246                bound_scope,
7247                project_root,
7248                identity.harness.clone(),
7249                build_class,
7250                operator_app.clone(),
7251                crate::forwarding::RouteAuthority {
7252                    incarnation: self.supervisor.daemon_incarnation(),
7253                    caller: caller_capture
7254                        .as_ref()
7255                        .map(|caller| caller.authority.pair()),
7256                },
7257                relay_deadline,
7258                busy_refusals == Some(true),
7259                accepts_close_reasons,
7260            )
7261            .await
7262        {
7263            Ok(pending) => pending,
7264            Err(err) => {
7265                return Ok(vec![self.route_open_refusal_frame(
7266                    ctx,
7267                    &caller,
7268                    &frame,
7269                    &target_module_id,
7270                    "relay_reservation_failed",
7271                    forwarding_error_code(&err),
7272                    err.to_string(),
7273                )?])
7274            }
7275        };
7276        timings.enter(RouteOpenPhase::Admission);
7277        let crate::forwarding::PendingRouteBindRelay {
7278            endpoint,
7279            module_sink,
7280            negotiated_ver,
7281            client_channel,
7282            client_epoch,
7283            module_channel,
7284            module_epoch,
7285            corr: relay_corr,
7286            receiver,
7287        } = pending;
7288        let mut reservation =
7289            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
7290
7291        // Reserving egress can wait while a module reconnects or a swap cuts
7292        // over. Check the relay's captured connection, not the earlier by-id
7293        // lookup: the original module's flow/run capabilities cannot authorize
7294        // its replacement. The captured sink stays bound to that connection.
7295        let relay_registration = self
7296            .registry
7297            .route_registration_by_connection(endpoint.connection_id)
7298            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7299        let relay_capabilities = relay_registration
7300            .as_ref()
7301            .and_then(|registration| registration.capabilities.as_ref());
7302        if let Some(selector) = &scope {
7303            // Egress reservation may wait across a scope update. Recheck the
7304            // proof against the current record before sending the captured bind.
7305            if let Err(refusal) = self
7306                .scopes
7307                .read()
7308                .unwrap_or_else(|poisoned| poisoned.into_inner())
7309                .check_bind_proof(&principal, selector)
7310            {
7311                reservation.release_and_disarm();
7312                return Ok(vec![self.route_open_refusal_frame(
7313                    ctx,
7314                    &caller,
7315                    &frame,
7316                    &target_module_id,
7317                    refusal.code,
7318                    refusal.code,
7319                    refusal.message,
7320                )?]);
7321            }
7322        }
7323        if let Some(stamp) = scope_stamp.as_ref() {
7324            if let Err(refusal) = crate::scopes::check_target_required_stamp(
7325                stamp_required,
7326                &target_module_id,
7327                relay_capabilities,
7328            )
7329            .and_then(|()| {
7330                crate::scopes::check_target_flow_support(
7331                    stamp,
7332                    &target_module_id,
7333                    relay_capabilities,
7334                )
7335            })
7336            .and_then(|()| {
7337                crate::scopes::check_target_agent_run_support(
7338                    stamp,
7339                    &target_module_id,
7340                    relay_capabilities,
7341                )
7342            }) {
7343                reservation.release_and_disarm();
7344                return Ok(vec![self.route_open_refusal_frame(
7345                    ctx,
7346                    &caller,
7347                    &frame,
7348                    &target_module_id,
7349                    refusal.code,
7350                    refusal.code,
7351                    refusal.message,
7352                )?]);
7353            }
7354        }
7355
7356        // Older readers may reject unknown fields. Select optional fields from
7357        // the captured endpoint's declaration, including on unscoped binds.
7358        if scope_stamp
7359            .as_ref()
7360            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7361            && !crate::scopes::target_supports_federated(relay_capabilities)
7362        {
7363            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7364            scope_stamp = None;
7365        }
7366        if !relay_capabilities.is_some_and(|caps| {
7367            caps.provides
7368                .iter()
7369                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7370        }) {
7371            if let Some(stamp) = scope_stamp.as_mut() {
7372                stamp.workdir = None;
7373                stamp.project_id = None;
7374            }
7375        }
7376        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7377        // attribution. The run gate above has already required the target to
7378        // declare `worker-runs/v1`, which promises to read both
7379        // `on_behalf_of_agent` and `call_mode`.
7380        let worker_run = scope_stamp
7381            .as_ref()
7382            .is_some_and(crate::scopes::is_worker_run)
7383            && relay_capabilities.is_some_and(|caps| {
7384                caps.provides
7385                    .iter()
7386                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7387            });
7388        if !worker_run
7389            && !relay_capabilities.is_some_and(|caps| {
7390                caps.provides
7391                    .iter()
7392                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7393            })
7394        {
7395            if let Some(stamp) = scope_stamp.as_mut() {
7396                stamp.attributes.on_behalf_of_agent = None;
7397            }
7398        }
7399        if !relay_capabilities.is_some_and(|caps| {
7400            caps.provides
7401                .iter()
7402                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7403        }) {
7404            if let Some(stamp) = scope_stamp.as_mut() {
7405                stamp.attributes.flow_version = None;
7406                stamp.attributes.flow_code_hash = None;
7407                stamp.attributes.flow_install_id = None;
7408            }
7409        }
7410        let call_mode = if worker_run
7411            || relay_capabilities
7412                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7413        {
7414            Some(derive_call_mode(scope_stamp.as_ref()))
7415        } else {
7416            if let Some(stamp) = scope_stamp.as_mut() {
7417                stamp.expires_at_ms = None;
7418            }
7419            None
7420        };
7421
7422        debug!(
7423            connection_id = ctx.connection_id.get(),
7424            client_channel,
7425            client_epoch,
7426            module_channel,
7427            module_epoch,
7428            "reserved route handle pair"
7429        );
7430        // Rendered BEFORE the move into the relay, because the accept arm below
7431        // is where it is logged and the principal is gone by then.
7432        let route_principal_label = principal_label(&principal);
7433        let relay = ModuleControlRequest::RouteBind {
7434            route_channel: module_channel,
7435            epoch: module_epoch,
7436            target,
7437            identity,
7438            principal: Some(principal),
7439            consumer_capabilities,
7440            role_versions,
7441            admission_facts,
7442            scope: scope_stamp,
7443            call_mode,
7444        };
7445        let peer = RouteBindPeer::new()
7446            .with_observed_peer(
7447                relay_capabilities
7448                    .is_some_and(|caps| {
7449                        caps.provides
7450                            .iter()
7451                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7452                    })
7453                    .then(|| {
7454                        self.observed_peers
7455                            .lock()
7456                            .unwrap_or_else(|p| p.into_inner())
7457                            .get(&ctx.connection_id)
7458                            .cloned()
7459                            .unwrap_or_else(ObservedPeer::unobserved)
7460                    }),
7461            )
7462            .with_operator_app(
7463                self.connection_operator_app(operator_app.as_ref())
7464                    .filter(|_| {
7465                        relay_capabilities.is_some_and(|caps| {
7466                            caps.provides
7467                                .iter()
7468                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7469                        })
7470                    }),
7471            )
7472            .with_caller(caller_for_target(
7473                caller_capture.as_ref(),
7474                relay_capabilities,
7475                &target_module_id,
7476            ))
7477            .with_peer_build(
7478                (production_peer_build
7479                    && relay_capabilities.is_some_and(|caps| {
7480                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7481                    }))
7482                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7483            );
7484        let relay_body = crate::bind_compat::encode_bind(
7485            &relay,
7486            &peer,
7487            &legacy_bind_project,
7488            relay_capabilities,
7489        )
7490        .map_err(|err| {
7491            RouterError::backend(
7492                0,
7493                frame.header.corr,
7494                format!("failed to encode route.bind request: {err}"),
7495            )
7496        })?;
7497        let relay_frame = Frame::build_with_version(
7498            negotiated_ver,
7499            FrameType::Request,
7500            control_flags(),
7501            0,
7502            0,
7503            relay_corr,
7504            relay_body,
7505        )
7506        .map_err(RouterError::FrameBuild)?;
7507
7508        timings.enter(RouteOpenPhase::BindSend);
7509        let sent = module_sink.send(relay_frame).await;
7510        timings.enter(RouteOpenPhase::Admission);
7511        if let Err(err) = sent {
7512            reservation.release_and_disarm();
7513            return Ok(vec![self.route_open_refusal_frame(
7514                ctx,
7515                &caller,
7516                &frame,
7517                &target_module_id,
7518                "relay_send_failed",
7519                "target_unavailable",
7520                err.to_string(),
7521            )?]);
7522        }
7523
7524        #[cfg(test)]
7525        if let Some(hold) = &self.route_bind_relay_sent_hold {
7526            // First wait: tell the test the bind is queued. Second wait: stay
7527            // here until the test has driven whatever it wants to happen
7528            // between queueing the bind and marking it enqueued.
7529            hold.wait().await;
7530            hold.wait().await;
7531        }
7532
7533        // A missing relay is not by itself an abandoned bind: the module may
7534        // already have acked it and the route may be committed. Only a relay
7535        // dropped without any module reply needs this GOODBYE; one a reply
7536        // settled has already had its GOODBYE decided by the reply path.
7537        if self
7538            .forwarding
7539            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7540            .map_err(RouterError::Forwarding)?
7541            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7542        {
7543            self.send_abandoned_route_bind_goodbye(
7544                &module_sink,
7545                negotiated_ver,
7546                module_channel,
7547                module_epoch,
7548            );
7549        }
7550
7551        timings.enter(RouteOpenPhase::BindAckWait);
7552        let outcome = timeout_at(relay_deadline, receiver).await;
7553        timings.enter(RouteOpenPhase::Admission);
7554        match outcome {
7555            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7556                reservation.disarm();
7557                if breaker.record_accepted() {
7558                    info!(
7559                        module_id = %target_module_id,
7560                        "route.bind breaker closed: the probe was accepted"
7561                    );
7562                }
7563                self.observe_route_open_accept(
7564                    ctx,
7565                    &target_module_id,
7566                    &route_principal_label,
7567                    &caller.scope,
7568                );
7569                Ok(Vec::new())
7570            }
7571            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7572                reservation.release_and_disarm();
7573                // A module that says no in microseconds is healthy. Rejection
7574                // is a different condition with its own refusal and must not
7575                // move the breaker.
7576                breaker.record_inconclusive();
7577                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7578            }
7579            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7580                reservation.release_and_disarm();
7581                breaker.record_inconclusive();
7582                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7583            }
7584            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7585                reservation.release_and_disarm();
7586                breaker.record_inconclusive();
7587                // Fires when the module's connection closes while a relayed
7588                // bind is pending -- typically a caller racing a module restart
7589                // whose bind was relayed BEFORE the drain mark went up. Logged
7590                // because the caller sees only its own error and the fleet has
7591                // already spent one diagnosis round unable to tell this arm
7592                // from a relay timeout without daemon-side evidence.
7593                tracing::warn!(
7594                    module_id = %target_module_id,
7595                    "route.bind relay abandoned: {message}"
7596                );
7597                Ok(vec![self.route_open_refusal_frame(
7598                    ctx,
7599                    &caller,
7600                    &frame,
7601                    &target_module_id,
7602                    "relay_abandoned",
7603                    "target_unavailable",
7604                    message,
7605                )?])
7606            }
7607            Ok(Err(_)) => {
7608                reservation.release_and_disarm();
7609                breaker.record_inconclusive();
7610                Ok(vec![self.route_open_refusal_frame(
7611                    ctx,
7612                    &caller,
7613                    &frame,
7614                    &target_module_id,
7615                    "relay_waiter_canceled",
7616                    "target_unavailable",
7617                    "route.bind relay waiter was canceled before the module responded",
7618                )?])
7619            }
7620            Err(_) => {
7621                reservation.release_and_disarm();
7622                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7623                // answer at all is the one condition a fast refusal can
7624                // usefully stand in for; every other arm already answered.
7625                if let Some(opened) = breaker.record_timeout(
7626                    self.route_bind_breaker_threshold,
7627                    self.route_bind_breaker_cooldown,
7628                ) {
7629                    warn!(
7630                        module_id = %target_module_id,
7631                        consecutive_timeouts = opened.consecutive_timeouts,
7632                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7633                        reopened_after_probe = opened.reopened_after_probe,
7634                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7635                    );
7636                }
7637                // The generous budget just burned to no answer: the module is
7638                // registered and its connection is up, but its bind handler sat
7639                // on the ack for the full budget (warm-on-bind, cold configure,
7640                // or a wedged handler). Every earlier unavailability shape
7641                // fast-refuses BEFORE the relay, so this arm firing means the
7642                // slowness is module-side -- log it so the per-module timeline
7643                // is reconstructable without client audit rows.
7644                tracing::warn!(
7645                    module_id = %target_module_id,
7646                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7647                    "route.bind relay timed out: module did not ack within budget"
7648                );
7649                Ok(vec![self.route_open_refusal_frame(
7650                    ctx,
7651                    &caller,
7652                    &frame,
7653                    &target_module_id,
7654                    "relay_timed_out",
7655                    "module_timeout",
7656                    format!(
7657                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7658                        route_bind_relay_timeout
7659                    ),
7660                )?])
7661            }
7662        }
7663    }
7664
7665    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7666        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7667            snapshot: self.supervisor.spawn_snapshot(),
7668        };
7669        Ok(vec![control_response_body_frame(
7670            &frame,
7671            &response,
7672            "ClientControlResponse::SupervisorSpawnSnapshot",
7673        )?])
7674    }
7675
7676    fn handle_supervisor_spawn_subscribe(
7677        &self,
7678        ctx: &RouteCtx,
7679        frame: Frame,
7680        since: Option<SpawnCursor>,
7681    ) -> Result<Vec<Frame>, RouterError> {
7682        match self.supervisor.subscribe_spawns(
7683            ctx.connection_id,
7684            frame.header.corr,
7685            response_version(&frame),
7686            since,
7687            ctx.egress.clone(),
7688        ) {
7689            Ok(()) => Ok(Vec::new()),
7690            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7691                Ok(vec![control_error_body_frame(
7692                    &frame,
7693                    ErrorBody {
7694                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7695                        message: "spawn cursor belongs to a different daemon incarnation"
7696                            .to_string(),
7697                        detail: Some(serde_json::json!({
7698                            "current_daemon_incarnation": current
7699                        })),
7700                    },
7701                )?])
7702            }
7703            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7704                &frame,
7705                ErrorBody {
7706                    code: "spawn_cursor_too_old".to_string(),
7707                    message: "spawn cursor predates the retained event ring".to_string(),
7708                    detail: Some(serde_json::json!({
7709                        "oldest_retained_cursor": oldest
7710                    })),
7711                },
7712            )?]),
7713            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7714                0,
7715                frame.header.corr,
7716                format!("failed to open supervisor spawn subscription: {error}"),
7717            )),
7718        }
7719    }
7720
7721    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7722        // Status/configuration snapshots may wait on synchronous supervisor
7723        // locks. Keep that work off the connection's async runtime thread.
7724        let handler = self.clone();
7725        let runtime = tokio::runtime::Handle::current();
7726        // The blocking pool does not inherit the control request's tracing
7727        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7728        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7729        let corr = frame.header.corr;
7730        tokio::task::spawn_blocking(move || {
7731            runtime.block_on(
7732                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7733                    .with_subscriber(subscriber),
7734            )
7735        })
7736        .await
7737        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7738    }
7739
7740    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7741        use crate::config_gate::runtime::ApprovedDaemonView;
7742        let publication = self
7743            .config_runtime
7744            .as_ref()
7745            .and_then(|owner| owner.polled_snapshot().ok());
7746        let approved = publication
7747            .as_ref()
7748            .map(|view| view.approved_daemon.clone())
7749            .unwrap_or_else(|| {
7750                if self.config_runtime.is_some() {
7751                    ApprovedDaemonView::Unavailable
7752                } else {
7753                    ApprovedDaemonView::NotStamped
7754                }
7755            });
7756        let generation = self
7757            .registry
7758            .generation()
7759            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7760        let supervised = self.supervisor.list();
7761        let mut statuses = BTreeMap::new();
7762        let mut not_running = BTreeSet::new();
7763        for module in &supervised {
7764            let status = module.status_for_control("list").map_err(|err| {
7765                RouterError::backend(
7766                    0,
7767                    frame.header.corr,
7768                    format!("failed to read supervisor status: {err}"),
7769                )
7770            })?;
7771            if !status.enabled || !status.process_alive {
7772                not_running.insert(module.module_id().to_owned());
7773            }
7774            statuses.insert(module.module_id().to_owned(), status);
7775        }
7776        // Legacy per-process diagnostics keep their shared optional budget.
7777        // The cached tree and accounting export below does not spend it.
7778        let mut process_resources = BTreeMap::new();
7779        for module in &supervised {
7780            process_resources.insert(
7781                module.module_id().to_owned(),
7782                crate::subtree_resources::read_process(module.clone()).await,
7783            );
7784        }
7785        // Image evidence uses the same optional deadline, but an exhausted
7786        // budget must not suppress the committed resource view.
7787        let mut image_readings = BTreeMap::new();
7788        for module in &supervised {
7789            image_readings.insert(
7790                module.module_id().to_owned(),
7791                module.running_image_agreement().await,
7792            );
7793        }
7794        let readings = self.resource_tracker.list(supervised.clone());
7795        let mut modules = Vec::new();
7796        for module in supervised {
7797            let status = statuses
7798                .remove(module.module_id())
7799                .expect("each supervised module has a status snapshot");
7800            let (configured, _) = module.configuration().map_err(|err| {
7801                RouterError::backend(
7802                    0,
7803                    frame.header.corr,
7804                    format!("failed to read module configuration: {err}"),
7805                )
7806            })?;
7807            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7808                RouterError::backend(
7809                    0,
7810                    frame.header.corr,
7811                    format!("failed to read retry time: {err}"),
7812                )
7813            })?;
7814            let image = image_readings
7815                .remove(module.module_id())
7816                .expect("each supervised module has an image snapshot");
7817            let resources = process_resources.remove(module.module_id());
7818            let mut verdict =
7819                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7820            verdict.spec = Some(launch_spec_agreement(
7821                &configured,
7822                status.process_alive,
7823                status.launch_spec_digest.as_ref(),
7824            ));
7825            let pending_reload = Some(verdict);
7826            let pending_entry = match &approved {
7827                ApprovedDaemonView::Approved { config, .. } => config
7828                    .modules
7829                    .iter()
7830                    .find(|m| m.module_id == module.module_id()),
7831                _ => None,
7832            };
7833            let pending = self
7834                .pending_module_fields(
7835                    &module,
7836                    pending_entry,
7837                    false,
7838                    Self::registration_channel_in_force(
7839                        publication
7840                            .as_ref()
7841                            .and_then(|view| view.registration_declaration(module.module_id()))
7842                            .as_deref(),
7843                        pending_entry.map(|entry| entry.registration_channel),
7844                    ),
7845                )
7846                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7847            let script = configured.script.as_ref().map(|entry| {
7848                let approved = self
7849                    .config_runtime
7850                    .as_ref()
7851                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7852                crate::supervise::script::status(entry, approved.as_ref())
7853            });
7854            let configured_enabled = match &approved {
7855                ApprovedDaemonView::Approved {
7856                    config: approved, ..
7857                } => approved
7858                    .modules
7859                    .iter()
7860                    .find(|module| module.module_id == status.module_id)
7861                    .map(|module| module.enabled),
7862                ApprovedDaemonView::NotStamped => self
7863                    .capability_evaluator
7864                    .configured_enabled(&status.module_id),
7865                ApprovedDaemonView::Unavailable => None,
7866            };
7867            let admission_refused = status
7868                .admission_refused
7869                .clone()
7870                .filter(|_| status.enabled && !status.process_alive)
7871                .filter(|_| {
7872                    publication
7873                        .as_ref()
7874                        .and_then(|view| view.registration_declaration(&status.module_id))
7875                        .as_deref()
7876                        == Some("undeclared")
7877                });
7878            // Keep the retired policy field on the wire for one release so
7879            // existing status consumers still receive the platform policy.
7880            let mut entry = SupervisorEntry::new(
7881                status.module_id,
7882                status.state.to_string(),
7883                status.enabled,
7884                status.live,
7885                status.health.status,
7886            )
7887            .with_configured_enabled(configured_enabled)
7888            .with_script(script)
7889            .with_admission_refused(admission_refused)
7890            .with_next_retry_at_ms(next_retry_at_ms)
7891            .with_launch_nonce_env(Some(!cfg!(unix)))
7892            .with_launch_nonce_source(status.launch_nonce_source)
7893            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7894            .with_protocol(status.protocol)
7895            .with_pending_reload(pending_reload)
7896            .with_last_probe_ms(status.health.last_probe_ms)
7897            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7898            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7899            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7900            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7901            .with_restart_count(Some(status.restart_count))
7902            .with_max_restarts(Some(status.max_restarts))
7903            .with_lifetime_restarts(Some(status.lifetime_restarts))
7904            .with_spawn_generation(Some(status.spawn_generation))
7905            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7906            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7907            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7908            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7909            .with_resources(resources);
7910            entry.pending = pending;
7911            modules.push(entry);
7912        }
7913        for module in &mut modules {
7914            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7915                module.tree = tree.clone();
7916                module.cpu_last_hour = hour.clone();
7917            }
7918            module.tree_unavailable = readings
7919                .reasons
7920                .get(&module.module_id)
7921                .map(|reason| (*reason).to_owned());
7922            if module.tree.is_none() {
7923                module.tree_unavailable = Some(
7924                    if not_running.contains(&module.module_id) {
7925                        "not_running"
7926                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7927                        reason
7928                    } else {
7929                        "not_yet_measured"
7930                    }
7931                    .to_owned(),
7932                );
7933            }
7934        }
7935        let response = ClientControlResponse::SupervisorList {
7936            generation,
7937            modules,
7938            daemon: readings.daemon,
7939            agent_commands: readings.agent_commands,
7940        };
7941        Ok(vec![control_response_body_frame(
7942            &frame,
7943            &response,
7944            "ClientControlResponse::SupervisorList",
7945        )?])
7946    }
7947
7948    fn handle_supervisor_stderr_tail(
7949        &self,
7950        frame: Frame,
7951        module_id: String,
7952        max_lines: Option<u32>,
7953        max_bytes: Option<u32>,
7954    ) -> Result<Vec<Frame>, RouterError> {
7955        let Some(module) = self.supervisor.get(&module_id) else {
7956            return Ok(vec![control_error_frame(
7957                &frame,
7958                "unknown_module",
7959                format!("module_id '{module_id}' is not supervised"),
7960            )?]);
7961        };
7962
7963        let snapshot = module.stderr_tail(
7964            max_lines.map(|value| value as usize),
7965            max_bytes.map(|value| value as usize),
7966        );
7967
7968        let response = ClientControlResponse::SupervisorStderrTail {
7969            module_id,
7970            tail: StderrTail {
7971                capture: match snapshot.capture {
7972                    CaptureState::Captured => StderrCaptureState::Captured,
7973                    CaptureState::Incomplete { reason } => {
7974                        StderrCaptureState::Incomplete { reason }
7975                    }
7976                    CaptureState::NotCaptured { reason } => {
7977                        StderrCaptureState::NotCaptured { reason }
7978                    }
7979                },
7980                entries: snapshot
7981                    .entries
7982                    .into_iter()
7983                    .map(|entry| match entry {
7984                        TailEntry::Line {
7985                            text,
7986                            truncated,
7987                            at_ms,
7988                        } => StderrTailEntry::Line {
7989                            text,
7990                            truncated,
7991                            at_ms,
7992                        },
7993                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7994                    })
7995                    .collect(),
7996                dropped_lines: snapshot.dropped_lines,
7997            },
7998        };
7999        Ok(vec![control_response_body_frame(
8000            &frame,
8001            &response,
8002            "ClientControlResponse::SupervisorStderrTail",
8003        )?])
8004    }
8005
8006    async fn observe_control_wait<F: std::future::Future>(
8007        &self,
8008        ctx: &RouteCtx,
8009        target: Option<&str>,
8010        kind: &'static str,
8011        future: F,
8012    ) -> F::Output {
8013        self.counters
8014            .observe_reader_wait(
8015                || {
8016                    let module = self
8017                        .forwarding
8018                        .module_id_for_connection(ctx.connection_id)
8019                        .ok()
8020                        .flatten();
8021                    let principal = if module.is_some() { "module" } else { "direct" };
8022                    (
8023                        self.resolve_reader_wait_target(kind, target)
8024                            .or(module)
8025                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
8026                        principal.into(),
8027                    )
8028                },
8029                kind,
8030                future,
8031            )
8032            .await
8033    }
8034
8035    /// Resolve the reader-wait module ID only from supervisor or registry
8036    /// records; never attribute a wait from the request selector alone.
8037    pub(crate) fn resolve_reader_wait_target(
8038        &self,
8039        op: &str,
8040        selector: Option<&str>,
8041    ) -> Option<String> {
8042        let selector = selector?;
8043        match op {
8044            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
8045                .supervisor
8046                .get(selector)
8047                .map(|module| module.module_id().to_owned()),
8048            ops::SUPERVISOR_HEALTH_PROBE => self
8049                .registry
8050                .get_module(selector)
8051                .ok()
8052                .flatten()
8053                .map(|registration| registration.manifest.module_id),
8054            _ => None,
8055        }
8056    }
8057
8058    async fn handle_supervisor_terminals(
8059        &self,
8060        ctx: &RouteCtx,
8061        frame: Frame,
8062        module_id: String,
8063    ) -> Result<Vec<Frame>, RouterError> {
8064        let Some(module) = self.supervisor.get(&module_id) else {
8065            return Ok(vec![control_error_frame(
8066                &frame,
8067                "unknown_module",
8068                format!("module_id '{module_id}' is not supervised"),
8069            )?]);
8070        };
8071
8072        // The journal read runs on a blocking thread: it can be megabytes of
8073        // file I/O and must not occupy a runtime worker.
8074        let terminals = self
8075            .observe_control_wait(
8076                ctx,
8077                Some(module.module_id()),
8078                ops::SUPERVISOR_TERMINALS,
8079                module.read_durable_terminal_history(),
8080            )
8081            .await
8082            .map_err(|error| {
8083                RouterError::backend(
8084                    0,
8085                    frame.header.corr,
8086                    format!("failed to read terminal history: {error}"),
8087                )
8088            })?;
8089        let response = ClientControlResponse::SupervisorTerminals {
8090            module_id,
8091            terminals,
8092        };
8093        Ok(vec![control_response_body_frame(
8094            &frame,
8095            &response,
8096            "ClientControlResponse::SupervisorTerminals",
8097        )?])
8098    }
8099
8100    fn handle_supervisor_routes(
8101        &self,
8102        frame: Frame,
8103        module_id: Option<String>,
8104    ) -> Result<Vec<Frame>, RouterError> {
8105        let modules = self
8106            .forwarding
8107            .route_census(module_id.as_deref())
8108            .map_err(RouterError::Forwarding)?
8109            .into_iter()
8110            .map(|(module_id, routes)| SupervisorRouteModule {
8111                module_id,
8112                routes: routes
8113                    .into_iter()
8114                    .map(|route| SupervisorRoute {
8115                        consumer: match route.principal {
8116                            Principal::Reserved { module_id } => {
8117                                SupervisorRouteConsumer::Reserved { module_id }
8118                            }
8119                            Principal::Direct | Principal::Unverified => {
8120                                SupervisorRouteConsumer::Direct {
8121                                    connection_id: route.goodbye_target.connection_id.get(),
8122                                }
8123                            }
8124                        },
8125                        age_ms: Instant::now()
8126                            .saturating_duration_since(route.bound_at)
8127                            .as_millis()
8128                            .try_into()
8129                            .unwrap_or(u64::MAX),
8130                        draining: route.draining,
8131                        drain_reason: route.drain_reason,
8132                    })
8133                    .collect(),
8134            })
8135            .collect();
8136        let response = ClientControlResponse::SupervisorRoutes { modules };
8137        Ok(vec![control_response_body_frame(
8138            &frame,
8139            &response,
8140            "ClientControlResponse::SupervisorRoutes",
8141        )?])
8142    }
8143
8144    fn running_registration_method(
8145        &self,
8146        module: &str,
8147    ) -> Option<subc_control::RegistrationMethod> {
8148        let registration = self.registry.get_module(module).ok()??;
8149        let connection = registration.connection_id;
8150        let channel = self.supervisor.registration_spawn(connection).is_some();
8151        let nonce = if channel {
8152            None
8153        } else {
8154            self.hello_launch_nonces
8155                .lock()
8156                .ok()?
8157                .nonce(connection)
8158                .map(str::to_owned)
8159        };
8160        if !channel && nonce.is_none() {
8161            return None;
8162        }
8163        self.supervisor
8164            .registration_snapshot_is_current_live(
8165                &self.registry,
8166                module,
8167                connection,
8168                nonce.as_deref(),
8169            )
8170            .then_some(if channel {
8171                subc_control::RegistrationMethod::Channel
8172            } else {
8173                subc_control::RegistrationMethod::Nonce
8174            })
8175    }
8176
8177    async fn handle_supervisor_provenance(
8178        &self,
8179        ctx: &RouteCtx,
8180        frame: Frame,
8181        module_id: Option<String>,
8182    ) -> Result<Vec<Frame>, RouterError> {
8183        let targeted = module_id.is_some();
8184        let selected = if let Some(module_id) = module_id {
8185            let Some(module) = self.supervisor.get(&module_id) else {
8186                return Ok(vec![control_error_frame(
8187                    &frame,
8188                    "unknown_module",
8189                    format!("module_id '{module_id}' is not supervised"),
8190                )?]);
8191            };
8192            vec![module]
8193        } else {
8194            self.supervisor.list()
8195        };
8196
8197        let target = targeted.then(|| selected[0].module_id());
8198        let declarations = if let Some(owner) = &self.config_runtime {
8199            owner
8200                .on_blocking(|owner| owner.registration_declarations())
8201                .await
8202                .ok()
8203        } else {
8204            None
8205        };
8206        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
8207            let mut modules = Vec::with_capacity(selected.len());
8208            let mut extensions = Vec::with_capacity(selected.len());
8209            for module in &selected {
8210                let (status, observed_image) = module
8211                    .status_and_running_image_agreement()
8212                    .await
8213                    .map_err(|err| {
8214                        RouterError::backend(
8215                            0,
8216                            frame.header.corr,
8217                            format!("failed to read supervisor status: {err}"),
8218                        )
8219                    })?;
8220                let module_declared = self
8221                    .registry
8222                    .get_module(&status.module_id)
8223                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8224                    .and_then(|registration| registration.manifest.provenance)
8225                    .map(|build| ModuleDeclaredProvenance::Reported { build })
8226                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
8227                #[cfg(test)]
8228                let running_image = match &self.provenance_probe_override {
8229                    Some(result) => result.clone(),
8230                    None => observed_image,
8231                };
8232                #[cfg(not(test))]
8233                let running_image = observed_image;
8234                let registration = self.running_registration_method(&status.module_id);
8235                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
8236                    .with_registration(registration);
8237                extension.registration_declaration = declarations
8238                    .as_ref()
8239                    .and_then(|entries| entries.get(&status.module_id))
8240                    .cloned();
8241                if status.process_alive && status.registration_declaration.is_some() {
8242                    extension.registration_declaration = status.registration_declaration.clone();
8243                }
8244                extensions.push(extension);
8245                modules.push(SupervisorModuleProvenance {
8246                    module_id: status.module_id,
8247                    module_declared,
8248                    daemon_observed: SupervisorObservedProcess {
8249                        launch_nonce_source: status.launch_nonce_source,
8250                        pid: status.pid,
8251                        spawned_at_ms: status.spawned_at_ms,
8252                        spawned_from: status.spawned_from,
8253                        running_image,
8254                    },
8255                });
8256            }
8257            let daemon = SupervisorDaemonProvenance {
8258                daemon_build: self.daemon_provenance.build.clone(),
8259                daemon_observed: DaemonObservedProcess {
8260                    pid: self.daemon_provenance.pid,
8261                    started_at_ms: self
8262                        .daemon_provenance
8263                        .start_clock
8264                        .map(|clock| clock.started_at_ms())
8265                        .or(self.daemon_provenance.started_at_ms),
8266                    running_image: self
8267                        .daemon_provenance
8268                        .probe
8269                        .observe(
8270                            self.daemon_provenance.pid,
8271                            self.daemon_provenance.executable_path.as_deref(),
8272                            self.daemon_provenance.executable_identity.clone(),
8273                            self.daemon_provenance.process_start_time,
8274                        )
8275                        .await,
8276                },
8277            };
8278            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8279            let mut response = serde_json::to_value(response)
8280                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8281            for (entry, extension) in response["modules"]
8282                .as_array_mut()
8283                .expect("provenance modules are an array")
8284                .iter_mut()
8285                .zip(extensions)
8286            {
8287                extension.write_to(entry).map_err(|error| {
8288                    RouterError::backend(0, frame.header.corr, error.to_string())
8289                })?;
8290            }
8291            Ok(vec![control_response_body_frame(
8292                &frame,
8293                &response,
8294                "ClientControlResponse::SupervisorProvenance",
8295            )?])
8296        })
8297        .await
8298    }
8299
8300    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8301        self.refresh_capability_requirements();
8302        let publication = self
8303            .config_runtime
8304            .as_ref()
8305            .and_then(|owner| owner.polled_snapshot().ok());
8306        let generation = self
8307            .registry
8308            .generation()
8309            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8310        let modules = self
8311            .supervisor
8312            .list()
8313            .into_iter()
8314            .map(|module| {
8315                let status = module.status_for_control("health").map_err(|err| {
8316                    RouterError::backend(
8317                        0,
8318                        frame.header.corr,
8319                        format!("failed to read supervisor health: {err}"),
8320                    )
8321                })?;
8322                let module_id = status.module_id;
8323                let capability_detail = self
8324                    .capability_evaluator
8325                    .required_problem_detail(&module_id);
8326                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8327                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8328                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8329                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8330                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8331                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8332                Ok(SupervisorHealthEntry {
8333                    module_id,
8334                    status: status.health.status,
8335                    detail: append_capability_problem_detail(
8336                        status.health.detail,
8337                        capability_detail,
8338                    ),
8339                    metrics: status.health.metrics,
8340                    consecutive_failures: status.health.consecutive_failures,
8341                    late_answer_count: status.health.late_answer_count,
8342                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8343                    last_action: status.health.last_action,
8344                    last_action_ms: status.health.last_action_ms,
8345                    last_probe_ms: status.health.last_probe_ms,
8346                })
8347            })
8348            .collect::<Result<Vec<_>, RouterError>>()?;
8349        let response = ClientControlResponse::SupervisorHealth {
8350            generation,
8351            modules,
8352        };
8353        Ok(vec![control_response_body_frame(
8354            &frame,
8355            &response,
8356            "ClientControlResponse::SupervisorHealth",
8357        )?])
8358    }
8359
8360    async fn handle_supervisor_restart(
8361        &self,
8362        frame: Frame,
8363        module_id: String,
8364        drain_timeout_ms: Option<u64>,
8365        requester: Principal,
8366    ) -> Result<Vec<Frame>, RouterError> {
8367        let operation_lock = self.supervisor.operation_lock();
8368        let _operation_guard = operation_lock.lock().await;
8369        let Some(module) = self.supervisor.get(&module_id) else {
8370            return Ok(vec![control_error_frame(
8371                &frame,
8372                "unknown_module",
8373                format!("module_id '{module_id}' is not supervised"),
8374            )?]);
8375        };
8376
8377        self.route_outages.mark_operator_action(&module_id);
8378        if let Err(err) = module
8379            .restart_requested(drain_timeout_ms, Some(requester))
8380            .await
8381        {
8382            self.route_outages
8383                .operator_action_ended_unrefused(&module_id);
8384            let (code, message) = match err {
8385                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8386                crate::supervise::SuperviseError::Disabled { .. } => {
8387                    ("module_disabled", err.to_string())
8388                }
8389                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8390                    ("swap_in_progress", err.to_string())
8391                }
8392                _ => (
8393                    "target_unavailable",
8394                    format!("failed to restart module_id '{module_id}': {err}"),
8395                ),
8396            };
8397            return Ok(vec![control_error_frame(&frame, code, message)?]);
8398        }
8399
8400        let response = ClientControlResponse::SupervisorAck {
8401            module_id,
8402            applied: true,
8403        };
8404        Ok(vec![control_response_body_frame(
8405            &frame,
8406            &response,
8407            "ClientControlResponse::SupervisorAck",
8408        )?])
8409    }
8410
8411    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8412    /// when the old process has finished draining: a caller whose own lane
8413    /// rides the old process must get its reply before that drain waits on it.
8414    async fn handle_supervisor_swap(
8415        &self,
8416        frame: Frame,
8417        module_id: String,
8418        ready_timeout_ms: Option<u64>,
8419        requester: Principal,
8420    ) -> Result<Vec<Frame>, RouterError> {
8421        // The daemon-wide operation lock is held only to resolve the handle,
8422        // not across the swap. The swap can take its whole readiness budget,
8423        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8424        // holding it here would park an operator's stop behind the swap it is
8425        // meant to abort. A rescan or stop that reaches the module during the
8426        // swap is served by the swap itself (see `supervise_swap`).
8427        let module = {
8428            let operation_lock = self.supervisor.operation_lock();
8429            let _operation_guard = operation_lock.lock().await;
8430            self.supervisor.get(&module_id)
8431        };
8432        let Some(module) = module else {
8433            return Ok(vec![control_error_frame(
8434                &frame,
8435                "unknown_module",
8436                format!("module_id '{module_id}' is not supervised"),
8437            )?]);
8438        };
8439
8440        self.route_outages.mark_operator_action(&module_id);
8441        if let Err(err) = module
8442            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8443            .await
8444        {
8445            self.route_outages
8446                .operator_action_ended_unrefused(&module_id);
8447            use crate::supervise::SuperviseError;
8448            let message = err.to_string();
8449            let error = match err {
8450                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8451                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8452                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8453                    code: "swap_refused".to_string(),
8454                    message,
8455                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8456                },
8457                SuperviseError::SwapFailed {
8458                    arm,
8459                    candidate_exit,
8460                    ..
8461                } => ErrorBody {
8462                    code: "swap_failed".to_string(),
8463                    message,
8464                    detail: Some(serde_json::json!({
8465                        "arm": arm.as_str(),
8466                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8467                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8468                    })),
8469                },
8470                _ => ErrorBody::new(
8471                    "target_unavailable",
8472                    format!("failed to swap module_id '{module_id}': {message}"),
8473                ),
8474            };
8475            return Ok(vec![control_error_body_frame(&frame, error)?]);
8476        }
8477        // A completed swap kept the incumbent serving until cutover, so it
8478        // usually opened no outage; a mark left behind would make the next,
8479        // unrelated outage read as requested.
8480        self.route_outages
8481            .operator_action_ended_unrefused(&module_id);
8482
8483        let response = ClientControlResponse::SupervisorAck {
8484            module_id,
8485            applied: true,
8486        };
8487        Ok(vec![control_response_body_frame(
8488            &frame,
8489            &response,
8490            "ClientControlResponse::SupervisorAck",
8491        )?])
8492    }
8493
8494    async fn handle_supervisor_reload(
8495        &self,
8496        frame: Frame,
8497        module_id: String,
8498        requester: Principal,
8499    ) -> Result<Vec<Frame>, RouterError> {
8500        let operation_lock = self.supervisor.operation_lock();
8501        let _operation_guard = operation_lock.lock().await;
8502        let Some(module) = self.supervisor.get(&module_id) else {
8503            return Ok(vec![control_error_frame(
8504                &frame,
8505                "unknown_module",
8506                format!("module_id '{module_id}' is not supervised"),
8507            )?]);
8508        };
8509
8510        self.route_outages.mark_operator_action(&module_id);
8511        if let Err(err) = module.reload_requested(Some(requester)).await {
8512            self.route_outages
8513                .operator_action_ended_unrefused(&module_id);
8514            let (code, message) = match err {
8515                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8516                crate::supervise::SuperviseError::Disabled { .. } => {
8517                    ("module_disabled", err.to_string())
8518                }
8519                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8520                    ("swap_in_progress", err.to_string())
8521                }
8522                _ => (
8523                    "reload_failed",
8524                    format!("failed to reload module_id '{module_id}': {err}"),
8525                ),
8526            };
8527            return Ok(vec![control_error_frame(&frame, code, message)?]);
8528        }
8529
8530        let response = ClientControlResponse::SupervisorAck {
8531            module_id,
8532            applied: true,
8533        };
8534        Ok(vec![control_response_body_frame(
8535            &frame,
8536            &response,
8537            "ClientControlResponse::SupervisorAck",
8538        )?])
8539    }
8540
8541    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8542    /// the configuration comes from and whether to apply it; every mode then
8543    /// runs the same comparison, so a preview describes the apply it previews.
8544    async fn handle_supervisor_rescan(
8545        &self,
8546        frame: Frame,
8547        mode: RescanMode,
8548        requester: Principal,
8549    ) -> Result<Vec<Frame>, RouterError> {
8550        let preview = mode.previews();
8551        let mut approved_preview = None;
8552        if matches!(mode, RescanMode::Preview) {
8553            if let Some(owner) = &self.config_runtime {
8554                match owner
8555                    .on_blocking(|owner| {
8556                        owner.observe_file_proposal()?;
8557                        owner.approved_daemon_configuration()
8558                    })
8559                    .await
8560                {
8561                    Ok(config) => approved_preview = config,
8562                    Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8563                }
8564            }
8565        }
8566        let Some(context) = self.rescan.clone() else {
8567            return Ok(vec![control_error_frame(
8568                &frame,
8569                "rescan_unavailable",
8570                "the daemon was not started with a reloadable config path".to_string(),
8571            )?]);
8572        };
8573
8574        let operation_lock = self.supervisor.operation_lock();
8575        let _operation_guard = operation_lock.lock().await;
8576        // Loaded under the operation lock, so no other rescan can change the
8577        // staged configuration between a checked apply's comparison and the
8578        // apply itself.
8579        let loaded = match self.load_rescan_config(&mode, &context) {
8580            Ok(config) => config,
8581            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
8582        };
8583        // `load` reports a missing file as Ok(None), which is correct at boot
8584        // (no config, nothing to supervise) and catastrophic here: rescan treats
8585        // "not in the config" as "remove it", so an absent file would read as an
8586        // empty module list and retire the entire running fleet. An editor
8587        // writing via write-new-then-rename, or a half-finished edit, is enough
8588        // to open that window. Refuse instead: a config that cannot be read
8589        // carries no instruction to remove anything.
8590        let Some((config, activity_config)) = loaded else {
8591            return Ok(vec![control_error_frame(
8592                &frame,
8593                "invalid_daemon_config",
8594                format!(
8595                    "daemon config not found at {}; refusing to rescan (an absent config would \
8596                     retire every supervised module)",
8597                    context.config_path.display()
8598                ),
8599            )?]);
8600        };
8601        let (
8602            configured_port,
8603            storage_config,
8604            admission_facts_carrier_module_id,
8605            admission_facts_targets,
8606            scope_authority_owners,
8607            federated_scope_owner,
8608            privileged_operator_prompt,
8609            modules,
8610            reserved_capabilities,
8611        ) = (
8612            config.port,
8613            config.storage,
8614            config.admission_facts_carrier_module_id,
8615            config.admission_facts_targets,
8616            config.scope_authority_owners,
8617            config.federated_scope_owner,
8618            config.privileged_operator_prompt,
8619            config.modules,
8620            config.reserved_capabilities,
8621        );
8622
8623        // Collect the sections rescan cannot apply, so the REPLY carries them.
8624        //
8625        // The warning below has always been correct and has always gone only to
8626        // the journal -- addressed to whoever reads logs, while the person who
8627        // just edited the config is looking at the CLI. Naming each section
8628        // individually rather than setting a flag: "something outside modules
8629        // changed" sends the operator back to diffing their own file, which is
8630        // the work this is meant to save.
8631        let mut restart_required = Vec::new();
8632        for section in RestartRequiredSection::ALL {
8633            let changed = match section {
8634                RestartRequiredSection::Port => configured_port != context.configured_port,
8635                RestartRequiredSection::Storage => storage_config != context.storage_config,
8636                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8637                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8638                }
8639                RestartRequiredSection::AdmissionFactsTargets => {
8640                    admission_facts_targets != context.admission_facts_targets
8641                }
8642                RestartRequiredSection::ScopeAuthorityOwners => {
8643                    scope_authority_owners != context.scope_authority_owners
8644                }
8645                RestartRequiredSection::FederatedScopeOwner => {
8646                    federated_scope_owner != context.federated_scope_owner
8647                }
8648                RestartRequiredSection::PrivilegedOperatorPrompt => {
8649                    privileged_operator_prompt != context.privileged_operator_prompt
8650                }
8651            };
8652            if changed {
8653                restart_required.push(section.label().to_string());
8654            }
8655        }
8656        if !restart_required.is_empty() {
8657            warn!(
8658                config_path = %context.config_path.display(),
8659                sections = %restart_required.join(", "),
8660                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8661            );
8662        }
8663
8664        for configured in &modules {
8665            if let Err(err) = validate_spec(&configured.module_spec()) {
8666                return Ok(vec![control_error_frame(
8667                    &frame,
8668                    "invalid_daemon_config",
8669                    format!("supervisor rescan rejected daemon config: {err}"),
8670                )?]);
8671            }
8672        }
8673
8674        let configured_capabilities = modules
8675            .iter()
8676            .map(|module| (module.module_id.clone(), module.enabled))
8677            .collect::<Vec<_>>();
8678        let preview_capability_warnings = if preview {
8679            let (_, registrations) = self.runtime_capability_snapshot()?;
8680            let current_modules = self
8681                .supervisor
8682                .list()
8683                .into_iter()
8684                .map(|module| module.module_id().to_string())
8685                .collect::<BTreeSet<_>>();
8686            let resulting_modules = configured_capabilities.clone();
8687            let removed = current_modules
8688                .into_iter()
8689                .filter(|module_id| {
8690                    !resulting_modules
8691                        .iter()
8692                        .any(|(configured_id, _)| configured_id == module_id)
8693                })
8694                .collect::<Vec<_>>();
8695            // A candidate preview also names providers the candidate disables.
8696            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8697            let disabled = match &mode {
8698                RescanMode::Candidate(_) => resulting_modules
8699                    .iter()
8700                    .filter(|(_, enabled)| !enabled)
8701                    .map(|(module_id, _)| module_id.clone())
8702                    .collect::<Vec<_>>(),
8703                _ => Vec::new(),
8704            };
8705            self.capability_evaluator.preview_warnings(
8706                resulting_modules,
8707                &removed,
8708                &disabled,
8709                &registrations,
8710            )
8711        } else {
8712            Vec::new()
8713        };
8714        let reconciled = match (&mode, approved_preview.as_ref()) {
8715            (RescanMode::Preview, Some(approved)) => Ok((
8716                config_gate::preview_approved_daemon(approved, &modules),
8717                Vec::new(),
8718            )),
8719            (RescanMode::Candidate(candidate), _) => self
8720                .preview_candidate(&context, modules, candidate)
8721                .map(|result| (result, Vec::new())),
8722            _ => {
8723                self.reconcile_supervised_modules(
8724                    &context.supervisor,
8725                    modules,
8726                    preview,
8727                    requester.clone(),
8728                )
8729                .await
8730            }
8731        };
8732        let (result, changed) = match reconciled {
8733            Ok(result) => result,
8734            Err(message) => {
8735                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8736            }
8737        };
8738        if !preview {
8739            if let Some(ledger) = &self.activity {
8740                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8741                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8742            }
8743            if let Err(code) = self.configure_activity(activity_config).await {
8744                warn!(
8745                    code,
8746                    "activity retention could not be applied during rescan"
8747                );
8748            }
8749            self.capability_evaluator
8750                .configure(configured_capabilities, reserved_capabilities);
8751            self.capability_evaluator.wake_deadline_loop();
8752            self.refresh_capability_requirements();
8753        }
8754        let mut result = result;
8755        result.restart_required = restart_required;
8756        result.capability_warnings = preview_capability_warnings;
8757        let response = ClientControlResponse::SupervisorRescan { result };
8758        Ok(vec![control_response_body_frame(
8759            &frame,
8760            &response,
8761            "ClientControlResponse::SupervisorRescan",
8762        )?])
8763    }
8764
8765    async fn handle_supervisor_release_reserved(
8766        &self,
8767        frame: Frame,
8768        module_id: String,
8769    ) -> Result<Vec<Frame>, RouterError> {
8770        let Some(context) = self.rescan.clone() else {
8771            return Ok(vec![control_error_frame(
8772                &frame,
8773                "release_unavailable",
8774                "reserved-id release requires a daemon started with a reloadable config path",
8775            )?]);
8776        };
8777        let operation_lock = self.supervisor.operation_lock();
8778        let _operation_guard = operation_lock.lock().await;
8779        let approved = if let Some(owner) = &self.config_runtime {
8780            // Observe the file as a proposal, but decide membership solely from
8781            // approved bytes. A proposed re-add must not retain a removed id.
8782            match owner
8783                .on_blocking(|owner| {
8784                    owner.observe_file_proposal()?;
8785                    owner.approved_daemon_configuration()
8786                })
8787                .await
8788            {
8789                Ok(config) => config,
8790                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8791            }
8792        } else {
8793            None
8794        };
8795        let loaded = if let Some(approved) = approved {
8796            Ok(Some(approved))
8797        } else {
8798            crate::daemon_config::load(&context.config_path)
8799        };
8800        let loaded = match loaded {
8801            Ok(Some(config)) => config,
8802            Ok(None) => {
8803                return Ok(vec![control_error_frame(
8804                    &frame,
8805                    "invalid_daemon_config",
8806                    format!(
8807                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8808                        context.config_path.display()
8809                    ),
8810                )?])
8811            }
8812            Err(err) => {
8813                return Ok(vec![control_error_frame(
8814                    &frame,
8815                    "invalid_daemon_config",
8816                    format!("unable to verify reserved-id release against daemon config: {err}"),
8817                )?])
8818            }
8819        };
8820        if loaded
8821            .modules
8822            .iter()
8823            .any(|configured| configured.module_id == module_id)
8824        {
8825            return Ok(vec![control_error_frame(
8826                &frame,
8827                "reserved_module_configured",
8828                format!(
8829                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8830                ),
8831            )?]);
8832        }
8833        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8834            return Ok(vec![control_error_frame(
8835                &frame,
8836                "reserved_gate_not_retained",
8837                format!(
8838                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8839                ),
8840            )?]);
8841        }
8842
8843        let response = ClientControlResponse::SupervisorAck {
8844            module_id,
8845            applied: true,
8846        };
8847        Ok(vec![control_response_body_frame(
8848            &frame,
8849            &response,
8850            "ClientControlResponse::SupervisorAck",
8851        )?])
8852    }
8853
8854    /// Compare the configured module set with the supervised one, changing
8855    /// nothing. The staged spec each supervised module holds is what the
8856    /// configured entry is compared with.
8857    fn plan_rescan(
8858        &self,
8859        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8860    ) -> Result<RescanPlan, String> {
8861        let mut current = BTreeMap::new();
8862        for module in self.supervisor.list() {
8863            let (spec, health) = module.configuration().map_err(|err| {
8864                format!(
8865                    "failed to read configuration for module_id '{}': {err}",
8866                    module.module_id()
8867                )
8868            })?;
8869            let enabled = module
8870                .status()
8871                .map_err(|err| {
8872                    format!(
8873                        "failed to read status for module_id '{}': {err}",
8874                        module.module_id()
8875                    )
8876                })?
8877                .enabled;
8878            current.insert(
8879                module.module_id().to_string(),
8880                (module, spec, health, enabled),
8881            );
8882        }
8883        let configured = configured_modules
8884            .into_iter()
8885            .map(|module| (module.module_id.clone(), module))
8886            .collect::<BTreeMap<_, _>>();
8887
8888        let added = configured
8889            .keys()
8890            .filter(|module_id| !current.contains_key(*module_id))
8891            .cloned()
8892            .collect::<Vec<_>>();
8893        let removed = current
8894            .keys()
8895            .filter(|module_id| !configured.contains_key(*module_id))
8896            .cloned()
8897            .collect::<Vec<_>>();
8898        let mut changed_pending_reload = Vec::new();
8899        let mut changed_pending = Vec::new();
8900        let mut configuration_changes = BTreeSet::new();
8901        let mut enabled_changes = BTreeSet::new();
8902        let mut unchanged = 0_u32;
8903        let publication = self
8904            .config_runtime
8905            .as_ref()
8906            .and_then(|owner| owner.polled_snapshot().ok());
8907
8908        for (module_id, configured_module) in &configured {
8909            let Some((module, current_spec, current_health, current_enabled)) =
8910                current.get(module_id)
8911            else {
8912                continue;
8913            };
8914            // Compare the whole launch spec so a future launch field cannot
8915            // accidentally become a live-only policy change. Health is stored
8916            // separately and applies live without replacing the process.
8917            let launch_changed = *current_spec != configured_module.module_spec();
8918            let configuration_changed =
8919                launch_changed || *current_health != configured_module.health;
8920            let pending = self.pending_module_fields(
8921                module,
8922                Some(configured_module),
8923                configuration_changed,
8924                Self::registration_channel_in_force(
8925                    publication
8926                        .as_ref()
8927                        .and_then(|view| view.registration_declaration(module_id))
8928                        .as_deref(),
8929                    publication
8930                        .as_ref()
8931                        .and_then(|view| match &view.approved_daemon {
8932                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8933                                config,
8934                                ..
8935                            } => config
8936                                .modules
8937                                .iter()
8938                                .find(|entry| entry.module_id == *module_id)
8939                                .map(|entry| entry.registration_channel),
8940                            _ => None,
8941                        }),
8942                ),
8943            )?;
8944            let has_pending = !pending.is_empty();
8945            if has_pending {
8946                changed_pending.push(subc_control::SupervisorPendingModule {
8947                    module_id: module_id.clone(),
8948                    fields: pending
8949                        .into_iter()
8950                        .map(|mut field| {
8951                            field.value = None;
8952                            field
8953                        })
8954                        .collect(),
8955                });
8956            }
8957            // Applying a rescan also replaces the recorded config value, even
8958            // when an operator already put the runtime in the requested state.
8959            let enabled_changed = *current_enabled != configured_module.enabled
8960                || self
8961                    .capability_evaluator
8962                    .configured_enabled(module_id)
8963                    .is_some_and(|enabled| enabled != configured_module.enabled);
8964            if configuration_changed {
8965                configuration_changes.insert(module_id.clone());
8966            }
8967            if launch_changed {
8968                changed_pending_reload.push(module_id.clone());
8969            }
8970            if enabled_changed {
8971                enabled_changes.insert(module_id.clone());
8972            }
8973            if !configuration_changed && !enabled_changed && !has_pending {
8974                unchanged = unchanged.saturating_add(1);
8975            }
8976        }
8977        Ok(RescanPlan {
8978            current,
8979            configured,
8980            added,
8981            removed,
8982            changed_pending_reload,
8983            changed_pending,
8984            configuration_changes,
8985            enabled_changes,
8986            unchanged,
8987        })
8988    }
8989
8990    /// Reconcile the running module set against the configured one.
8991    ///
8992    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8993    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8994    /// deliberately shares this function with the executing path rather than
8995    /// computing the same diff somewhere else -- two implementations of one
8996    /// decision agree until they do not, and the whole value of a preview is that
8997    /// it describes the operation that will actually run.
8998    async fn reconcile_supervised_modules(
8999        &self,
9000        supervisor: &Supervisor,
9001        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
9002        preview: bool,
9003        requester: Principal,
9004    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
9005        let plan = self.plan_rescan(configured_modules)?;
9006
9007        // Everything above this point is pure computation over two snapshots.
9008        // Everything below MUTATES. The preview returns here so the boundary is a
9009        // single early return rather than a condition repeated at each mutation
9010        // site, where one missed guard would apply part of a change the caller was
9011        // told would not happen.
9012        if preview {
9013            return Ok((plan.preview_result(), Vec::new()));
9014        }
9015        let changed = plan
9016            .configuration_changes
9017            .union(&plan.enabled_changes)
9018            .cloned()
9019            .collect::<Vec<_>>();
9020        let RescanPlan {
9021            current,
9022            configured,
9023            added,
9024            removed,
9025            changed_pending_reload,
9026            changed_pending,
9027            configuration_changes,
9028            enabled_changes,
9029            unchanged,
9030        } = plan;
9031        // The staged generation moves before the first change rather than
9032        // after the last, so a rescan that fails partway still invalidates
9033        // every earlier `supervisor.rescan_checked` preview: part of its diff
9034        // may have run.
9035        if !(added.is_empty()
9036            && removed.is_empty()
9037            && configuration_changes.is_empty()
9038            && changed_pending.is_empty()
9039            && enabled_changes.is_empty())
9040        {
9041            if let Some(context) = &self.rescan {
9042                context
9043                    .generation
9044                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
9045            }
9046        }
9047
9048        for module_id in &removed {
9049            let module = &current
9050                .get(module_id)
9051                .expect("removed module came from current supervisor state")
9052                .0;
9053            module
9054                .retire_requested(Some(requester.clone()))
9055                .await
9056                .map_err(|err| {
9057                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
9058                })?;
9059            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
9060            //
9061            // `handle_route_open` resolves an absent module in three steps:
9062            // registry, then supervisor status, then tombstone. Retiring first
9063            // opens a window where ALL THREE ARE ABSENT -- the registry entry
9064            // went with the teardown above, the supervisor entry went with
9065            // `retire`, and the tombstone does not exist yet -- so a route.open
9066            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
9067            // it") for a module that was deliberately removed and whose caller
9068            // should get `module_removed` (TERMINAL, carrying a removal age).
9069            //
9070            // Writing the tombstone first closes it: during the window the
9071            // supervisor entry still answers, so the caller gets
9072            // `target_unavailable` -- retryable, and TRUE, because the module
9073            // is mid-teardown. After both statements it is `module_removed`.
9074            // No instant remains where a removed module reads as one that
9075            // never existed.
9076            //
9077            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
9078            // the absence of a test beside a fix invites deletion: these are
9079            // two sync statements with no await between them, so reaching the
9080            // window needs a second worker thread to land exactly between them
9081            // and there is no hook to force it. MEASURED: the 25 daemon_config
9082            // tests pass identically with the old order and the new one, so
9083            // the existing suite cannot see this and a green run is not
9084            // evidence either way. What the suite does hold is the
9085            // post-condition -- a removed module answers `module_removed` --
9086            // which this preserves.
9087            //
9088            // Found by an Athena panel reading the shipped tree against a
9089            // design note (2026-09-19), as the one concrete instance of that
9090            // note's class that survived contact with source. Direction is
9091            // benign: retryable where terminal was intended, never the reverse.
9092            self.supervisor.record_rescan_removal(module_id);
9093            self.supervisor.retire(module_id);
9094            self.route_outages.forget(module_id);
9095        }
9096
9097        for module_id in configured.keys() {
9098            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
9099                continue;
9100            };
9101            let configured_module = configured
9102                .get(module_id)
9103                .expect("configured module id came from configured map");
9104            if configuration_changes.contains(module_id) {
9105                module
9106                    .update_configuration(
9107                        configured_module.module_spec(),
9108                        configured_module.health.clone(),
9109                        configured_module.drain_timeout_ms,
9110                    )
9111                    .await
9112                    .map_err(|err| {
9113                        format!(
9114                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
9115                        )
9116                    })?;
9117            }
9118            // Config-only drift is applied by the evaluator's config update;
9119            // do not turn it into a runtime start or stop.
9120            if *current_enabled != configured_module.enabled {
9121                // A rescan that starts or stops a module applies an operator's
9122                // edit to the config, so the resulting outage was asked for.
9123                self.route_outages.mark_operator_action(module_id);
9124                module
9125                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
9126                    .await
9127                    .map_err(|err| {
9128                        self.route_outages.operator_action_ended_unrefused(module_id);
9129                        format!(
9130                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
9131                            configured_module.enabled
9132                        )
9133                    })?;
9134            }
9135        }
9136
9137        for module_id in &added {
9138            let configured_module = configured
9139                .get(module_id)
9140                .expect("added module id came from configured map");
9141            supervisor
9142                .supervise_configured_requested_async(
9143                    configured_module.module_spec(),
9144                    configured_module.enabled,
9145                    configured_module.health.clone(),
9146                    configured_module.drain_timeout_ms,
9147                    configured_module.restart,
9148                    configured_module.register_timeout,
9149                    Some(requester.clone()),
9150                )
9151                .await
9152                .map_err(|err| {
9153                    format!("failed to add module_id '{module_id}' during rescan: {err}")
9154                })?;
9155        }
9156
9157        if let Some(context) = &self.rescan {
9158            let mut entries = context
9159                .module_entries
9160                .lock()
9161                .unwrap_or_else(|e| e.into_inner());
9162            entries.record(&configured, &added, &removed);
9163        }
9164
9165        Ok((
9166            SupervisorRescanResult {
9167                added,
9168                removed,
9169                changed_pending_reload,
9170                changed_pending,
9171                enabled_changes: enabled_changes.iter().cloned().collect(),
9172                unchanged,
9173                preview: false,
9174                // Filled by the caller, which is the only layer that can see the
9175                // previous config to diff against.
9176                restart_required: Vec::new(),
9177                capability_warnings: Vec::new(),
9178                module_actions: Vec::new(),
9179                earlier_pending: Vec::new(),
9180                expect: None,
9181            },
9182            changed,
9183        ))
9184    }
9185
9186    async fn handle_supervisor_set_enabled(
9187        &self,
9188        frame: Frame,
9189        module_id: String,
9190        enabled: bool,
9191        requester: Principal,
9192    ) -> Result<Vec<Frame>, RouterError> {
9193        let operation_lock = self.supervisor.operation_lock();
9194        let _operation_guard = operation_lock.lock().await;
9195        let Some(module) = self.supervisor.get(&module_id) else {
9196            return Ok(vec![control_error_frame(
9197                &frame,
9198                "unknown_module",
9199                format!("module_id '{module_id}' is not supervised"),
9200            )?]);
9201        };
9202
9203        // Enabling counts as well as disabling: a module an operator starts
9204        // is refused until it registers, and that wait was asked for.
9205        self.route_outages.mark_operator_action(&module_id);
9206        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
9207            Ok(applied) => applied,
9208            Err(err) => {
9209                self.route_outages
9210                    .operator_action_ended_unrefused(&module_id);
9211                return Ok(vec![control_error_frame(
9212                    &frame,
9213                    if err.is_config_gate_error() {
9214                        "config_gated"
9215                    } else {
9216                        "target_unavailable"
9217                    },
9218                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
9219                )?]);
9220            }
9221        };
9222        if !applied {
9223            // Already in the requested state: nothing was made unavailable,
9224            // so the mark must not outlive this request.
9225            self.route_outages
9226                .operator_action_ended_unrefused(&module_id);
9227        }
9228
9229        self.capability_evaluator.wake_deadline_loop();
9230        self.refresh_capability_requirements();
9231        let response = ClientControlResponse::SupervisorAck { module_id, applied };
9232        Ok(vec![control_response_body_frame(
9233            &frame,
9234            &response,
9235            "ClientControlResponse::SupervisorAck",
9236        )?])
9237    }
9238
9239    async fn handle_supervisor_health_probe(
9240        &self,
9241        ctx: &RouteCtx,
9242        frame: Frame,
9243        module_id: String,
9244    ) -> Result<Vec<Frame>, RouterError> {
9245        self.refresh_capability_requirements();
9246        let Some(registration) = self
9247            .registry
9248            .get_module(&module_id)
9249            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
9250        else {
9251            return Ok(vec![control_error_frame(
9252                &frame,
9253                "unknown_module",
9254                format!("module_id '{module_id}' is not registered"),
9255            )?]);
9256        };
9257
9258        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
9259        // named for it. Making `module_registration_grants_op` return false
9260        // unconditionally reddens five tests, and every one is named for something
9261        // else -- capability relay, probe/bind demultiplexing, supervision-only
9262        // probing. They exercise a successful advertisement check on the way to their
9263        // own subject.
9264        //
9265        // Real protection, fragile in a specific way: narrowing any of those tests to
9266        // focus on its stated subject would silently remove coverage nobody knows
9267        // they are carrying. Recorded here rather than as a sixth test, because the
9268        // useful fact is WHICH tests hold the guard up -- a new test would add
9269        // coverage without telling the next person what the existing ones quietly do.
9270        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
9271        {
9272            return Ok(vec![control_error_frame(
9273                &frame,
9274                "health_not_advertised",
9275                format!("module_id '{module_id}' did not advertise health.check"),
9276            )?]);
9277        }
9278
9279        self.observe_control_wait(
9280            ctx,
9281            Some(&registration.manifest.module_id),
9282            ops::SUPERVISOR_HEALTH_PROBE,
9283            async {
9284                let deadline = Instant::now() + self.health_probe_timeout;
9285                let pending = match self.forwarding.begin_module_control_rpc_for(
9286                    &module_id,
9287                    MODULE_CONTROL_OP_HEALTH_CHECK,
9288                    deadline,
9289                ) {
9290                    Ok(pending) => pending,
9291                    Err(err) => {
9292                        return Ok(vec![control_error_frame(
9293                            &frame,
9294                            forwarding_error_code(&err),
9295                            err.to_string(),
9296                        )?])
9297                    }
9298                };
9299
9300                let PendingModuleControlRpc {
9301                    endpoint,
9302                    module_sink,
9303                    negotiated_ver,
9304                    corr: probe_corr,
9305                    receiver,
9306                } = pending;
9307                let mut guard =
9308                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9309                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9310                    .map_err(|err| {
9311                        RouterError::backend(
9312                            0,
9313                            frame.header.corr,
9314                            format!("failed to encode health.check request: {err}"),
9315                        )
9316                    })?;
9317                let probe_frame = Frame::build_with_version(
9318                    negotiated_ver,
9319                    FrameType::Request,
9320                    control_flags(),
9321                    0,
9322                    0,
9323                    probe_corr,
9324                    probe_body,
9325                )
9326                .map_err(RouterError::FrameBuild)?;
9327
9328                // Queue admission and the reply share one deadline, so a module that
9329                // stops reading cannot park the requesting connection's reader forever.
9330                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9331                    Ok(Ok(())) => {}
9332                    Ok(Err(err)) => {
9333                        return Ok(vec![control_error_frame(
9334                            &frame,
9335                            "target_unavailable",
9336                            err.to_string(),
9337                        )?]);
9338                    }
9339                    Err(_) => {
9340                        return Ok(vec![control_error_frame(
9341                            &frame,
9342                            "module_timeout",
9343                            format!(
9344                                "module_id '{module_id}' did not answer health.check within {:?}",
9345                                self.health_probe_timeout
9346                            ),
9347                        )?]);
9348                    }
9349                }
9350
9351                match timeout_at(deadline, receiver).await {
9352                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9353                        Ok(vec![control_error_frame(
9354                            &frame,
9355                            "invalid_control_body",
9356                            "health.check returned an unexpected config response",
9357                        )?])
9358                    }
9359                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9360                        guard.disarm();
9361                        let Some(report) = response.health_report() else {
9362                            return Ok(vec![control_error_frame(
9363                                &frame,
9364                                "invalid_control_body",
9365                                "health.check RPC returned a non-health response",
9366                            )?]);
9367                        };
9368                        // Metrics go out whole here. The supervisor's cached snapshot
9369                        // caps this blob (see truncate_health_metrics), and this path
9370                        // exists precisely to answer without that cap -- so applying it
9371                        // here would leave no way to see what the cached view drops.
9372                        let HealthReport {
9373                            status,
9374                            detail,
9375                            metrics,
9376                        } = report;
9377                        let capability_detail = self
9378                            .capability_evaluator
9379                            .required_problem_detail(&module_id);
9380                        let response = ClientControlResponse::SupervisorHealthProbe {
9381                            module_id,
9382                            status,
9383                            detail: append_capability_problem_detail(detail, capability_detail),
9384                            metrics,
9385                        };
9386                        Ok(vec![control_response_body_frame(
9387                            &frame,
9388                            &response,
9389                            "ClientControlResponse::SupervisorHealthProbe",
9390                        )?])
9391                    }
9392                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9393                        guard.disarm();
9394                        // The module refused the health probe with its own body, so
9395                        // the refusal is relayed without the daemon-origin flag
9396                        // (bit 6): a client must not read it as the daemon's own
9397                        // refusal, which it may treat as never forwarded.
9398                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9399                    }
9400                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9401                        guard.disarm();
9402                        Ok(vec![control_error_frame(
9403                            &frame,
9404                            "target_unavailable",
9405                            message,
9406                        )?])
9407                    }
9408                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9409                        guard.disarm();
9410                        Ok(vec![control_error_frame(
9411                            &frame,
9412                            "invalid_control_body",
9413                            message,
9414                        )?])
9415                    }
9416                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9417                        guard.disarm();
9418                        Ok(vec![control_error_frame(
9419                            &frame,
9420                            "invalid_control_body",
9421                            format!("expected module-control op '{expected}', got '{actual}'"),
9422                        )?])
9423                    }
9424                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9425                        guard.disarm();
9426                        Ok(vec![control_error_frame(
9427                            &frame,
9428                            "module_timeout",
9429                            format!(
9430                                "module_id '{module_id}' answered health.check after {:?}",
9431                                self.health_probe_timeout
9432                            ),
9433                        )?])
9434                    }
9435                    Ok(Err(_)) => Ok(vec![control_error_frame(
9436                        &frame,
9437                        "target_unavailable",
9438                        "health.check waiter was canceled before the module responded",
9439                    )?]),
9440                    Err(_) => Ok(vec![control_error_frame(
9441                        &frame,
9442                        "module_timeout",
9443                        format!(
9444                            "module_id '{module_id}' did not answer health.check within {:?}",
9445                            self.health_probe_timeout
9446                        ),
9447                    )?]),
9448                }
9449            },
9450        )
9451        .await
9452    }
9453
9454    fn supervisor_status(
9455        &self,
9456        module_id: &str,
9457        corr: u64,
9458    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9459        self.supervisor
9460            .get(module_id)
9461            .map(|module| {
9462                let warming = module.is_warming_for_control("status").map_err(|err| {
9463                    RouterError::backend(
9464                        0,
9465                        corr,
9466                        format!(
9467                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9468                        ),
9469                    )
9470                })?;
9471                module.status_for_control("status").map_err(|err| {
9472                    RouterError::backend(
9473                        0,
9474                        corr,
9475                        format!(
9476                            "failed to read supervisor status for module_id '{module_id}': {err}"
9477                        ),
9478                    )
9479                }).map(|status| (status, warming))
9480            })
9481            .transpose()
9482    }
9483
9484    fn guard_module_control_op(
9485        &self,
9486        frame: &Frame,
9487        module_id: &str,
9488        op: &str,
9489    ) -> Result<Option<Frame>, RouterError> {
9490        if self.module_grants_op(module_id, op, frame.header.corr)? {
9491            return Ok(None);
9492        }
9493
9494        Ok(Some(control_error_frame(
9495            frame,
9496            "op_not_allowed",
9497            format!("module_id '{module_id}' did not grant control op '{op}'"),
9498        )?))
9499    }
9500
9501    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9502        self.registry
9503            .grants_control_op(module_id, op)
9504            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9505    }
9506
9507    fn handle_status_update(
9508        &self,
9509        endpoint: ModuleEndpointId,
9510        frame: Frame,
9511    ) -> Result<Vec<Frame>, RouterError> {
9512        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9513            Ok(update) => update,
9514            Err(err) => {
9515                // Forward-compat: a newer module may push a channel-0 op this subc
9516                // version doesn't know. The control contract says unknown push ops
9517                // are IGNORED, never answered with an error. Only a malformed body
9518                // for an op we DO know is a real error worth surfacing.
9519                if is_known_module_push_op(&frame.body) {
9520                    return Ok(vec![control_error_frame(
9521                        &frame,
9522                        "invalid_control_body",
9523                        format!("malformed module control push body: {err}"),
9524                    )?]);
9525                }
9526                return Ok(Vec::new());
9527            }
9528        };
9529
9530        match update {
9531            ModuleControlPush::RouteStatus {
9532                route_channel,
9533                route_epoch,
9534                status,
9535            } => {
9536                self.forwarding
9537                    .cache_status(endpoint, route_channel, route_epoch, status)
9538                    .map_err(RouterError::Forwarding)?;
9539            }
9540        }
9541        Ok(Vec::new())
9542    }
9543
9544    fn handle_route_poll(
9545        &self,
9546        ctx: &RouteCtx,
9547        frame: Frame,
9548        route_channel: u16,
9549        route_epoch: u32,
9550        kind: PollKind,
9551    ) -> Result<Vec<Frame>, RouterError> {
9552        let snapshot = self
9553            .forwarding
9554            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9555            .map_err(RouterError::Forwarding)?;
9556        let response = match (kind, snapshot) {
9557            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9558                ClientControlResponse::RoutePoll {
9559                    route_channel,
9560                    route_epoch,
9561                    status,
9562                    live: None,
9563                }
9564            }
9565            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9566                route_channel,
9567                route_epoch,
9568                status: None,
9569                live: None,
9570            },
9571            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9572                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9573                // is what makes reporting `true` correct rather than a
9574                // confident guess. `process_live` returns None only when the
9575                // module id has no supervisor snapshot at all -- an
9576                // externally-started module the daemon did not spawn -- and
9577                // for those the supervisor has no opinion to offer, ever. It
9578                // is never None for a supervised module in an unknown state:
9579                // a supervised module always has a snapshot, and the answer
9580                // comes from `state == Running && process_alive`.
9581                //
9582                // The route is Bound, so the module completed a HELLO on a
9583                // live connection; "the process this route points at is
9584                // running" is therefore attested by the binding rather than
9585                // assumed. Reporting `false` for an unsupervised module would
9586                // be the actual lie -- it would tell a client its healthy
9587                // route is dead because the daemon does not manage the
9588                // process.
9589                //
9590                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9591                // module whose liveness is genuinely unknown, e.g. a snapshot
9592                // that has not been populated yet -- THIS DEFAULT BECOMES
9593                // WRONG and must split: unsupervised stays true, unknown
9594                // becomes null so the client can tell the two apart. The
9595                // response field is already `Option<bool>`, so the wire can
9596                // carry that distinction today.
9597                let live = self
9598                    .process_liveness
9599                    .as_ref()
9600                    .and_then(|source| source.process_live(&module_id))
9601                    .unwrap_or(true);
9602                ClientControlResponse::RoutePoll {
9603                    route_channel,
9604                    route_epoch,
9605                    status: None,
9606                    live: Some(live),
9607                }
9608            }
9609            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9610                route_channel,
9611                route_epoch,
9612                status: None,
9613                live: Some(false),
9614            },
9615        };
9616
9617        Ok(vec![control_response_body_frame(
9618            &frame,
9619            &response,
9620            "ClientControlResponse::RoutePoll",
9621        )?])
9622    }
9623
9624    pub(crate) fn observe_module_control_completion(
9625        &self,
9626        completion: ModuleControlRpcCompletion,
9627    ) -> bool {
9628        match completion {
9629            ModuleControlRpcCompletion::Unknown => false,
9630            ModuleControlRpcCompletion::Settled => true,
9631            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9632                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9633                info!(
9634                    module_id = %module_id,
9635                    latency_ms,
9636                    "late health.check answer proves the module is alive"
9637                );
9638                match self
9639                    .supervisor
9640                    .record_late_health_answer(&module_id, latency_ms)
9641                {
9642                    Ok(true) => {}
9643                    Ok(false) => debug!(
9644                        module_id = %module_id,
9645                        latency_ms,
9646                        "late health.check answer has no active supervisor snapshot"
9647                    ),
9648                    Err(err) => warn!(
9649                        module_id = %module_id,
9650                        latency_ms,
9651                        error = %err,
9652                        "failed to record late health.check answer"
9653                    ),
9654                }
9655                true
9656            }
9657        }
9658    }
9659
9660    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9661    /// the module connection whose frame is being handled, or to the client that
9662    /// relay was opened for.
9663    ///
9664    /// This runs on the MODULE connection's frame handler, where returning `Err`
9665    /// ends that connection -- and a module connection carries every client's
9666    /// routes to that module, so ending it costs the whole fleet its tools.
9667    /// `ConnectionClosing` carries the id of the connection that is closing, and
9668    /// when that id is a CLIENT's, the condition is entirely about that one
9669    /// client's route.open. A client-scoped condition has no authority over a
9670    /// shared module connection, so it is logged and the single relay is dropped:
9671    /// the client is going away, and `complete_pending_relay` already removed the
9672    /// relay before failing, so there is nothing left to settle. Anything that
9673    /// relay still reserved is released by that client's own connection teardown,
9674    /// which is already under way -- that is what "closing" means.
9675    ///
9676    /// Every other failure is a statement about THIS connection and stays fatal:
9677    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9678    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9679    /// frames correctly.
9680    fn refuse_to_end_module_connection_for_a_client(
9681        &self,
9682        module_connection_id: ConnectionId,
9683        corr: u64,
9684        err: ForwardingError,
9685    ) -> Result<(), RouterError> {
9686        if let ForwardingError::ConnectionClosing { connection_id } = err {
9687            if connection_id != module_connection_id {
9688                warn!(
9689                    module_connection_id = module_connection_id.get(),
9690                    client_connection_id = connection_id.get(),
9691                    corr,
9692                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9693                );
9694                return Ok(());
9695            }
9696        }
9697        Err(RouterError::Forwarding(err))
9698    }
9699
9700    fn handle_module_relay_response(
9701        &self,
9702        connection_id: ConnectionId,
9703        frame: Frame,
9704    ) -> Result<Vec<Frame>, RouterError> {
9705        let mut secondary_error = None;
9706        let outcome = match frame.header.ty {
9707            FrameType::Response => match module_control_response_probe(&frame.body) {
9708                Ok(probe) if probe.op == "route.bind" => {
9709                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9710                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9711                            RouteBindRelayOutcome::Accepted
9712                        }
9713                        Ok(other) => {
9714                            let message =
9715                                format!("route.bind response carried unexpected body: {other:?}");
9716                            secondary_error = Some(control_error_frame(
9717                                &frame,
9718                                "invalid_control_body",
9719                                message.clone(),
9720                            )?);
9721                            RouteBindRelayOutcome::ModuleGone(message)
9722                        }
9723                        Err(err) => {
9724                            let message = format!("malformed route.bind response body: {err}");
9725                            secondary_error = Some(control_error_frame(
9726                                &frame,
9727                                "invalid_control_body",
9728                                message.clone(),
9729                            )?);
9730                            RouteBindRelayOutcome::ModuleGone(message)
9731                        }
9732                    }
9733                }
9734                Ok(probe) => {
9735                    let outcome = if matches!(
9736                        probe.op.as_str(),
9737                        "config.review" | "consent/v1" | "projects.enumerate"
9738                    ) {
9739                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9740                    } else {
9741                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9742                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9743                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9744                                "malformed {} response body: {err}",
9745                                probe.op
9746                            )),
9747                        }
9748                    };
9749                    let completion = self
9750                        .forwarding
9751                        .complete_module_control_rpc(
9752                            connection_id,
9753                            frame.header.corr,
9754                            Some(&probe.op),
9755                            outcome,
9756                        )
9757                        .map_err(RouterError::Forwarding)?;
9758                    if !self.observe_module_control_completion(completion) {
9759                        debug!(
9760                            connection_id = connection_id.get(),
9761                            corr = frame.header.corr,
9762                            op = %probe.op,
9763                            "dropping late or unknown module-control RPC response"
9764                        );
9765                    }
9766                    return Ok(Vec::new());
9767                }
9768                Err(err) => {
9769                    if let Some(expected_op) = self
9770                        .forwarding
9771                        .pending_module_control_op(connection_id, frame.header.corr)
9772                        .map_err(RouterError::Forwarding)?
9773                    {
9774                        let completion = self
9775                            .forwarding
9776                            .complete_module_control_rpc(
9777                                connection_id,
9778                                frame.header.corr,
9779                                None,
9780                                ModuleControlRpcOutcome::MalformedResponse(format!(
9781                                    "malformed {expected_op} response body: {err}"
9782                                )),
9783                            )
9784                            .map_err(RouterError::Forwarding)?;
9785                        if !self.observe_module_control_completion(completion) {
9786                            debug!(
9787                                connection_id = connection_id.get(),
9788                                corr = frame.header.corr,
9789                                "dropping late malformed module-control RPC response"
9790                            );
9791                        }
9792                        return Ok(Vec::new());
9793                    }
9794                    let message = format!("malformed route.bind response body: {err}");
9795                    secondary_error = Some(control_error_frame(
9796                        &frame,
9797                        "invalid_control_body",
9798                        message.clone(),
9799                    )?);
9800                    RouteBindRelayOutcome::ModuleGone(message)
9801                }
9802            },
9803            FrameType::Error => {
9804                if self
9805                    .forwarding
9806                    .pending_module_control_op(connection_id, frame.header.corr)
9807                    .map_err(RouterError::Forwarding)?
9808                    .is_some()
9809                {
9810                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9811                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9812                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9813                            "malformed module-control ERROR body: {err}"
9814                        )),
9815                    };
9816                    let completion = self
9817                        .forwarding
9818                        .complete_module_control_rpc(
9819                            connection_id,
9820                            frame.header.corr,
9821                            None,
9822                            outcome,
9823                        )
9824                        .map_err(RouterError::Forwarding)?;
9825                    if !self.observe_module_control_completion(completion) {
9826                        debug!(
9827                            connection_id = connection_id.get(),
9828                            corr = frame.header.corr,
9829                            "dropping late or unknown module-control RPC error"
9830                        );
9831                    }
9832                    return Ok(Vec::new());
9833                }
9834                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9835                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9836                    Err(err) => {
9837                        let message = format!("malformed route.bind ERROR body: {err}");
9838                        secondary_error = Some(control_error_frame(
9839                            &frame,
9840                            "invalid_control_body",
9841                            message.clone(),
9842                        )?);
9843                        RouteBindRelayOutcome::ModuleGone(message)
9844                    }
9845                }
9846            }
9847            ty => {
9848                return Ok(vec![control_error_frame(
9849                    &frame,
9850                    "unsupported_control_frame",
9851                    format!("unsupported module channel-0 frame {ty:?}"),
9852                )?])
9853            }
9854        };
9855
9856        let settled =
9857            self.forwarding
9858                .complete_pending_relay(connection_id, frame.header.corr, outcome);
9859        let completion = match settled {
9860            Ok(completion) => completion,
9861            Err(err) => {
9862                self.refuse_to_end_module_connection_for_a_client(
9863                    connection_id,
9864                    frame.header.corr,
9865                    err,
9866                )?;
9867                return Ok(secondary_error.into_iter().collect());
9868            }
9869        };
9870        if let Some(target) = completion.abandoned.as_ref() {
9871            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9872        }
9873        if !completion.settled {
9874            debug!(
9875                connection_id = connection_id.get(),
9876                corr = frame.header.corr,
9877                frame_type = ?frame.header.ty,
9878                "dropping late or unknown route.bind relay response"
9879            );
9880        }
9881        Ok(secondary_error.into_iter().collect())
9882    }
9883
9884    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9885        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9886        // GOODBYE ends the connection's logical session even when its socket
9887        // stays open. Use disconnect teardown so verdicts, client notices and
9888        // scope authority are released at the same lifecycle boundary.
9889        self.cleanup_connection_with_end_reason(
9890            connection_id,
9891            RegistrationEndReason::ExplicitGoodbye,
9892        )
9893        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9894        Ok(Vec::new())
9895    }
9896}
9897
9898impl Default for ControlHandler {
9899    fn default() -> Self {
9900        Self::new(Arc::new(Registry::default()))
9901    }
9902}
9903
9904impl crate::supervise::SwapPromotionObserver for ControlHandler {
9905    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9906        self.apply_registration_capabilities(registration);
9907    }
9908}
9909
9910fn capability_requirement_status(status: RequirementStatus) -> CapabilityRequirementStatus {
9911    CapabilityRequirementStatus {
9912        consumer: status.consumer,
9913        capability: status.capability,
9914        need: match status.need {
9915            subc_protocol::manifest::CapabilityNeed::Required => "required".to_string(),
9916            subc_protocol::manifest::CapabilityNeed::Optional => "optional".to_string(),
9917        },
9918        verdict: status.verdict.as_str().to_string(),
9919        episode_seq: status.episode_seq,
9920        config_satisfiable: status.config_satisfiable,
9921        runtime_available: status.runtime_available,
9922        detail: status.detail,
9923    }
9924}
9925
9926fn append_capability_problem_detail(
9927    detail: Option<String>,
9928    capability_detail: Option<String>,
9929) -> Option<String> {
9930    match (detail, capability_detail) {
9931        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9932        (Some(detail), None) => Some(detail),
9933        (None, Some(capability_detail)) => Some(capability_detail),
9934        (None, None) => None,
9935    }
9936}
9937
9938fn subc_ops() -> Vec<String> {
9939    SUBC_CONTROL_OPS
9940        .iter()
9941        .map(|op| (*op).to_string())
9942        .collect()
9943}
9944
9945fn module_subc_ops() -> Vec<String> {
9946    SUBC_CONTROL_OPS
9947        .iter()
9948        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9949        .map(|op| (*op).to_string())
9950        .collect()
9951}
9952
9953#[cfg(test)]
9954fn module_baseline_control_ops() -> Vec<String> {
9955    MODULE_BASELINE_CONTROL_OPS
9956        .iter()
9957        .map(|op| (*op).to_string())
9958        .collect()
9959}
9960
9961fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9962    let mut seen = HashSet::new();
9963    let mut effective = Vec::new();
9964    for op in MODULE_BASELINE_CONTROL_OPS {
9965        if seen.insert((*op).to_string()) {
9966            effective.push((*op).to_string());
9967        }
9968    }
9969    for op in declared.unwrap_or_default() {
9970        if seen.insert(op.clone()) {
9971            effective.push(op);
9972        }
9973    }
9974    effective
9975}
9976
9977fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9978    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9979}
9980
9981fn target_module_id(target: &RouteTarget) -> &str {
9982    match target {
9983        RouteTarget::ToolProvider { module_id }
9984        | RouteTarget::ManagementSurface { module_id }
9985        | RouteTarget::InternalService { module_id, .. } => module_id,
9986    }
9987}
9988
9989fn target_has_required_role(
9990    target: &RouteTarget,
9991    roles: &[crate::registry::AdmissionRole],
9992) -> bool {
9993    use crate::registry::AdmissionRole;
9994    roles.iter().any(|role| match (target, role) {
9995        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9996        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9997        (
9998            RouteTarget::InternalService { service_id, .. },
9999            AdmissionRole::InternalService(provided),
10000        ) => service_id == provided,
10001        _ => false,
10002    })
10003}
10004
10005fn is_routable_role(role: &ProviderRole) -> bool {
10006    matches!(
10007        role,
10008        ProviderRole::ToolProvider { .. }
10009            | ProviderRole::ManagementSurface { .. }
10010            | ProviderRole::InternalService { .. }
10011    )
10012}
10013
10014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10015enum ControlRequestBodyError {
10016    UnknownOp,
10017    InvalidBody,
10018}
10019
10020#[derive(Debug, Deserialize)]
10021struct ControlOpProbe {
10022    op: String,
10023}
10024
10025fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
10026    serde_json::from_slice(body).or_else(|original| {
10027        #[derive(Deserialize)]
10028        struct ConsentProbe {
10029            protocol: String,
10030        }
10031        match serde_json::from_slice::<ConsentProbe>(body) {
10032            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
10033                Ok(ControlOpProbe { op: probe.protocol })
10034            }
10035            _ => Err(original),
10036        }
10037    })
10038}
10039
10040/// Channel-0 push ops this subc version understands. A push whose `op` is not in
10041/// this set is treated as a forward-compat unknown and ignored rather than errored.
10042const MODULE_PUSH_OPS: &[&str] = &["route.status"];
10043
10044fn is_known_module_push_op(body: &[u8]) -> bool {
10045    serde_json::from_slice::<ControlOpProbe>(body)
10046        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
10047        .unwrap_or(false)
10048}
10049
10050fn is_known_module_request_op(body: &[u8]) -> bool {
10051    serde_json::from_slice::<ControlOpProbe>(body)
10052        .map(|probe| is_module_to_subc_op(&probe.op))
10053        .unwrap_or(false)
10054}
10055
10056fn is_module_to_subc_op(op: &str) -> bool {
10057    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
10058}
10059
10060fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
10061    debug!(
10062        op = %op,
10063        connection_id = connection_id.get(),
10064        corr,
10065        "control dispatch"
10066    );
10067}
10068
10069fn log_slow_control_dispatch(
10070    dispatch_started_at: Option<StdInstant>,
10071    op: &'static str,
10072    connection_id: ConnectionId,
10073    corr: u64,
10074    route_open_timings: Option<&RouteOpenTimings>,
10075) {
10076    let Some(dispatch_started_at) = dispatch_started_at else {
10077        return;
10078    };
10079    // Use the same monotonic clock as the phase timers and relay deadline.
10080    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
10081    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
10082        if let Some(timings) = route_open_timings {
10083            warn!(
10084                op = %op,
10085                connection_id = connection_id.get(),
10086                corr,
10087                elapsed_ms = elapsed.as_millis() as u64,
10088                module_id = ?timings.module_id,
10089                principal = %timings.principal,
10090                admission_ms = timings.admission.as_millis() as u64,
10091                project_root_ms = timings.project_root.as_millis() as u64,
10092                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
10093                bind_send_ms = timings.bind_send.as_millis() as u64,
10094                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
10095                "slow control dispatch"
10096            );
10097            return;
10098        }
10099        warn!(
10100            op = %op,
10101            connection_id = connection_id.get(),
10102            corr,
10103            elapsed_ms = elapsed.as_millis() as u64,
10104            "slow control dispatch"
10105        );
10106    }
10107}
10108
10109/// A test stand-in for the OS caller lookup, given the recorded endpoints.
10110#[cfg(test)]
10111type TestCallerLookup =
10112    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
10113
10114/// Every new client operation needs an explicit privilege decision here.
10115fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
10116    request.privileged_operation()
10117}
10118
10119trait PrivilegedRequest {
10120    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
10121}
10122
10123impl PrivilegedRequest for ClientControlRequest {
10124    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
10125        let request = self;
10126        match request {
10127        ClientControlRequest::SupervisorRestart { module_id, .. } => {
10128            Some(PrivilegedOperation::Restart { module_id })
10129        }
10130        ClientControlRequest::SupervisorSwap { module_id, .. } => {
10131            Some(PrivilegedOperation::Swap { module_id })
10132        }
10133        ClientControlRequest::SupervisorReload { module_id } => {
10134            Some(PrivilegedOperation::Reload { module_id })
10135        }
10136        ClientControlRequest::SupervisorRescan { preview } => {
10137            if *preview {
10138                None
10139            } else {
10140                Some(PrivilegedOperation::Rescan)
10141            }
10142        }
10143        // Only the well-formed apply asks for approval. A preview changes
10144        // nothing, and any other combination is refused before it touches
10145        // anything, so prompting the operator for it would ask about a request
10146        // that cannot run.
10147        ClientControlRequest::SupervisorRescanChecked {
10148            preview,
10149            candidate,
10150            expect,
10151        } => (!*preview && candidate.is_none() && expect.is_some())
10152            .then_some(PrivilegedOperation::Rescan),
10153        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
10154            Some(PrivilegedOperation::SetEnabled {
10155                module_id,
10156                enabled: *enabled,
10157            })
10158        }
10159        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
10160            Some(PrivilegedOperation::ReleaseReserved { module_id })
10161        }
10162        ClientControlRequest::ServerDescribe {}
10163        // The announcement uses the same client admission as supervisor.restart,
10164        // but cannot stop anything itself and needs no operator confirmation.
10165        | ClientControlRequest::DaemonShutdownIntent { .. }
10166        | ClientControlRequest::CatalogList { .. }
10167        | ClientControlRequest::RouteOpen { .. }
10168        | ClientControlRequest::RoutePoll { .. }
10169        | ClientControlRequest::SupervisorList {}
10170        | ClientControlRequest::SupervisorHealth {}
10171        | ClientControlRequest::SupervisorHealthProbe { .. }
10172        | ClientControlRequest::SupervisorRoutes { .. }
10173        | ClientControlRequest::SupervisorProvenance { .. }
10174        | ClientControlRequest::SupervisorStderrTail { .. }
10175        | ClientControlRequest::SupervisorTerminals { .. }
10176        | ClientControlRequest::SupervisorSpawnSnapshot {}
10177        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
10178    }
10179    }
10180}
10181
10182fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
10183    match request {
10184        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
10185        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
10186        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
10187        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
10188        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
10189        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
10190        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
10191        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
10192        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
10193        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
10194        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
10195        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
10196        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
10197        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
10198        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
10199        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
10200        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
10201        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
10202        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
10203        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
10204        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
10205    }
10206}
10207
10208/// The caller of one `route.open`, as its `route.open refused` line names it.
10209///
10210/// A connection id alone cannot name a caller after the fact: ids restart at
10211/// every daemon restart, so the same number belongs to different modules
10212/// before and after one. These three fields are what the refused line needs
10213/// to be attributable on its own, and they are rendered with the same helpers
10214/// as the `route.open accepted` line so both directions grep alike.
10215struct RouteOpenCaller {
10216    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
10217    /// when the request presented a consumer identity whose launch nonce did
10218    /// not verify. The claimed module id is never printed as a principal.
10219    principal: String,
10220    /// `none` for an unscoped open; the admitted stamp's label once scope
10221    /// admission issued one; before that, the requested selector's label.
10222    scope: String,
10223    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
10224    /// because it is a string the caller chose.
10225    harness: String,
10226}
10227
10228impl RouteOpenCaller {
10229    fn new(
10230        principal: Option<&Principal>,
10231        scope: Option<&ScopeSelector>,
10232        identity: &BindIdentity,
10233    ) -> Self {
10234        Self {
10235            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
10236            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
10237            harness: bounded_log_text(&identity.harness),
10238        }
10239    }
10240
10241    /// For a refusal that has no parsed request at hand: names whatever the
10242    /// frame still says, and `unknown` where it says nothing parseable.
10243    fn unknown() -> Self {
10244        Self {
10245            principal: "unknown".to_string(),
10246            scope: "unknown".to_string(),
10247            harness: "unknown".to_string(),
10248        }
10249    }
10250}
10251
10252/// Longest client-chosen text (a scope ref, a harness) a route.open log line
10253/// prints before cutting it.
10254const MAX_LOGGED_TEXT_CHARS: usize = 64;
10255
10256/// `value` Debug-quoted, so control characters land escaped and cannot forge
10257/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
10258/// `…` inside the quotes so one request cannot flood the line.
10259fn bounded_log_text(value: &str) -> String {
10260    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
10261    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
10262        bounded.push('…');
10263    }
10264    format!("{bounded:?}")
10265}
10266
10267/// The `scope=` field of the `route.open accepted` line, from the stamp that
10268/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
10269/// so a ref holding control characters cannot forge a log line, and cut to 64
10270/// characters with a trailing `…` to bound the line. The bind proof and the
10271/// scope's attributes never appear.
10272fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
10273    use subc_protocol::scope::ScopeKind;
10274    let kind = match stamp.kind {
10275        ScopeKind::Head => "head",
10276        ScopeKind::Worker => "worker",
10277        ScopeKind::Ephemeral => "ephemeral",
10278        ScopeKind::Federated => "federated",
10279        _ => "unknown",
10280    };
10281    format!(
10282        "{kind}/{}/{}@{}",
10283        principal_label(&stamp.owner),
10284        bounded_log_text(&stamp.scope_ref),
10285        stamp.scope_epoch
10286    )
10287}
10288
10289/// The `scope=` field of a `route.open refused` line for an open refused
10290/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
10291/// The kind is not known yet, so the literal `requested` stands in its place.
10292/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
10293/// owner it has not been checked against the configured modules: a quoted
10294/// owner means the value was never validated. The bind proof never appears.
10295fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10296    let epoch = selector
10297        .scope_epoch
10298        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10299    format!(
10300        "requested/{}/{}@{epoch}",
10301        bounded_log_text(&principal_label(&selector.owner)),
10302        bounded_log_text(&selector.scope_ref),
10303    )
10304}
10305
10306fn principal_label(principal: &Principal) -> String {
10307    match principal {
10308        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10309        Principal::Direct => "direct".to_string(),
10310        other => format!("{other:?}"),
10311    }
10312}
10313
10314fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10315    match request {
10316        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10317        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10318            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10319        }
10320        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10321        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10322        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10323        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10324        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10325            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10326        }
10327        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10328        _ => "unsupported",
10329    }
10330}
10331
10332fn parse_client_control_request(
10333    body: &[u8],
10334) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10335    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10336        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10337            Ok(probe)
10338                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10339                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10340            {
10341                ControlRequestBodyError::InvalidBody
10342            }
10343            Ok(_) => ControlRequestBodyError::UnknownOp,
10344            Err(_) => ControlRequestBodyError::InvalidBody,
10345        };
10346        (err, classification)
10347    })
10348}
10349
10350fn parse_module_control_request_from_module(
10351    body: &[u8],
10352) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10353    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10354        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10355            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10356            Ok(_) => ControlRequestBodyError::UnknownOp,
10357            Err(_) => ControlRequestBodyError::InvalidBody,
10358        };
10359        (err, classification)
10360    })
10361}
10362
10363#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10364enum ProviderRoleKind {
10365    ToolProvider,
10366    PipelineStage,
10367    ManagementSurface,
10368    InternalService,
10369}
10370
10371fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10372    match role {
10373        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10374        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10375        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10376        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10377    }
10378}
10379
10380fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10381    roles.iter().map(provider_role_kind).collect()
10382}
10383
10384/// Most refused scope records named individually in the log per sync; the
10385/// `refused` count on the accepted line is always complete.
10386const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10387
10388/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10389#[derive(Debug, Default, PartialEq, Eq)]
10390struct ScopeOutcomeCounts {
10391    created: usize,
10392    replaced: usize,
10393    updated: usize,
10394    unchanged: usize,
10395    refused: usize,
10396}
10397
10398impl ScopeOutcomeCounts {
10399    fn of(results: &[ScopeRecordResult]) -> Self {
10400        let mut counts = Self::default();
10401        for result in results {
10402            let slot = match result.outcome {
10403                ScopeRecordOutcome::Created => &mut counts.created,
10404                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10405                ScopeRecordOutcome::Updated => &mut counts.updated,
10406                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10407                ScopeRecordOutcome::Refused => &mut counts.refused,
10408            };
10409            *slot += 1;
10410        }
10411        counts
10412    }
10413}
10414
10415#[cfg(test)]
10416mod scope_outcome_count_tests {
10417    use super::*;
10418
10419    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10420        ScopeRecordResult {
10421            scope_ref: "r".to_string(),
10422            scope_epoch: 1,
10423            outcome,
10424            code: None,
10425            message: None,
10426            version: None,
10427            parent_state: None,
10428        }
10429    }
10430
10431    /// Each outcome lands in its own count, so a refused record can never be
10432    /// hidden inside the total the log already printed.
10433    #[test]
10434    fn every_outcome_is_counted_in_its_own_field() {
10435        let results = [
10436            result(ScopeRecordOutcome::Created),
10437            result(ScopeRecordOutcome::Created),
10438            result(ScopeRecordOutcome::Replaced),
10439            result(ScopeRecordOutcome::Updated),
10440            result(ScopeRecordOutcome::Unchanged),
10441            result(ScopeRecordOutcome::Refused),
10442            result(ScopeRecordOutcome::Refused),
10443            result(ScopeRecordOutcome::Refused),
10444        ];
10445        assert_eq!(
10446            ScopeOutcomeCounts::of(&results),
10447            ScopeOutcomeCounts {
10448                created: 2,
10449                replaced: 1,
10450                updated: 1,
10451                unchanged: 1,
10452                refused: 3,
10453            }
10454        );
10455    }
10456}
10457
10458/// Return whether a catalog change can create a newly violating live route.
10459/// Removing an attested claim is intentionally excluded: it makes fewer routes
10460/// forbidden and therefore must leave the existing route census untouched.
10461fn capability_census_trigger(
10462    old: Option<&CapabilityDeclarations>,
10463    new: Option<&CapabilityDeclarations>,
10464) -> bool {
10465    let old_provides = old
10466        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10467        .unwrap_or_default();
10468    let old_denies = old
10469        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10470        .unwrap_or_default();
10471    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10472        provides: Vec::new(),
10473        requires: Vec::new(),
10474        must_never_reach: Vec::new(),
10475    });
10476
10477    new.provides
10478        .iter()
10479        .any(|capability| !old_provides.contains(capability))
10480        || new
10481            .must_never_reach
10482            .iter()
10483            .any(|capability| !old_denies.contains(capability))
10484}
10485
10486fn catalog_update_frozen_field_message(
10487    registered: &ModuleManifest,
10488    provides: &[ProviderRole],
10489) -> Option<String> {
10490    let old_has_provides = !registered.provides.is_empty();
10491    let new_has_provides = !provides.is_empty();
10492    if old_has_provides != new_has_provides {
10493        return Some(format!(
10494            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10495            registered.module_id
10496        ));
10497    }
10498
10499    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10500        return Some(format!(
10501            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10502            registered.module_id
10503        ));
10504    }
10505
10506    let registered_concurrency = manifest_concurrency(registered);
10507    let mut candidate = registered.clone();
10508    candidate.provides = provides.to_vec();
10509    let candidate_concurrency = manifest_concurrency(&candidate);
10510    if candidate_concurrency != registered_concurrency {
10511        return Some(format!(
10512            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10513            registered.module_id, registered_concurrency, candidate_concurrency
10514        ));
10515    }
10516
10517    // control_ops live beside the manifest in the HELLO body, not inside
10518    // ModuleManifest, so a provides-only catalog.update cannot change them.
10519    None
10520}
10521
10522fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10523    manifest.provides.iter().any(is_routable_role)
10524}
10525
10526/// Returns the routable-provider concurrency subc should enforce for this manifest.
10527///
10528/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10529/// InternalService has no role-specific concurrency field, so it retains the
10530/// existing ModuleManaged default for backward compatibility.
10531fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10532    manifest
10533        .provides
10534        .iter()
10535        .find_map(|provider| match provider {
10536            ProviderRole::ToolProvider { concurrency, .. }
10537            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10538            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10539        })
10540        .unwrap_or(Concurrency::ModuleManaged)
10541}
10542
10543/// True when the manifest carries a ManagementSurface role whose concurrency
10544/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10545/// bytes because the typed manifest deliberately erases that distinction: the
10546/// default exists for wire compatibility, and this probe exists so the default
10547/// stays observable. Any parse irregularity returns false -- the caller only
10548/// logs, and a malformed body already failed registration upstream.
10549fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10550    let has_management_surface = manifest
10551        .provides
10552        .iter()
10553        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10554    if !has_management_surface {
10555        return false;
10556    }
10557    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10558        return false;
10559    };
10560    let Some(provides) = raw
10561        .get("manifest")
10562        .and_then(|manifest| manifest.get("provides"))
10563        .and_then(serde_json::Value::as_array)
10564    else {
10565        return false;
10566    };
10567    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10568    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10569    // against the management_surface_manifest_without_concurrency golden, not
10570    // recalled (the externally-tagged guess was this function's first bug).
10571    provides.iter().any(|role| {
10572        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10573            && role.get("concurrency").is_none()
10574    })
10575}
10576
10577fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10578    if peer_version != PROTOCOL_VERSION {
10579        return Err(format!(
10580            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10581        ));
10582    }
10583    Ok(PROTOCOL_VERSION)
10584}
10585
10586fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10587    Frame::build_with_version(
10588        response_version(frame),
10589        FrameType::Pong,
10590        frame.header.flags,
10591        0,
10592        0,
10593        frame.header.corr,
10594        Vec::new(),
10595    )
10596    .map_err(RouterError::FrameBuild)
10597}
10598
10599pub(crate) fn control_error_frame(
10600    frame: &Frame,
10601    code: &'static str,
10602    message: impl Into<String>,
10603) -> Result<Frame, RouterError> {
10604    control_error_body_frame(
10605        frame,
10606        ErrorBody {
10607            code: code.to_string(),
10608            message: message.into(),
10609            detail: None,
10610        },
10611    )
10612}
10613
10614/// A channel-0 ERROR for a refusal the daemon decided itself: every
10615/// route.open refusal, the drain `module_reloading` and scope-change/end
10616/// bodies, spawn-subscription and supervisor refusals. Carries the
10617/// daemon-origin bit, which is what lets a client treat `module_reloading`
10618/// as proof that its request never reached a module. Response, push,
10619/// goodbye and relay-request frames keep the plain control flags in their
10620/// own builders.
10621pub(crate) fn control_error_body_frame(
10622    frame: &Frame,
10623    error: ErrorBody,
10624) -> Result<Frame, RouterError> {
10625    control_error_frame_with_flags(frame, error, daemon_error_flags())
10626}
10627
10628/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10629/// refused route.bind answered as a route.open refusal, or a refused
10630/// module-control RPC. Plain control flags — the code and message are
10631/// module-chosen, so the frame must not claim daemon authorship, even when
10632/// the module picks a daemon code like `module_reloading`.
10633fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10634    control_error_frame_with_flags(frame, error, control_flags())
10635}
10636
10637fn control_error_frame_with_flags(
10638    frame: &Frame,
10639    error: ErrorBody,
10640    flags: Flags,
10641) -> Result<Frame, RouterError> {
10642    let body = serde_json::to_vec(&error).map_err(|err| {
10643        RouterError::backend(
10644            0,
10645            frame.header.corr,
10646            format!("failed to encode control ERROR: {err}"),
10647        )
10648    })?;
10649
10650    Frame::build_with_version(
10651        response_version(frame),
10652        FrameType::Error,
10653        flags,
10654        0,
10655        0,
10656        frame.header.corr,
10657        body,
10658    )
10659    .map_err(RouterError::FrameBuild)
10660}
10661
10662pub(crate) fn control_response_body_frame<T: Serialize>(
10663    frame: &Frame,
10664    reply: &T,
10665    label: &'static str,
10666) -> Result<Frame, RouterError> {
10667    let body = serde_json::to_vec(reply).map_err(|err| {
10668        RouterError::backend(
10669            0,
10670            frame.header.corr,
10671            format!("failed to encode {label}: {err}"),
10672        )
10673    })?;
10674
10675    Frame::build_with_version(
10676        response_version(frame),
10677        FrameType::Response,
10678        control_flags(),
10679        0,
10680        0,
10681        frame.header.corr,
10682        body,
10683    )
10684    .map_err(RouterError::FrameBuild)
10685}
10686
10687/// Map a forwarding failure to the wire code a client sees.
10688///
10689/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10690/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10691/// chosen here decides whether a caller retries or gives up.
10692///
10693/// That makes attribution the load-bearing property, not merely having a code. A
10694/// permanent fault published as a retryable one produces a fleet-wide retry storm
10695/// against something that can never recover; a transient fault published as
10696/// permanent gives up on work that would have succeeded. Both look correct in a
10697/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10698/// the mapping per variant rather than merely asserting that some code exists.
10699///
10700/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10701/// two codes on the same side of the boundary passes it. Measured rather than
10702/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10703/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10704/// a test named for something else that happens to assert the string.
10705///
10706/// That accidental coverage is deliberately left alone rather than promoted to a
10707/// named test, because it guards a property this function does not promise.
10708/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10709/// specific code within a class, so identity is free to change and only the
10710/// partition is a contract. Splitting it out would assert a guarantee nothing
10711/// depends on — and a suite that promises more than the code does is the harder
10712/// thing to correct later, because the next reader cannot tell which assertions
10713/// are load-bearing.
10714///
10715/// Pin identity here the moment a consumer branches on a specific code.
10716/// The spawn a HELLO would register as and the provider declarations it
10717/// requests, carried from the HELLO's checks to the point the registry
10718/// accepts it.
10719struct HelloAuthority {
10720    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10721    requested: ProviderDeclarations,
10722    /// Whether admitting this HELLO froze the spawn's requested declarations,
10723    /// so a refusal after admission undoes that freeze and no other.
10724    froze: std::sync::atomic::AtomicBool,
10725}
10726
10727fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10728    match err {
10729        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10730        ForwardingError::NoModuleConnection => "target_unavailable",
10731        ForwardingError::ModuleReloading { .. } => "module_reloading",
10732        ForwardingError::ClientRouteChannelExhausted { .. }
10733        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10734        ForwardingError::StaleModuleEndpoint
10735        | ForwardingError::UnknownReservation { .. }
10736        | ForwardingError::ConnectionClosing { .. }
10737        | ForwardingError::ClientEgressClosed { .. }
10738        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10739        // Only a swap candidate's registration can produce this, and it means
10740        // exactly what a second active HELLO for a live id means.
10741        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10742        ForwardingError::RelayCorrelationExhausted
10743        | ForwardingError::RouteOpenBuild(_)
10744        | ForwardingError::Poisoned => "forwarding_error",
10745    }
10746}
10747
10748fn response_version(frame: &Frame) -> u8 {
10749    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10750        frame.header.ver
10751    } else {
10752        PROTOCOL_VERSION
10753    }
10754}
10755
10756pub(crate) fn control_flags() -> Flags {
10757    Flags::new(false, Priority::Passive, false)
10758}
10759
10760/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10761/// channel. The target is the module (a client never saw the route), so this
10762/// takes the module path: delivered late rather than dropped when the module's
10763/// queue is momentarily full, and never closing its connection.
10764fn send_goodbye_target_best_effort(
10765    counters: &DaemonCounters,
10766    target: &GoodbyeTarget,
10767    context: &'static str,
10768) {
10769    let Ok(frame) = Frame::build_with_version(
10770        target.negotiated_ver,
10771        FrameType::Goodbye,
10772        control_flags(),
10773        target.channel,
10774        target.epoch,
10775        0,
10776        Vec::new(),
10777    ) else {
10778        return;
10779    };
10780    crate::forwarding::send_module_route_goodbye(
10781        counters,
10782        &target.sink,
10783        frame,
10784        target.module_id.as_deref(),
10785        context,
10786    );
10787}
10788
10789fn route_close_reason_for_opener(
10790    reason: RouteCloseReason,
10791    accepts_close_reasons: Option<&[String]>,
10792) -> RouteCloseReason {
10793    if reason == RouteCloseReason::AuthorityChanged
10794        && !accepts_close_reasons
10795            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10796    {
10797        // Older readers forbid reopening for unknown reasons. Reload already
10798        // permits reopening and, like an authority change, requires a new bind.
10799        RouteCloseReason::Reload
10800    } else {
10801        reason
10802    }
10803}
10804
10805pub(crate) fn send_route_control_pushes(
10806    forwarding: &ForwardingTable,
10807    routes: Vec<EndpointRoute>,
10808    push: ClientControlPush,
10809) {
10810    let reason = match &push {
10811        ClientControlPush::RouteClosing { reason, .. }
10812        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10813    };
10814    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10815    for route in routes {
10816        let recipient_reason =
10817            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10818        let target = route.goodbye_target;
10819        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10820            existing.connection_id == target.connection_id && *reason == recipient_reason
10821        }) {
10822            debug_assert_eq!(
10823                existing.negotiated_ver, target.negotiated_ver,
10824                "one connection cannot negotiate multiple frame versions"
10825            );
10826            if !channels.contains(&target.channel) {
10827                channels.push(target.channel);
10828            }
10829            continue;
10830        }
10831        let channel = target.channel;
10832        targets.push((target, recipient_reason, vec![channel]));
10833    }
10834    for (target, recipient_reason, mut channels) in targets {
10835        channels.sort_unstable();
10836        let mut push = push.clone();
10837        match &mut push {
10838            ClientControlPush::RouteClosing {
10839                channels: covered,
10840                reason,
10841                ..
10842            }
10843            | ClientControlPush::RouteClosed {
10844                channels: covered,
10845                reason,
10846                ..
10847            } => {
10848                *covered = channels;
10849                *reason = recipient_reason;
10850            }
10851        }
10852        let body = match serde_json::to_vec(&push) {
10853            Ok(body) => body,
10854            Err(err) => {
10855                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10856                continue;
10857            }
10858        };
10859        let frame = match Frame::build_with_version(
10860            target.negotiated_ver,
10861            FrameType::Push,
10862            control_flags(),
10863            0,
10864            0,
10865            0,
10866            body.clone(),
10867        ) {
10868            Ok(frame) => frame,
10869            Err(err) => {
10870                warn!(
10871                    route_channel = target.channel,
10872                    error = %err,
10873                    "failed to build route lifecycle control PUSH frame"
10874                );
10875                continue;
10876            }
10877        };
10878        if let Err(err) = target.sink.try_send(frame) {
10879            if target.close_on_delivery_failure() {
10880                warn!(
10881                    target_connection_id = target.connection_id.get(),
10882                    route_channel = target.channel,
10883                    error = %err,
10884                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10885                );
10886                let _ = forwarding.escalate_client_delivery_failure(
10887                    target.connection_id,
10888                    target.channel,
10889                    target.epoch,
10890                    CloseReason::new(
10891                        "route_lifecycle_push_delivery_failed",
10892                        format!(
10893                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10894                            target.channel
10895                        ),
10896                    ),
10897                    crate::forwarding::UndeliveredFrame {
10898                        module_id: target.module_id.as_deref(),
10899                        sink: &target.sink,
10900                    },
10901                );
10902            }
10903        }
10904    }
10905}
10906
10907#[cfg(test)]
10908mod tests {
10909    include!("control/agent_commands_tests.rs");
10910    include!("control/supervisor_health_vectors_tests.rs");
10911    include!("control/resource_revision_tests.rs");
10912    include!("control/route_open_recovery_tests.rs");
10913    #[tokio::test]
10914    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10915        let registry = Arc::new(Registry::default());
10916        let handler = ControlHandler::new(registry);
10917        assert_eq!(
10918            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10919            None
10920        );
10921        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10922        hello_via_sink(
10923            &handler,
10924            &ctx,
10925            &mut rx,
10926            hello_frame("daemon", PROTOCOL_VERSION, 1),
10927        )
10928        .await;
10929        assert_eq!(
10930            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10931            Some("daemon".into())
10932        );
10933        assert_eq!(
10934            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10935            None
10936        );
10937        assert_eq!(
10938            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10939            None,
10940            "a registered module is not necessarily supervised"
10941        );
10942        assert_eq!(
10943            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10944            None,
10945            "aggregate provenance has no single target"
10946        );
10947        assert_eq!(
10948            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10949            None
10950        );
10951    }
10952
10953    mod peer_manifest {
10954        include!("peer_manifest_tests.rs");
10955    }
10956    mod catalog_declarations {
10957        include!("control/catalog_tests.rs");
10958    }
10959    mod activity_read {
10960        include!("activity_read_tests.rs");
10961    }
10962
10963    mod lifecycle_activity {
10964        include!("control_lifecycle_tests.rs");
10965    }
10966    #[cfg(unix)]
10967    #[tokio::test]
10968    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10969        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10970        let path = dir.join("subc.jsonc");
10971        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10972            "program":"/bin/sleep","args":["60"],"protocol":"none",
10973            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10974        }}}).to_string()).unwrap();
10975        let mut configured = crate::daemon_config::load(&path)
10976            .unwrap()
10977            .unwrap()
10978            .modules
10979            .pop()
10980            .unwrap();
10981        let registry = std::sync::Arc::new(crate::Registry::default());
10982        let handle = crate::SupervisorHandle::new();
10983        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10984            .with_handle(handle.clone());
10985        let module = supervisor
10986            .supervise_configured_with_health(
10987                configured.module_spec(),
10988                true,
10989                configured.health.clone(),
10990                None,
10991                configured.restart,
10992            )
10993            .unwrap();
10994        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10995        let before = module.status().unwrap().pid;
10996        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10997        configured.health.cadence = std::time::Duration::from_secs(3600);
10998        let health_only = handler
10999            .reconcile_supervised_modules(
11000                &supervisor,
11001                vec![configured.clone()],
11002                false,
11003                Principal::Direct,
11004            )
11005            .await
11006            .unwrap();
11007        assert!(
11008            health_only.0.changed_pending_reload.is_empty(),
11009            "health policy is already applied live"
11010        );
11011        assert_eq!(module.status().unwrap().pid, before);
11012        assert_eq!(
11013            module.configuration().unwrap().1.http,
11014            configured.health.http
11015        );
11016        configured.args = vec!["61".into()];
11017        let launch = handler
11018            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
11019            .await
11020            .unwrap();
11021        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
11022        assert_eq!(
11023            module.status().unwrap().pid,
11024            before,
11025            "a launch edit is stored until reload"
11026        );
11027        module.drain().await.unwrap();
11028    }
11029    use cortexkit_test_support::ScratchDir;
11030    use std::{
11031        collections::BTreeMap,
11032        fmt,
11033        path::PathBuf,
11034        sync::{Arc, Mutex},
11035        time::Duration,
11036    };
11037
11038    use serde_json::{json, Value};
11039    use subc_protocol::{
11040        manifest::{
11041            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
11042            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
11043        },
11044        session::HealthStatus,
11045        FrameType,
11046    };
11047
11048    use super::*;
11049    use crate::{
11050        forwarding::{DataRoute, DataRouteState},
11051        registry::ChannelState,
11052        router::FrameSink,
11053        stderr_tail::DEFAULT_MAX_LINE_BYTES,
11054        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
11055        RouteCtx, Router,
11056    };
11057    use tokio::{
11058        sync::mpsc,
11059        time::{sleep, Instant},
11060    };
11061    use tracing::{
11062        field::{Field, Visit},
11063        Event, Subscriber,
11064    };
11065    use tracing_subscriber::{layer::Context, prelude::*, Layer};
11066
11067    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
11068    ///
11069    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
11070    /// is only populated for `tests/*.rs` integration test binaries -- this file
11071    /// compiles as part of the library target, which gets neither. The binary
11072    /// lives in the profile folder this test was built into,
11073    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
11074    /// from the test's own path.
11075    ///
11076    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
11077    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
11078    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
11079    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
11080    /// `NotFound`, which reads as a broken test rather than an unbuilt
11081    /// dependency -- so state the cause and the remedy instead. Deliberately a
11082    /// panic and not a silent skip: a test that quietly passes when it could not
11083    /// run is worse than one that fails, because it reports health it never
11084    /// verified.
11085    fn fake_aft_stub_path() -> PathBuf {
11086        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
11087        assert!(
11088            path.exists(),
11089            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
11090             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
11091            path.display()
11092        );
11093        path
11094    }
11095
11096    /// Whether clients retry `code` in place: the predicate itself, never a copy
11097    /// of its set. A copied list breaks silently when a code is added to or
11098    /// removed from the real one, and a stale copy here would let exactly the
11099    /// failure this test exists to catch pass.
11100    fn client_retries(code: &str) -> bool {
11101        subc_protocol::error_codes::is_retryable_route_open(code)
11102    }
11103
11104    /// A code is not a label — clients branch on it, so publishing the wrong KIND
11105    /// of failure is worse than publishing none. A permanent fault dressed as
11106    /// retryable makes every client in the fleet retry forever against something
11107    /// that cannot recover; a transient fault dressed as permanent abandons work
11108    /// that would have succeeded.
11109    ///
11110    /// Asserting "a code exists" cannot catch either, because the string is free
11111    /// to say anything. This enumerates every variant and pins which side of the
11112    /// retry boundary it lands on, so a new variant must be classified here
11113    /// deliberately rather than inheriting whichever arm it was appended to.
11114    #[test]
11115    fn retryability_of_forwarding_codes_matches_the_failure() {
11116        // Transient by nature: the target is booting, reloading, or its endpoint
11117        // was swapped mid-flight. Retrying is how these resolve.
11118        let transient = [
11119            ForwardingError::NoModuleConnection,
11120            ForwardingError::ModuleReloading {
11121                module_id: "m".into(),
11122            },
11123            ForwardingError::StaleModuleEndpoint,
11124            ForwardingError::UnknownReservation {
11125                client_channel: 1,
11126                module_channel: 1,
11127            },
11128            ForwardingError::ConnectionClosing {
11129                connection_id: ConnectionId::new(1),
11130            },
11131            ForwardingError::ClientEgressClosed {
11132                connection_id: ConnectionId::new(1),
11133            },
11134            ForwardingError::ModuleEgressUnavailable {
11135                connection_id: ConnectionId::new(1),
11136            },
11137        ];
11138        for err in transient {
11139            let code = forwarding_error_code(&err);
11140            assert!(
11141                client_retries(code),
11142                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
11143            );
11144        }
11145
11146        // Not fixed by retrying. Channel and correlation exhaustion need the
11147        // caller to close routes, and a poisoned lock is a daemon that cannot
11148        // recover at all — the worst thing to advertise as retryable, since every
11149        // client would storm a daemon that will never answer.
11150        let permanent = [
11151            ForwardingError::ConnectionRoleConflict {
11152                connection_id: ConnectionId::new(1),
11153            },
11154            ForwardingError::ClientRouteChannelExhausted {
11155                connection_id: ConnectionId::new(1),
11156            },
11157            ForwardingError::ModuleRouteChannelExhausted {
11158                endpoint: ModuleEndpointId {
11159                    connection_id: ConnectionId::new(1),
11160                    generation: 1,
11161                },
11162            },
11163            ForwardingError::RelayCorrelationExhausted,
11164            ForwardingError::RouteOpenBuild("x".into()),
11165            ForwardingError::Poisoned,
11166        ];
11167        for err in permanent {
11168            let code = forwarding_error_code(&err);
11169            assert!(
11170                !client_retries(code),
11171                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
11172            );
11173        }
11174    }
11175
11176    /// The principal is the daemon's answer to "who is calling", and modules
11177    /// branch on it: aft gates bash on it, cerebellum gates browser control,
11178    /// plexus gates connector invocation. So a stamp is an authorization input in
11179    /// another process, not a label — and both possible answers SUCCEED, which is
11180    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
11181    /// first-party capability to something that never proved it; a supervised one
11182    /// stamped `Direct` silently strips a module of capability it is entitled to.
11183    ///
11184    /// Neither shows up in a test that only checks the bind succeeded. Before this
11185    /// test the only coverage was accidental —
11186    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
11187    /// stamped principal on its way past, so narrowing that wire-shape test to its
11188    /// stated subject would have deleted the last assertion on this value. It
11189    /// still asserts the stamp, which is now redundancy rather than the only
11190    /// guard: both fail under the same mutation, and this one names the reason.
11191    /// SCOPE: this handler's supervisor has spawned nothing, so
11192    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
11193    /// is unreachable here. Both assertions below are refusals, and a mutant that
11194    /// refuses everything would satisfy them.
11195    ///
11196    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
11197    /// spawns a supervised consumer, reads its live nonce, and asserts the module
11198    /// observed `principal.kind == "reserved"` carrying that module_id — verified
11199    /// at source rather than assumed, since a citation is a claim about another
11200    /// file and ages like one. Recorded because a harness that structurally
11201    /// cannot reach an arm reports "none" for that arm identically to one that
11202    /// covers it and found nothing.
11203    #[tokio::test]
11204    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
11205        let handler = ControlHandler::default();
11206        let frame =
11207            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
11208
11209        // Absent consumer_identity is the ordinary case: a human at a terminal, or
11210        // any process holding the connection file. Nothing was proved, so nothing
11211        // may be granted beyond the unattested floor.
11212        let stamped = handler
11213            .route_open_principal(ConnectionId::new(1), &frame, None)
11214            .unwrap()
11215            .unwrap();
11216        assert_eq!(
11217            stamped,
11218            Principal::Direct,
11219            "a caller that proved nothing must not be stamped as a supervised module"
11220        );
11221
11222        // A claimed module_id with a nonce no supervised child was given is a
11223        // forgery attempt, not a weaker caller: it must be REFUSED rather than
11224        // quietly demoted to Direct, or an impersonation attempt looks identical
11225        // to an ordinary unattested connection.
11226        let forged = handler
11227            .route_open_principal(
11228                ConnectionId::new(1),
11229                &frame,
11230                Some(ConsumerIdentity {
11231                    module_id: "aft".to_string(),
11232                    launch_nonce: "not-a-real-nonce".to_string(),
11233                }),
11234            )
11235            .unwrap();
11236        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
11237        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
11238    }
11239
11240    /// The test above hands `route_open_principal` an identity it built itself,
11241    /// which proves the stamping rule and nothing about where the identity comes
11242    /// from. The real producer is a wire body, and the two are joined by a serde
11243    /// field name that nothing else asserts.
11244    ///
11245    /// That join fails quietly in one specific way: an unrecognised key is simply
11246    /// absent after parsing, so a renamed or misspelled `consumer_identity`
11247    /// yields `None` and every supervised module silently drops to `Direct`.
11248    /// Capability-wise that is the safe direction, but it surfaces far from its
11249    /// cause — as a module mysteriously refused bash — and it would pass every
11250    /// test that builds its own input.
11251    ///
11252    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
11253    /// would break every client the moment the daemon gains a field, trading a
11254    /// quiet demotion for a hard refusal on additive change. Asserting the join
11255    /// instead means a rename breaks a test here rather than the fleet.
11256    #[test]
11257    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
11258        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"}}"#;
11259        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
11260        let ClientControlRequest::RouteOpen {
11261            consumer_identity, ..
11262        } = parsed
11263        else {
11264            panic!("route.open body must parse as RouteOpen");
11265        };
11266        assert_eq!(
11267            consumer_identity,
11268            Some(ConsumerIdentity {
11269                module_id: "aft".to_string(),
11270                launch_nonce: "n".to_string(),
11271            }),
11272            "the wire field name must reach the value route_open_principal reads"
11273        );
11274    }
11275
11276    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
11277        ModuleManifest::builder(module_id, "0.1.0")
11278            .protocol_ver(protocol_ver)
11279            .provides(vec![ProviderRole::ToolProvider {
11280                tools: vec![Tool {
11281                    name: "read".to_string(),
11282                    description: None,
11283                    execution_mode: ExecutionMode::Pure,
11284                    schema: json!({"type": "object"}),
11285                }],
11286                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
11287                concurrency: Concurrency::ModuleManaged,
11288                emits_push: true,
11289                sub_supervises: true,
11290            }])
11291            .build()
11292    }
11293
11294    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11295        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11296    }
11297
11298    fn hello_frame_with_control_ops(
11299        module_id: &str,
11300        protocol_ver: u8,
11301        corr: u64,
11302        control_ops: Option<Vec<String>>,
11303    ) -> Frame {
11304        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11305    }
11306
11307    fn hello_frame_with_nonce(
11308        module_id: &str,
11309        protocol_ver: u8,
11310        corr: u64,
11311        launch_nonce: Option<&str>,
11312    ) -> Frame {
11313        hello_frame_full(
11314            module_id,
11315            protocol_ver,
11316            corr,
11317            None,
11318            launch_nonce.map(ToOwned::to_owned),
11319        )
11320    }
11321
11322    fn hello_frame_full(
11323        module_id: &str,
11324        protocol_ver: u8,
11325        corr: u64,
11326        control_ops: Option<Vec<String>>,
11327        launch_nonce: Option<String>,
11328    ) -> Frame {
11329        let body = serde_json::to_vec(&ModuleHelloBody {
11330            manifest: manifest(module_id, protocol_ver),
11331            protocol_ver,
11332            control_ops,
11333            launch_nonce,
11334        })
11335        .unwrap();
11336        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11337    }
11338
11339    fn hello_frame_with_rich_ui(
11340        module_id: &str,
11341        protocol_ver: u8,
11342        corr: u64,
11343        launch_nonce: Option<&str>,
11344        rich_ui: Value,
11345    ) -> Frame {
11346        let mut body = serde_json::to_value(ModuleHelloBody {
11347            manifest: manifest(module_id, protocol_ver),
11348            protocol_ver,
11349            control_ops: None,
11350            launch_nonce: launch_nonce.map(str::to_string),
11351        })
11352        .unwrap();
11353        body["manifest"]["rich_ui"] = rich_ui;
11354        Frame::build(
11355            FrameType::Hello,
11356            control_flags(),
11357            0,
11358            0,
11359            corr,
11360            serde_json::to_vec(&body).unwrap(),
11361        )
11362        .unwrap()
11363    }
11364
11365    fn non_routable_hello_frame_with_control_ops(
11366        module_id: &str,
11367        corr: u64,
11368        control_ops: Option<Vec<String>>,
11369    ) -> Frame {
11370        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11371        manifest.provides.clear();
11372        let body = serde_json::to_vec(&ModuleHelloBody {
11373            manifest,
11374            protocol_ver: PROTOCOL_VERSION,
11375            control_ops,
11376            launch_nonce: None,
11377        })
11378        .unwrap();
11379        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11380    }
11381
11382    fn capability_grammar_hello_frame(
11383        capabilities: Value,
11384        runtime_computed: Option<Value>,
11385        corr: u64,
11386    ) -> Frame {
11387        let mut body = serde_json::to_value(ModuleHelloBody {
11388            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11389            protocol_ver: PROTOCOL_VERSION,
11390            control_ops: None,
11391            launch_nonce: None,
11392        })
11393        .expect("HELLO body serializes");
11394        body["manifest"]["capabilities"] = capabilities;
11395        if let Some(runtime_computed) = runtime_computed {
11396            body["runtime_computed"] = runtime_computed;
11397        }
11398        Frame::build(
11399            FrameType::Hello,
11400            control_flags(),
11401            0,
11402            0,
11403            corr,
11404            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11405        )
11406        .expect("HELLO frame builds")
11407    }
11408
11409    fn channel_request(channel: u16, corr: u64) -> Frame {
11410        Frame::build(
11411            FrameType::Request,
11412            Flags::new(true, Priority::Interactive, false),
11413            channel,
11414            0,
11415            corr,
11416            b"opaque".to_vec(),
11417        )
11418        .unwrap()
11419    }
11420
11421    fn route_ctx(
11422        connection_id: ConnectionId,
11423    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11424        let (tx, rx) = mpsc::channel(8);
11425        (
11426            RouteCtx {
11427                connection_id,
11428                egress: FrameSink::new(tx),
11429            },
11430            rx,
11431        )
11432    }
11433
11434    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11435        serde_json::from_slice(&frame.body).unwrap()
11436    }
11437
11438    /// Register a module over a connection that has a sink and return the
11439    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11440    /// module's own sink rather than returning it as a reply, so the ack is
11441    /// taken off `rx` here and whatever the test reads next is what followed it.
11442    async fn hello_via_sink(
11443        handler: &ControlHandler,
11444        ctx: &RouteCtx,
11445        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11446        hello: Frame,
11447    ) -> Frame {
11448        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11449        assert!(
11450            replies.is_empty(),
11451            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11452        );
11453        let ack = rx
11454            .try_recv()
11455            .expect("HELLO_ACK is queued on the module sink")
11456            .frame;
11457        assert_eq!(ack.header.ty, FrameType::HelloAck);
11458        ack
11459    }
11460
11461    fn parse_error(frame: &Frame) -> Value {
11462        serde_json::from_slice(&frame.body).unwrap()
11463    }
11464
11465    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11466        serde_json::from_slice(&frame.body).unwrap()
11467    }
11468
11469    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11470        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11471            route_channel,
11472            route_epoch: 0,
11473            kind,
11474        })
11475        .unwrap();
11476        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11477    }
11478
11479    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11480        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11481            module_id: module_id.to_string(),
11482        })
11483        .unwrap();
11484        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11485    }
11486
11487    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11488        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11489    }
11490
11491    // Exercise retired opener fields without putting them back in BindIdentity.
11492    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11493        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11494        let mut frame = route_open_frame(corr, module_id, root);
11495        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11496        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11497        frame.body = serde_json::to_vec(&body).unwrap();
11498        frame
11499    }
11500
11501    fn route_open_frame_with_consumer_capabilities(
11502        corr: u64,
11503        module_id: &str,
11504        _project_root: ScratchDir,
11505        consumer_capabilities: Option<Vec<String>>,
11506    ) -> Frame {
11507        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11508            busy_refusals: None,
11509            target: RouteTarget::ToolProvider {
11510                module_id: module_id.to_string(),
11511            },
11512            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11513            consumer_identity: None,
11514            consumer_capabilities,
11515            role_versions: None,
11516            admission_facts: None,
11517            scope: None,
11518        })
11519        .unwrap();
11520        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11521    }
11522
11523    fn route_open_frame_with_role_versions(
11524        corr: u64,
11525        module_id: &str,
11526        _project_root: ScratchDir,
11527        role_versions: Option<BTreeMap<String, String>>,
11528    ) -> Frame {
11529        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11530            busy_refusals: None,
11531            target: RouteTarget::ToolProvider {
11532                module_id: module_id.to_string(),
11533            },
11534            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11535            consumer_identity: None,
11536            consumer_capabilities: None,
11537            role_versions,
11538            admission_facts: None,
11539            scope: None,
11540        })
11541        .unwrap();
11542        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11543    }
11544
11545    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11546        entries
11547            .iter()
11548            .map(|(role, version)| (role.to_string(), version.to_string()))
11549            .collect()
11550    }
11551
11552    fn route_open_frame_with_admission_facts(
11553        corr: u64,
11554        module_id: &str,
11555        _project_root: ScratchDir,
11556        consumer_identity: Option<subc_control::ConsumerIdentity>,
11557        facts: Option<Value>,
11558    ) -> Frame {
11559        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11560            busy_refusals: None,
11561            target: RouteTarget::ToolProvider {
11562                module_id: module_id.to_string(),
11563            },
11564            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11565            consumer_identity,
11566            consumer_capabilities: None,
11567            role_versions: None,
11568            admission_facts: facts,
11569            scope: None,
11570        })
11571        .unwrap();
11572        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11573    }
11574
11575    #[derive(Clone, Default)]
11576    struct EventCapture {
11577        events: Arc<Mutex<Vec<CapturedEvent>>>,
11578    }
11579
11580    #[derive(Clone, Debug)]
11581    struct CapturedEvent {
11582        target: String,
11583        level: tracing::Level,
11584        fields: BTreeMap<String, String>,
11585    }
11586
11587    impl EventCapture {
11588        fn events(&self) -> Vec<CapturedEvent> {
11589            self.events.lock().unwrap().clone()
11590        }
11591    }
11592
11593    impl<S> Layer<S> for EventCapture
11594    where
11595        S: Subscriber,
11596    {
11597        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11598            let mut visitor = EventFieldVisitor::default();
11599            event.record(&mut visitor);
11600            self.events.lock().unwrap().push(CapturedEvent {
11601                target: event.metadata().target().to_string(),
11602                level: *event.metadata().level(),
11603                fields: visitor.fields,
11604            });
11605        }
11606    }
11607
11608    #[derive(Default)]
11609    struct EventFieldVisitor {
11610        fields: BTreeMap<String, String>,
11611    }
11612
11613    impl Visit for EventFieldVisitor {
11614        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11615            self.fields
11616                .insert(field.name().to_string(), format!("{value:?}"));
11617        }
11618    }
11619
11620    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11621        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11622            status,
11623            detail: Some("warming".to_string()),
11624            metrics: Some(json!({"queue_depth": 3})),
11625        })
11626        .unwrap();
11627        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11628    }
11629
11630    fn route_bind_ack(corr: u64) -> Frame {
11631        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11632        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11633    }
11634
11635    fn unique_project_root(label: &str) -> ScratchDir {
11636        ScratchDir::new(label)
11637    }
11638
11639    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11640        match parse_route_poll(frame) {
11641            ClientControlResponse::RoutePoll {
11642                status: None,
11643                live: Some(live),
11644                ..
11645            } => assert_eq!(live, expected_live),
11646            other => panic!("unexpected route.poll response: {other:?}"),
11647        }
11648    }
11649
11650    fn bind_liveness_route(
11651        registry: &Registry,
11652        forwarding: &ForwardingTable,
11653        module_id: &str,
11654    ) -> (RouteCtx, u16, u32) {
11655        let module_connection = ConnectionId::new(101);
11656        let client_connection = ConnectionId::new(202);
11657        let registration = registry
11658            .register_with_control_ops(
11659                manifest(module_id, PROTOCOL_VERSION),
11660                PROTOCOL_VERSION,
11661                module_connection,
11662                module_baseline_control_ops(),
11663            )
11664            .unwrap();
11665        let (module_tx, _module_rx) = mpsc::channel(8);
11666        let endpoint = forwarding
11667            .register_module_connection(
11668                module_connection,
11669                module_id.to_string(),
11670                PROTOCOL_VERSION,
11671                manifest_concurrency(&registration.manifest),
11672                FrameSink::new(module_tx),
11673            )
11674            .unwrap();
11675        let (client_ctx, _client_rx) = route_ctx(client_connection);
11676        let pending = forwarding
11677            .begin_route_bind_relay_for_test(
11678                client_connection,
11679                client_ctx.egress.clone(),
11680                1,
11681                module_id,
11682            )
11683            .unwrap();
11684        assert_eq!(pending.endpoint, endpoint);
11685        let route_channel = pending.client_channel;
11686        let route_epoch = pending.client_epoch;
11687        forwarding
11688            .complete_pending_relay(
11689                module_connection,
11690                pending.corr,
11691                RouteBindRelayOutcome::Accepted,
11692            )
11693            .unwrap();
11694        (client_ctx, route_channel, route_epoch)
11695    }
11696
11697    struct FakeProcessLiveness {
11698        live: Option<bool>,
11699    }
11700
11701    impl ModuleProcessLiveness for FakeProcessLiveness {
11702        fn process_live(&self, _module_id: &str) -> Option<bool> {
11703            self.live
11704        }
11705    }
11706
11707    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11708    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11709    {
11710        let registry = Arc::new(Registry::default());
11711        let supervisor_handle = SupervisorHandle::new();
11712        let supervisor = Supervisor::new_for_test(
11713            Arc::clone(&registry),
11714            RestartPolicy::new(1, Duration::from_millis(10)),
11715        )
11716        .with_handle(supervisor_handle.clone());
11717        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11718        let module = supervisor
11719            .spawn(ModuleSpec {
11720                script: None,
11721                carry_containment: false,
11722                module_id: "stderr-tail-wire".to_string(),
11723                program: fake_aft_stub_path(),
11724                args: Vec::new(),
11725                env: vec![
11726                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11727                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11728                ],
11729                reserved: false,
11730                reserved_prefixes: Vec::new(),
11731                protocol: ModuleProtocol::Subc,
11732                overlap: Default::default(),
11733            })
11734            .unwrap();
11735
11736        let deadline = Instant::now() + Duration::from_secs(5);
11737        loop {
11738            let tail = module.stderr_tail(None, None);
11739            if tail
11740                .entries
11741                .iter()
11742                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11743                && tail.entries.iter().any(|entry| {
11744                    matches!(
11745                        entry,
11746                        TailEntry::Line {
11747                            truncated: true,
11748                            ..
11749                        }
11750                    )
11751                })
11752            {
11753                break;
11754            }
11755            assert!(
11756                Instant::now() < deadline,
11757                "module did not produce a truncated line and restart boundary: {tail:?}"
11758            );
11759            sleep(Duration::from_millis(10)).await;
11760        }
11761
11762        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11763        let request = ClientControlRequest::SupervisorStderrTail {
11764            module_id: "stderr-tail-wire".to_string(),
11765            max_lines: None,
11766            max_bytes: None,
11767        };
11768        let frame = Frame::build(
11769            FrameType::Request,
11770            control_flags(),
11771            0,
11772            0,
11773            1,
11774            serde_json::to_vec(&request).unwrap(),
11775        )
11776        .unwrap();
11777        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11778        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11779        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11780            serde_json::from_slice(&responses[0].body).unwrap()
11781        else {
11782            panic!("expected supervisor.stderr_tail response");
11783        };
11784
11785        assert!(
11786            tail.entries
11787                .iter()
11788                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11789            "the control response lost the restart boundary"
11790        );
11791        let Some(StderrTailEntry::Line {
11792            text,
11793            truncated,
11794            at_ms,
11795        }) = tail.entries.iter().find(|entry| {
11796            matches!(
11797                entry,
11798                StderrTailEntry::Line {
11799                    truncated: true,
11800                    ..
11801                }
11802            )
11803        })
11804        else {
11805            panic!("the control response lost the truncated line");
11806        };
11807        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11808        assert!(*truncated);
11809        assert!(
11810            at_ms.is_some(),
11811            "the control response lost the line's capture time"
11812        );
11813    }
11814
11815    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11816    /// read done on the worker thread would stall every other task until it
11817    /// finished; the read must run off the worker so this test's own task keeps
11818    /// running while the read is paused.
11819    #[tokio::test(flavor = "current_thread")]
11820    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11821        let dir = ScratchDir::new("terminals-off-worker");
11822        let journal_path = dir.join("terminals.jsonl");
11823        let registry = Arc::new(Registry::default());
11824        let supervisor_handle = SupervisorHandle::new();
11825        let supervisor =
11826            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11827                .with_handle(supervisor_handle.clone())
11828                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11829        let module = supervisor
11830            .spawn(ModuleSpec {
11831                script: None,
11832                carry_containment: false,
11833                module_id: "terminal-off-worker".to_string(),
11834                program: fake_aft_stub_path(),
11835                args: Vec::new(),
11836                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11837                reserved: false,
11838                reserved_prefixes: Vec::new(),
11839                protocol: ModuleProtocol::Subc,
11840                overlap: Default::default(),
11841            })
11842            .unwrap();
11843        let deadline = Instant::now() + Duration::from_secs(5);
11844        while module.terminal_history().entries.len() != 2 {
11845            assert!(Instant::now() < deadline, "module did not record two exits");
11846            sleep(Duration::from_millis(10)).await;
11847        }
11848
11849        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11850        let handler =
11851            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11852        let frame = Frame::build(
11853            FrameType::Request,
11854            control_flags(),
11855            0,
11856            0,
11857            1,
11858            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11859                module_id: "terminal-off-worker".to_string(),
11860            })
11861            .unwrap(),
11862        )
11863        .unwrap();
11864        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11865        let spawned_at = std::time::Instant::now();
11866        let read = tokio::spawn({
11867            let handler = Arc::clone(&handler);
11868            async move { handler.handle_control_frame(&ctx, frame).await }
11869        });
11870        // Waiting for the pause from a blocking thread keeps this task pending,
11871        // so the runtime's single worker is free to run the read task.
11872        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11873            .await
11874            .unwrap()
11875            .expect("the history read reached its pause");
11876        let elapsed = spawned_at.elapsed();
11877        assert!(
11878            elapsed < Duration::from_secs(2) && !read.is_finished(),
11879            "this task could not run while the history read was paused \
11880             (resumed after {elapsed:?}, read finished: {})",
11881            read.is_finished()
11882        );
11883
11884        drop(release);
11885        let responses = read.await.unwrap().unwrap();
11886        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11887        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11888            panic!("expected supervisor.terminals response");
11889        };
11890        assert_eq!(terminals.entries.len(), 2);
11891        assert_eq!(terminals.journal_skipped_lines, 0);
11892        assert_eq!(terminals.journal_read_errors, 0);
11893    }
11894
11895    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11896    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11897        let registry = Arc::new(Registry::default());
11898        let supervisor_handle = SupervisorHandle::new();
11899        let supervisor =
11900            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11901                .with_handle(supervisor_handle.clone());
11902        let module = supervisor
11903            .spawn(ModuleSpec {
11904                script: None,
11905                carry_containment: false,
11906                module_id: "terminal-golden".to_string(),
11907                program: fake_aft_stub_path(),
11908                args: Vec::new(),
11909                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11910                reserved: false,
11911                reserved_prefixes: Vec::new(),
11912                protocol: ModuleProtocol::Subc,
11913                overlap: Default::default(),
11914            })
11915            .unwrap();
11916
11917        let deadline = Instant::now() + Duration::from_secs(5);
11918        while module.terminal_history().entries.len() != 2 {
11919            assert!(
11920                Instant::now() < deadline,
11921                "module did not retain two terminal exits: {:?}",
11922                module.terminal_history()
11923            );
11924            sleep(Duration::from_millis(10)).await;
11925        }
11926
11927        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11928        let request = ClientControlRequest::SupervisorTerminals {
11929            module_id: "terminal-golden".to_string(),
11930        };
11931        let frame = Frame::build(
11932            FrameType::Request,
11933            control_flags(),
11934            0,
11935            0,
11936            1,
11937            serde_json::to_vec(&request).unwrap(),
11938        )
11939        .unwrap();
11940        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11941        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11942        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11943        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11944            panic!("expected supervisor.terminals response");
11945        };
11946        assert_eq!(terminals.entries.len(), 2);
11947        assert_eq!(terminals.dropped, 0);
11948
11949        let mut rendered = serde_json::to_value(response).unwrap();
11950        // Wall-clock fields are the observation contract, but not stable fixture
11951        // bytes; normalize only them after the real handler has shaped the response.
11952        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11953        for (index, entry) in rendered["entries"]
11954            .as_array_mut()
11955            .expect("terminal response entries array")
11956            .iter_mut()
11957            .enumerate()
11958        {
11959            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11960        }
11961
11962        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11963            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11964        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11965        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11966            std::fs::write(&golden_path, &serialized).unwrap();
11967        }
11968        let expected: Value =
11969            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11970        assert_eq!(rendered, expected);
11971    }
11972
11973    #[test]
11974    fn hello_registers_manifest_and_returns_ack() {
11975        let registry = Arc::new(Registry::default());
11976        let handler = ControlHandler::new(Arc::clone(&registry));
11977        let conn = ConnectionId::new(1);
11978
11979        let responses = handler
11980            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11981            .unwrap();
11982
11983        assert_eq!(responses.len(), 1);
11984        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11985        assert_eq!(responses[0].header.channel, 0);
11986        assert_eq!(responses[0].header.corr, 7);
11987        let ack = parse_ack(&responses[0]);
11988        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11989        assert!(ack
11990            .subc_capabilities
11991            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11992        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11993        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11994        assert!(ack
11995            .subc_ops
11996            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11997        assert!(ack
11998            .subc_ops
11999            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
12000        assert!(ack
12001            .subc_ops
12002            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
12003
12004        let registration = registry.get_module("aft").unwrap().unwrap();
12005        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
12006        assert_eq!(registration.state, ChannelState::Active);
12007        assert_eq!(registration.connection_id, conn);
12008        assert_eq!(registration.control_ops, module_baseline_control_ops());
12009        assert!(registration.manifest.display_name.is_none());
12010    }
12011
12012    #[test]
12013    fn hello_display_name_refuses_invalid_manifest_by_field() {
12014        let registry = Arc::new(Registry::default());
12015        let handler = ControlHandler::new(Arc::clone(&registry));
12016        for (index, invalid) in [
12017            json!(""),
12018            json!("a".repeat(41)),
12019            json!(" Routing"),
12020            json!("a\nb"),
12021            json!("a\u{202e}b"),
12022            json!(7),
12023        ]
12024        .into_iter()
12025        .enumerate()
12026        {
12027            let module_id = format!("bad-display-name-{index}");
12028            let mut body = serde_json::to_value(ModuleHelloBody {
12029                manifest: manifest(&module_id, PROTOCOL_VERSION),
12030                protocol_ver: PROTOCOL_VERSION,
12031                control_ops: None,
12032                launch_nonce: None,
12033            })
12034            .unwrap();
12035            body["manifest"]["display_name"] = invalid;
12036            let hello = Frame::build(
12037                FrameType::Hello,
12038                control_flags(),
12039                0,
12040                0,
12041                7,
12042                serde_json::to_vec(&body).unwrap(),
12043            )
12044            .unwrap();
12045            let response = handler
12046                .handle_control(ConnectionId::new(100 + index as u64), hello)
12047                .unwrap();
12048            assert_eq!(response[0].header.ty, FrameType::Error);
12049            let error = parse_error(&response[0]);
12050            assert_eq!(error["code"], "invalid_manifest");
12051            assert!(error["message"].as_str().unwrap().contains("display_name"));
12052            assert!(registry.get_module(&module_id).unwrap().is_none());
12053        }
12054    }
12055
12056    #[test]
12057    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
12058        let invalid_identifiers = [
12059            ("case_change", "credentials-Provider/v1"),
12060            ("leading_zero", "credentials-provider/v01"),
12061            ("trailing_hyphen", "credentials-provider-/v1"),
12062            ("consecutive_hyphens", "credentials--provider/v1"),
12063            ("uppercase", "Credentials-provider/v1"),
12064            ("missing_v", "credentials-provider/1"),
12065            ("whitespace", "credentials provider/v1"),
12066            ("zero_version", "credentials-provider/v0"),
12067            ("out_of_range_version", "credentials-provider/v4294967296"),
12068            (
12069                "overlength_name",
12070                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
12071            ),
12072        ];
12073        let mut cases = invalid_identifiers
12074            .into_iter()
12075            .map(|(name, identifier)| {
12076                (
12077                    format!("identifier_{name}"),
12078                    "capabilities.provides[0]".to_string(),
12079                    identifier.to_string(),
12080                    json!({ "provides": [identifier] }),
12081                    None,
12082                )
12083            })
12084            .collect::<Vec<_>>();
12085        cases.extend([
12086            (
12087                "unknown_need".to_string(),
12088                "capabilities.requires[0].need".to_string(),
12089                "deferred".to_string(),
12090                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
12091                None,
12092            ),
12093            (
12094                "duplicate_provides".to_string(),
12095                "capabilities.provides[1]".to_string(),
12096                "credentials-provider/v1".to_string(),
12097                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
12098                None,
12099            ),
12100            (
12101                "duplicate_must_never_reach".to_string(),
12102                "capabilities.must_never_reach[1]".to_string(),
12103                "credentials-provider/v1".to_string(),
12104                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
12105                None,
12106            ),
12107            (
12108                "duplicate_requires_same_need".to_string(),
12109                "capabilities.requires[1]".to_string(),
12110                "credentials-provider/v1".to_string(),
12111                json!({ "requires": [
12112                    { "capability": "credentials-provider/v1", "need": "required" },
12113                    { "capability": "credentials-provider/v1", "need": "required" }
12114                ] }),
12115                None,
12116            ),
12117            (
12118                "duplicate_requires_conflicting_need".to_string(),
12119                "capabilities.requires[1]".to_string(),
12120                "credentials-provider/v1".to_string(),
12121                json!({ "requires": [
12122                    { "capability": "credentials-provider/v1", "need": "required" },
12123                    { "capability": "credentials-provider/v1", "need": "optional" }
12124                ] }),
12125                None,
12126            ),
12127            (
12128                "capabilities_root_pointer".to_string(),
12129                "runtime_computed[0]".to_string(),
12130                "/capabilities".to_string(),
12131                json!({}),
12132                Some(json!(["/capabilities"])),
12133            ),
12134            (
12135                "capabilities_descendant_pointer".to_string(),
12136                "runtime_computed[0]".to_string(),
12137                "/capabilities/provides".to_string(),
12138                json!({}),
12139                Some(json!(["/capabilities/provides"])),
12140            ),
12141            (
12142                "malformed_pointer_without_leading_slash".to_string(),
12143                "runtime_computed[0]".to_string(),
12144                "capabilities".to_string(),
12145                json!({}),
12146                Some(json!(["capabilities"])),
12147            ),
12148            (
12149                "malformed_pointer_escape".to_string(),
12150                "runtime_computed[0]".to_string(),
12151                "/roles/~2/tools".to_string(),
12152                json!({}),
12153                Some(json!(["/roles/~2/tools"])),
12154            ),
12155            (
12156                "unknown_capabilities_field".to_string(),
12157                "capabilities.future".to_string(),
12158                "<array>".to_string(),
12159                json!({ "future": [] }),
12160                None,
12161            ),
12162        ]);
12163
12164        for (index, (name, field, value, capabilities, runtime_computed)) in
12165            cases.into_iter().enumerate()
12166        {
12167            let registry = Arc::new(Registry::default());
12168            let handler = ControlHandler::new(Arc::clone(&registry));
12169            let response = handler
12170                .handle_control(
12171                    ConnectionId::new((index + 1) as u64),
12172                    capability_grammar_hello_frame(
12173                        capabilities,
12174                        runtime_computed,
12175                        index as u64 + 1,
12176                    ),
12177                )
12178                .expect("invalid HELLO returns a refusal");
12179
12180            assert_eq!(response.len(), 1, "{name} must emit one refusal");
12181            let error = parse_error(&response[0]);
12182            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
12183            let message = error["message"]
12184                .as_str()
12185                .expect("error message is a string");
12186            assert!(
12187                message.contains(&field),
12188                "{name}: field missing from {message}"
12189            );
12190            assert!(
12191                message.contains(&value),
12192                "{name}: value missing from {message}"
12193            );
12194            assert_eq!(
12195                registry
12196                    .active_registration_count()
12197                    .expect("registry reads"),
12198                0,
12199                "{name}: refused HELLO must not create a catalog entry"
12200            );
12201        }
12202    }
12203
12204    #[test]
12205    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
12206        let registry = Arc::new(Registry::default());
12207        let handler = ControlHandler::new(Arc::clone(&registry));
12208        let capabilities = json!({
12209            "provides": ["credentials-provider/v1"],
12210            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
12211            "must_never_reach": ["federation-transport/v1"]
12212        });
12213        let response = handler
12214            .handle_control(
12215                ConnectionId::new(99),
12216                capability_grammar_hello_frame(
12217                    capabilities.clone(),
12218                    Some(json!(["/roles/0/tools"])),
12219                    99,
12220                ),
12221            )
12222            .expect("valid HELLO registers");
12223        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12224
12225        let request = Frame::build(
12226            FrameType::Request,
12227            control_flags(),
12228            0,
12229            0,
12230            100,
12231            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12232                .expect("catalog request serializes"),
12233        )
12234        .expect("catalog request frame builds");
12235        let response = handler
12236            .handle_catalog_list(request, None)
12237            .expect("catalog list succeeds");
12238        let ClientControlResponse::CatalogList { modules, .. } =
12239            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
12240        else {
12241            panic!("catalog request must return catalog.list");
12242        };
12243        assert_eq!(modules.len(), 1);
12244        assert_eq!(
12245            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
12246            capabilities
12247        );
12248    }
12249
12250    #[test]
12251    fn catalog_list_mirrors_management_operation_description() {
12252        let registry = Arc::new(Registry::default());
12253        let handler = ControlHandler::new(Arc::clone(&registry));
12254        let description = "List managed records and return their identifiers and metadata.";
12255        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
12256        manifest.provides = vec![ProviderRole::ManagementSurface {
12257            operations: vec![ManagementOperation {
12258                name: "records.list".to_string(),
12259                kind: ManagementOperationKind::Query,
12260                description: Some(description.to_string()),
12261            }],
12262            config_schema: json!({"type": "object"}),
12263            observability: vec![ObservabilitySurface {
12264                name: "records.stats".to_string(),
12265                kind: ObservabilityKind::Snapshot,
12266            }],
12267            identity_scope: vec![IdentityScope::Project],
12268            concurrency: Concurrency::ModuleManaged,
12269        }];
12270        registry
12271            .register_with_control_ops(
12272                manifest,
12273                PROTOCOL_VERSION,
12274                ConnectionId::new(99),
12275                Vec::new(),
12276            )
12277            .expect("described management manifest registers");
12278
12279        let request = Frame::build(
12280            FrameType::Request,
12281            control_flags(),
12282            0,
12283            0,
12284            100,
12285            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12286                .expect("catalog request serializes"),
12287        )
12288        .expect("catalog request frame builds");
12289        let response = handler
12290            .handle_catalog_list(request, None)
12291            .expect("catalog list succeeds");
12292        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12293        assert_eq!(
12294            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12295            "catalog.list must preserve the declared operation description verbatim"
12296        );
12297    }
12298
12299    #[test]
12300    fn catalog_list_mirrors_registered_operation_delivery() {
12301        let registry = Arc::new(Registry::default());
12302        let handler = ControlHandler::new(Arc::clone(&registry));
12303        let delivery =
12304            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12305        let mut body = serde_json::to_value(ModuleHelloBody {
12306            manifest: manifest("watch-management", PROTOCOL_VERSION),
12307            protocol_ver: PROTOCOL_VERSION,
12308            control_ops: None,
12309            launch_nonce: None,
12310        })
12311        .unwrap();
12312        body["manifest"]["provides"] = json!([{
12313            "role": "management_surface",
12314            "operations": [
12315                {"name": "status", "kind": "query"},
12316                {"name": "future", "kind": "query"},
12317                {"name": "reset", "kind": "mutate"}
12318            ],
12319            "config_schema": {}, "observability": [], "identity_scope": []
12320        }]);
12321        body["manifest"]["operation_delivery"] = delivery.clone();
12322        let hello = Frame::build(
12323            FrameType::Hello,
12324            control_flags(),
12325            0,
12326            0,
12327            99,
12328            serde_json::to_vec(&body).unwrap(),
12329        )
12330        .unwrap();
12331        let response = handler
12332            .handle_control(ConnectionId::new(99), hello)
12333            .unwrap();
12334        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12335
12336        let (_, registrations) = registry.list_modules().unwrap();
12337        let registered = &registrations[0].manifest;
12338        assert!(registered.is_watch_operation("status"));
12339        assert!(!registered.is_watch_operation("future"));
12340        assert!(!registered.is_watch_operation("reset"));
12341        assert!(!registered.is_watch_operation("missing"));
12342
12343        let request = Frame::build(
12344            FrameType::Request,
12345            control_flags(),
12346            0,
12347            0,
12348            100,
12349            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12350        )
12351        .unwrap();
12352        let response = handler.handle_catalog_list(request, None).unwrap();
12353        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12354        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12355        let ClientControlResponse::CatalogList { modules, .. } =
12356            serde_json::from_slice(&response[0].body).unwrap()
12357        else {
12358            panic!("expected catalog.list");
12359        };
12360        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12361    }
12362
12363    #[test]
12364    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12365        let registry = Arc::new(Registry::default());
12366        let supervisor = SupervisorHandle::new();
12367        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12368        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12369        let descriptor = json!({
12370            "schema": "ckios.richui.manifest/1",
12371            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12372            "bytes": 4096,
12373            "chunks": 4
12374        });
12375        let connection = ConnectionId::new(201);
12376        let hello = handler
12377            .handle_control(
12378                connection,
12379                hello_frame_with_rich_ui(
12380                    "vault",
12381                    PROTOCOL_VERSION,
12382                    201,
12383                    Some("the-real-nonce"),
12384                    descriptor.clone(),
12385                ),
12386            )
12387            .unwrap();
12388        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12389
12390        let request =
12391            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12392        let provides = registry
12393            .get_module_by_connection(connection)
12394            .unwrap()
12395            .unwrap()
12396            .manifest
12397            .provides;
12398        handler
12399            .handle_catalog_update(connection, request, provides, None, Some(false))
12400            .unwrap();
12401
12402        let request = Frame::build(
12403            FrameType::Request,
12404            control_flags(),
12405            0,
12406            0,
12407            203,
12408            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12409        )
12410        .unwrap();
12411        let response = handler.handle_catalog_list(request, None).unwrap();
12412        let ClientControlResponse::CatalogList { modules, .. } =
12413            serde_json::from_slice(&response[0].body).unwrap()
12414        else {
12415            panic!("expected catalog.list");
12416        };
12417        assert_eq!(
12418            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12419            descriptor
12420        );
12421        assert!(modules[0].nonce_verified);
12422    }
12423
12424    fn hello_with_role_declarations(declarations: Value) -> Frame {
12425        let mut body = serde_json::to_value(ModuleHelloBody {
12426            manifest: manifest("role-test", PROTOCOL_VERSION),
12427            protocol_ver: PROTOCOL_VERSION,
12428            control_ops: None,
12429            launch_nonce: None,
12430        })
12431        .unwrap();
12432        body["manifest"]["role_declarations"] = declarations;
12433        Frame::build(
12434            FrameType::Hello,
12435            control_flags(),
12436            0,
12437            0,
12438            301,
12439            serde_json::to_vec(&body).unwrap(),
12440        )
12441        .unwrap()
12442    }
12443
12444    fn update_role_declarations_frame(declarations: Value) -> Frame {
12445        Frame::build(
12446            FrameType::Request,
12447            control_flags(),
12448            0,
12449            0,
12450            303,
12451            serde_json::to_vec(&json!({
12452                "op": "catalog.update_role_declarations",
12453                "role_declarations": declarations,
12454            }))
12455            .unwrap(),
12456        )
12457        .unwrap()
12458    }
12459
12460    #[tokio::test]
12461    async fn role_declarations_update_replaces_then_clears_catalog() {
12462        let registry = Arc::new(Registry::default());
12463        let handler = ControlHandler::new(Arc::clone(&registry));
12464        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12465        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12466        hello_via_sink(
12467            &handler,
12468            &ctx,
12469            &mut rx,
12470            hello_with_role_declarations(initial.clone()),
12471        )
12472        .await;
12473        assert_eq!(
12474            role_declarations_catalog(&handler).0["role_declarations"],
12475            initial
12476        );
12477        let before = registry.get_module("role-test").unwrap().unwrap();
12478        for declarations in [
12479            json!({"media-provider/v1": {"engines": ["new"]}}),
12480            json!({}),
12481        ] {
12482            let response = handler
12483                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12484                .await
12485                .unwrap();
12486            assert_eq!(response[0].header.ty, FrameType::Response);
12487            assert_eq!(
12488                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12489                json!({"op": "catalog.update_role_declarations"})
12490            );
12491            let (raw, entry) = role_declarations_catalog(&handler);
12492            assert_eq!(
12493                serde_json::to_value(entry.role_declarations).unwrap(),
12494                declarations
12495            );
12496            if declarations.as_object().unwrap().is_empty() {
12497                assert!(raw.get("role_declarations").is_none());
12498            } else {
12499                assert_eq!(raw["role_declarations"], declarations);
12500            }
12501            let after = registry.get_module("role-test").unwrap().unwrap();
12502            let mut expected = before.manifest.clone();
12503            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12504            assert_eq!(after.manifest, expected);
12505            assert_eq!(after.ready, before.ready);
12506        }
12507    }
12508
12509    #[tokio::test]
12510    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12511        let registry = Arc::new(Registry::default());
12512        let handler = ControlHandler::new(registry);
12513        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12514        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12515        hello_via_sink(
12516            &handler,
12517            &ctx,
12518            &mut rx,
12519            hello_with_role_declarations(initial.clone()),
12520        )
12521        .await;
12522        for (invalid, reason) in [
12523            (json!(null), "role_declarations must be an object"),
12524            (json!([]), "role_declarations must be an object"),
12525            (
12526                json!({"bad key": {}}),
12527                "role_declarations key must use capability-name grammar",
12528            ),
12529            (
12530                json!({"media-provider/v1": []}),
12531                "role_declarations values must be objects",
12532            ),
12533            (
12534                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12535                "role_declarations exceeds 16384 compact JSON bytes",
12536            ),
12537        ] {
12538            let response = handler
12539                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12540                .await
12541                .unwrap();
12542            let error = parse_error(&response[0]);
12543            assert_eq!(error["code"], "invalid_role_declarations");
12544            assert_eq!(error["message"], reason);
12545            assert_eq!(
12546                role_declarations_catalog(&handler).0["role_declarations"],
12547                initial
12548            );
12549        }
12550    }
12551
12552    #[tokio::test]
12553    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12554        let registry = Arc::new(Registry::default());
12555        let handler = ControlHandler::new(Arc::clone(&registry));
12556        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12557        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12558        hello_via_sink(
12559            &handler,
12560            &owner,
12561            &mut owner_rx,
12562            hello_with_role_declarations(initial.clone()),
12563        )
12564        .await;
12565        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12566        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12567        let response = handler
12568            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12569            .await
12570            .unwrap();
12571        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12572        hello_via_sink(
12573            &handler,
12574            &other,
12575            &mut other_rx,
12576            hello_frame("other", PROTOCOL_VERSION, 304),
12577        )
12578        .await;
12579        let response = handler
12580            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12581            .await
12582            .unwrap();
12583        assert_eq!(response[0].header.ty, FrameType::Response);
12584        assert_eq!(
12585            serde_json::to_value(
12586                registry
12587                    .get_module("role-test")
12588                    .unwrap()
12589                    .unwrap()
12590                    .manifest
12591                    .role_declarations
12592            )
12593            .unwrap(),
12594            initial
12595        );
12596        assert_eq!(
12597            serde_json::to_value(
12598                registry
12599                    .get_module("other")
12600                    .unwrap()
12601                    .unwrap()
12602                    .manifest
12603                    .role_declarations
12604            )
12605            .unwrap(),
12606            replacement
12607        );
12608    }
12609
12610    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12611        let request = Frame::build(
12612            FrameType::Request,
12613            control_flags(),
12614            0,
12615            0,
12616            302,
12617            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12618        )
12619        .unwrap();
12620        let response = handler.handle_catalog_list(request, None).unwrap();
12621        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12622        let ClientControlResponse::CatalogList { mut modules, .. } =
12623            serde_json::from_slice(&response[0].body).unwrap()
12624        else {
12625            panic!("expected catalog.list");
12626        };
12627        (raw["modules"][0].clone(), modules.remove(0))
12628    }
12629
12630    #[test]
12631    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12632        let registry = Arc::new(Registry::default());
12633        let handler = ControlHandler::new(Arc::clone(&registry));
12634        let declarations = json!({
12635            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12636            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12637        });
12638        let connection = ConnectionId::new(301);
12639        let response = handler
12640            .handle_control(
12641                connection,
12642                hello_with_role_declarations(declarations.clone()),
12643            )
12644            .unwrap();
12645        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12646        let registered = registry
12647            .get_module_by_connection(connection)
12648            .unwrap()
12649            .unwrap()
12650            .manifest;
12651        // Compared as JSON values, not bytes: object key order is not part of
12652        // the relay's promise, and workspace builds unify serde_json's
12653        // preserve_order feature, which changes the order a literal keeps.
12654        assert_eq!(
12655            serde_json::to_value(&registered.role_declarations).unwrap(),
12656            declarations
12657        );
12658        let (raw, entry) = role_declarations_catalog(&handler);
12659        assert_eq!(raw["role_declarations"], declarations);
12660        assert_eq!(entry.role_declarations, registered.role_declarations);
12661
12662        let request =
12663            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12664        handler
12665            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12666            .unwrap();
12667        let (raw, entry) = role_declarations_catalog(&handler);
12668        assert_eq!(raw["role_declarations"], declarations);
12669        assert_eq!(entry.role_declarations, registered.role_declarations);
12670    }
12671
12672    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12673        let registry = Arc::new(Registry::default());
12674        let handler = ControlHandler::new(Arc::clone(&registry));
12675        let capture = EventCapture::default();
12676        let _subscriber =
12677            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12678        let response = handler
12679            .handle_control(
12680                ConnectionId::new(301),
12681                hello_with_role_declarations(declarations),
12682            )
12683            .unwrap();
12684        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12685        assert!(registry
12686            .get_module_by_connection(ConnectionId::new(301))
12687            .unwrap()
12688            .unwrap()
12689            .manifest
12690            .role_declarations
12691            .is_empty());
12692        let (raw, entry) = role_declarations_catalog(&handler);
12693        assert!(raw.get("role_declarations").is_none());
12694        assert!(entry.role_declarations.is_empty());
12695        let warnings: Vec<_> = capture
12696            .events()
12697            .into_iter()
12698            .filter(|event| {
12699                event.fields.get("message").map(String::as_str)
12700                    == Some("dropping whole role_declarations map from HELLO")
12701            })
12702            .collect();
12703        assert_eq!(warnings.len(), 1);
12704        assert_eq!(warnings[0].level, tracing::Level::WARN);
12705        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12706        assert_eq!(warnings[0].fields["reason"], reason);
12707    }
12708
12709    #[test]
12710    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12711        for value in [
12712            json!(null),
12713            json!(false),
12714            json!(0),
12715            json!("opaque"),
12716            json!([]),
12717        ] {
12718            assert_hello_drops_role_declarations_with_warning(
12719                json!({"routing/v1": {}, "broken/v1": value}),
12720                "role_declarations values must be objects",
12721            );
12722        }
12723        assert_hello_drops_role_declarations_with_warning(
12724            json!([]),
12725            "role_declarations must be an object",
12726        );
12727    }
12728
12729    #[test]
12730    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12731        assert_hello_drops_role_declarations_with_warning(
12732            json!({"routing/v1": {}, "bad key": {}}),
12733            "role_declarations key must use capability-name grammar",
12734        );
12735    }
12736
12737    #[test]
12738    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12739        assert_hello_drops_role_declarations_with_warning(
12740            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12741            "role_declarations exceeds 16384 compact JSON bytes",
12742        );
12743    }
12744
12745    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12746        let mut body = serde_json::to_value(ModuleHelloBody {
12747            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12748            protocol_ver: PROTOCOL_VERSION,
12749            control_ops: None,
12750            launch_nonce: None,
12751        })
12752        .unwrap();
12753        body["manifest"]["provides"] = json!([{
12754            "role": "management_surface",
12755            "operations": [
12756                {"name": "diagnostics.findings", "kind": "query"},
12757                {"name": "reset", "kind": "mutate"}
12758            ],
12759            "config_schema": {}, "observability": [], "identity_scope": []
12760        }]);
12761        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12762        if let Some(flow_operations) = flow_operations {
12763            body["manifest"]["flow_operations"] = flow_operations;
12764        }
12765        Frame::build(
12766            FrameType::Hello,
12767            control_flags(),
12768            0,
12769            0,
12770            401,
12771            serde_json::to_vec(&body).unwrap(),
12772        )
12773        .unwrap()
12774    }
12775
12776    #[test]
12777    fn catalog_list_mirrors_flow_operations_unchanged() {
12778        // Order is kept as declared (not sorted) and an empty list stays an
12779        // affirmative "none", distinct from an absent declaration.
12780        for (capability, flow_operations) in [
12781            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12782            ("call-modes/v1", json!(["diagnostics.findings"])),
12783            ("flow-scopes/v1", json!([])),
12784        ] {
12785            let registry = Arc::new(Registry::default());
12786            let handler = ControlHandler::new(Arc::clone(&registry));
12787            let connection = ConnectionId::new(401);
12788            let response = handler
12789                .handle_control(
12790                    connection,
12791                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12792                )
12793                .unwrap();
12794            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12795            let registered = registry
12796                .get_module_by_connection(connection)
12797                .unwrap()
12798                .unwrap()
12799                .manifest;
12800            assert_eq!(
12801                serde_json::to_value(&registered.flow_operations).unwrap(),
12802                flow_operations
12803            );
12804            let (raw, entry) = role_declarations_catalog(&handler);
12805            assert_eq!(raw["flow_operations"], flow_operations);
12806            assert_eq!(entry.flow_operations, registered.flow_operations);
12807        }
12808
12809        let registry = Arc::new(Registry::default());
12810        let handler = ControlHandler::new(Arc::clone(&registry));
12811        let response = handler
12812            .handle_control(
12813                ConnectionId::new(401),
12814                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12815            )
12816            .unwrap();
12817        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12818        let (raw, entry) = role_declarations_catalog(&handler);
12819        assert!(raw.get("flow_operations").is_none());
12820        assert_eq!(entry.flow_operations, None);
12821    }
12822
12823    #[test]
12824    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12825        let oversized: serde_json::Map<String, Value> = (0..257)
12826            .map(|n| (format!("tool:t{n}"), json!(true)))
12827            .collect();
12828        for (capabilities, map, valid) in [
12829            (
12830                json!(["scope-federated/v1"]),
12831                json!({"tool:read":true,"management:reset":true}),
12832                true,
12833            ),
12834            (json!(["scope-federated/v1"]), json!({}), true),
12835            (json!([]), json!({"tool:read":true}), false),
12836            (
12837                json!(["scope-federated/v1"]),
12838                json!({"tool:valid":true,"tool:bad":false}),
12839                false,
12840            ),
12841            (
12842                json!(["scope-federated/v1"]),
12843                json!({"tool:valid":true,"management:missing":true}),
12844                false,
12845            ),
12846            (
12847                json!(["scope-federated/v1"]),
12848                Value::Object(oversized),
12849                false,
12850            ),
12851        ] {
12852            let capture = EventCapture::default();
12853            let _subscriber = tracing::subscriber::set_default(
12854                tracing_subscriber::registry().with(capture.clone()),
12855            );
12856            let registry = Arc::new(Registry::default());
12857            let handler = ControlHandler::new(Arc::clone(&registry));
12858            let hello = hello_with_flow_operations(capabilities, None);
12859            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12860            body["manifest"]["operation_deferral"] = map.clone();
12861            let hello = Frame::build(
12862                FrameType::Hello,
12863                control_flags(),
12864                0,
12865                0,
12866                401,
12867                serde_json::to_vec(&body).unwrap(),
12868            )
12869            .unwrap();
12870            let response = handler
12871                .handle_control(ConnectionId::new(401), hello)
12872                .unwrap();
12873            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12874            let (raw, entry) = role_declarations_catalog(&handler);
12875            if valid {
12876                assert_eq!(raw["operation_deferral"], map);
12877                assert_eq!(
12878                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12879                    map
12880                );
12881            } else {
12882                assert!(entry.operation_deferral.is_none());
12883                assert!(raw.get("operation_deferral").is_none());
12884                assert_eq!(
12885                    capture
12886                        .events()
12887                        .iter()
12888                        .filter(|event| event.fields.get("message").map(String::as_str)
12889                            == Some("dropping operation_deferral from HELLO"))
12890                        .count(),
12891                    1
12892                );
12893            }
12894        }
12895    }
12896
12897    fn assert_hello_drops_flow_operations_with_warning(
12898        capabilities: Value,
12899        flow_operations: Value,
12900        reason: &str,
12901    ) {
12902        let registry = Arc::new(Registry::default());
12903        let handler = ControlHandler::new(Arc::clone(&registry));
12904        let capture = EventCapture::default();
12905        let _subscriber =
12906            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12907        let response = handler
12908            .handle_control(
12909                ConnectionId::new(401),
12910                hello_with_flow_operations(capabilities, Some(flow_operations)),
12911            )
12912            .unwrap();
12913        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12914        let registered = registry
12915            .get_module_by_connection(ConnectionId::new(401))
12916            .unwrap()
12917            .expect("the module still registers")
12918            .manifest;
12919        assert_eq!(registered.module_id, "flow-ops");
12920        assert_eq!(registered.flow_operations, None);
12921        let (raw, entry) = role_declarations_catalog(&handler);
12922        assert_eq!(raw["module_id"], "flow-ops");
12923        assert!(raw.get("flow_operations").is_none());
12924        assert_eq!(entry.flow_operations, None);
12925        let warnings: Vec<_> = capture
12926            .events()
12927            .into_iter()
12928            .filter(|event| {
12929                event.fields.get("message").map(String::as_str)
12930                    == Some("dropping flow_operations from HELLO")
12931            })
12932            .collect();
12933        assert_eq!(warnings.len(), 1);
12934        assert_eq!(warnings[0].level, tracing::Level::WARN);
12935        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12936        assert_eq!(warnings[0].fields["reason"], reason);
12937    }
12938
12939    #[test]
12940    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12941        assert_hello_drops_flow_operations_with_warning(
12942            json!(["flow-scopes/v1"]),
12943            json!(["diagnostics.findings", "missing"]),
12944            "flow_operations names 'missing', which is not a declared management operation",
12945        );
12946    }
12947
12948    #[test]
12949    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12950        assert_hello_drops_flow_operations_with_warning(
12951            json!([]),
12952            json!(["diagnostics.findings"]),
12953            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12954        );
12955        // A run-only capability does not admit flows either.
12956        assert_hello_drops_flow_operations_with_warning(
12957            json!(["agent-run-scopes/v1"]),
12958            json!([]),
12959            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12960        );
12961    }
12962
12963    #[test]
12964    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12965        assert_hello_drops_flow_operations_with_warning(
12966            json!(["flow-scopes/v1"]),
12967            json!(["reset", "reset"]),
12968            "flow_operations names 'reset' more than once",
12969        );
12970        assert_hello_drops_flow_operations_with_warning(
12971            json!(["flow-scopes/v1"]),
12972            json!(vec!["reset"; 257]),
12973            "flow_operations lists 257 names, more than 256",
12974        );
12975        assert_hello_drops_flow_operations_with_warning(
12976            json!(["flow-scopes/v1"]),
12977            json!("reset"),
12978            "flow_operations must be an array of operation names",
12979        );
12980    }
12981
12982    #[test]
12983    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12984        let registry = Arc::new(Registry::default());
12985        let handler = ControlHandler::new(registry.clone());
12986        let descriptor = json!({
12987            "schema": "ckios.richui.manifest/1",
12988            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12989            "bytes": 128,
12990            "chunks": 2
12991        });
12992        let malformed = [
12993            ("schema", json!("")),
12994            ("schema", json!("a".repeat(65))),
12995            ("schema", json!("Bad schema")),
12996            (
12997                "manifest_digest",
12998                json!(format!("sha256:{}", "A".repeat(64))),
12999            ),
13000            ("manifest_digest", json!("sha256:abc")),
13001            ("bytes", json!(0)),
13002            ("bytes", json!(16_777_217)),
13003            ("bytes", json!("128")),
13004            ("chunks", json!(0)),
13005            ("chunks", json!(1025)),
13006            ("chunks", json!("2")),
13007        ];
13008        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
13009            let mut invalid = descriptor.clone();
13010            invalid[field] = invalid_value;
13011            let response = handler
13012                .handle_control(
13013                    ConnectionId::new(210 + index as u64),
13014                    hello_frame_with_rich_ui(
13015                        &format!("bad-rich-ui-{index}"),
13016                        PROTOCOL_VERSION,
13017                        210 + index as u64,
13018                        None,
13019                        invalid,
13020                    ),
13021                )
13022                .unwrap();
13023            assert_eq!(response[0].header.ty, FrameType::Error);
13024            let error = parse_error(&response[0]);
13025            assert_eq!(error["code"], "invalid_manifest");
13026            assert!(error["message"]
13027                .as_str()
13028                .unwrap()
13029                .contains(&format!("rich_ui.{field}")));
13030            assert!(registry
13031                .get_module(&format!("bad-rich-ui-{index}"))
13032                .unwrap()
13033                .is_none());
13034        }
13035    }
13036
13037    #[test]
13038    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
13039        let registry = Arc::new(Registry::default());
13040        let handler = ControlHandler::new(Arc::clone(&registry));
13041        let connection = ConnectionId::new(219);
13042        registry
13043            .register_with_control_ops(
13044                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
13045                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
13046                        "bad schema",
13047                        format!("sha256:{}", "a".repeat(64)),
13048                        128,
13049                        2,
13050                    )))
13051                    .build(),
13052                PROTOCOL_VERSION,
13053                connection,
13054                Vec::new(),
13055            )
13056            .unwrap();
13057        let request =
13058            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
13059        let response = handler
13060            .handle_catalog_update(connection, request, Vec::new(), None, None)
13061            .unwrap();
13062        assert_eq!(response[0].header.ty, FrameType::Error);
13063        let error = parse_error(&response[0]);
13064        assert_eq!(error["code"], "invalid_manifest");
13065        assert!(error["message"]
13066            .as_str()
13067            .unwrap()
13068            .contains("rich_ui.schema"));
13069    }
13070
13071    #[test]
13072    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
13073        let registry = Arc::new(Registry::default());
13074        let supervisor = SupervisorHandle::new();
13075        supervisor.open_swap("provider", "candidate-nonce".to_string());
13076        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
13077        let connection = ConnectionId::new(218);
13078        let hello = handler
13079            .handle_control(
13080                connection,
13081                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
13082            )
13083            .unwrap();
13084        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13085        assert!(registry.list_modules().unwrap().1.is_empty());
13086
13087        registry.promote_candidate("provider").unwrap().unwrap();
13088        let request = Frame::build(
13089            FrameType::Request,
13090            control_flags(),
13091            0,
13092            0,
13093            219,
13094            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13095        )
13096        .unwrap();
13097        let response = handler.handle_catalog_list(request, None).unwrap();
13098        let ClientControlResponse::CatalogList { modules, .. } =
13099            serde_json::from_slice(&response[0].body).unwrap()
13100        else {
13101            panic!("expected catalog.list");
13102        };
13103        assert_eq!(modules.len(), 1);
13104        assert!(modules[0].nonce_verified);
13105    }
13106
13107    #[test]
13108    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
13109        for provenance_json in [
13110            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
13111            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
13112        ] {
13113            let registry = Arc::new(Registry::default());
13114            let handler = ControlHandler::new(registry);
13115            let hello = Frame::build(
13116                FrameType::Hello,
13117                control_flags(),
13118                0,
13119                0,
13120                220,
13121                serde_json::to_vec(&ModuleHelloBody {
13122                    manifest: ModuleManifest::builder("built", "0.1.0")
13123                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
13124                        .build(),
13125                    protocol_ver: PROTOCOL_VERSION,
13126                    control_ops: None,
13127                    launch_nonce: None,
13128                })
13129                .unwrap(),
13130            )
13131            .unwrap();
13132            assert_eq!(
13133                handler
13134                    .handle_control(ConnectionId::new(220), hello)
13135                    .unwrap()[0]
13136                    .header
13137                    .ty,
13138                FrameType::HelloAck
13139            );
13140            let request = Frame::build(
13141                FrameType::Request,
13142                control_flags(),
13143                0,
13144                0,
13145                221,
13146                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13147            )
13148            .unwrap();
13149            let response = handler.handle_catalog_list(request, None).unwrap();
13150            let ClientControlResponse::CatalogList { modules, .. } =
13151                serde_json::from_slice(&response[0].body).unwrap()
13152            else {
13153                panic!("expected catalog.list");
13154            };
13155            assert_eq!(modules.len(), 1);
13156            assert_eq!(
13157                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
13158                format!(
13159                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
13160                )
13161                .as_bytes()
13162            );
13163        }
13164    }
13165
13166    #[test]
13167    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
13168        let registry = Arc::new(Registry::default());
13169        let handler = ControlHandler::new(Arc::clone(&registry));
13170        let hello = Frame::build(
13171            FrameType::Hello,
13172            control_flags(),
13173            0,
13174            0,
13175            220,
13176            serde_json::to_vec(&ModuleHelloBody {
13177                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
13178                protocol_ver: PROTOCOL_VERSION,
13179                control_ops: None,
13180                launch_nonce: Some("unverified".to_string()),
13181            })
13182            .unwrap(),
13183        )
13184        .unwrap();
13185        assert_eq!(
13186            handler
13187                .handle_control(ConnectionId::new(220), hello)
13188                .unwrap()[0]
13189                .header
13190                .ty,
13191            FrameType::HelloAck
13192        );
13193        let request = Frame::build(
13194            FrameType::Request,
13195            control_flags(),
13196            0,
13197            0,
13198            221,
13199            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13200        )
13201        .unwrap();
13202        let response = handler.handle_catalog_list(request, None).unwrap();
13203        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
13204        assert!(wire["modules"][0].get("provenance").is_none());
13205        let ClientControlResponse::CatalogList { modules, .. } =
13206            serde_json::from_slice(&response[0].body).unwrap()
13207        else {
13208            panic!("expected catalog.list");
13209        };
13210        assert_eq!(
13211            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
13212            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
13213        );
13214        assert!(!modules[0].nonce_verified);
13215        assert!(modules[0].provenance.is_none());
13216    }
13217
13218    // Preserve the legacy-field byte pins while discovery adds optional facts.
13219    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
13220        assert_eq!(entry.first_party, Some(false));
13221        entry.incarnation = None;
13222        entry.spawn = None;
13223        entry.first_party = None;
13224        entry.origin = None;
13225        entry.requested_declarations_digest = None;
13226        entry.approved_declarations_digest = None;
13227        entry
13228    }
13229
13230    #[test]
13231    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
13232        let registry = Arc::new(Registry::default());
13233        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13234            [("vault".to_string(), true), ("squatter".to_string(), true)],
13235            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13236        );
13237        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
13238        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13239            provides: vec!["credentials-provider/v1".to_string()],
13240            requires: Vec::new(),
13241            must_never_reach: Vec::new(),
13242        });
13243        let frame = Frame::build(
13244            FrameType::Hello,
13245            control_flags(),
13246            0,
13247            0,
13248            77,
13249            serde_json::to_vec(&ModuleHelloBody {
13250                manifest: squatter,
13251                protocol_ver: PROTOCOL_VERSION,
13252                control_ops: None,
13253                launch_nonce: None,
13254            })
13255            .expect("HELLO serializes"),
13256        )
13257        .expect("HELLO frame builds");
13258        let response = handler
13259            .handle_control(ConnectionId::new(77), frame)
13260            .expect("reserved claim receives a typed refusal");
13261        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13262        assert_eq!(
13263            registry
13264                .active_registration_count()
13265                .expect("registry reads"),
13266            0,
13267            "a reserved capability refusal must not leave a catalog entry"
13268        );
13269    }
13270
13271    #[test]
13272    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
13273        for settlement in ["timeout", "inconclusive", "drop"] {
13274            let breakers = RouteBindBreakers::default();
13275            let RouteBindAdmission::Admitted {
13276                guard: mut old,
13277                probe: false,
13278            } = breakers.admit("prov")
13279            else {
13280                panic!("ordinary relay admitted")
13281            };
13282            let RouteBindAdmission::Admitted {
13283                guard: mut opener, ..
13284            } = breakers.admit("prov")
13285            else {
13286                panic!("second relay admitted")
13287            };
13288            assert!(
13289                !opener
13290                    .record_timeout(1, Duration::ZERO)
13291                    .unwrap()
13292                    .reopened_after_probe
13293            );
13294            let RouteBindAdmission::Admitted {
13295                guard: mut probe,
13296                probe: true,
13297            } = breakers.admit("prov")
13298            else {
13299                panic!("one cooldown probe admitted")
13300            };
13301            match settlement {
13302                "timeout" => assert!(
13303                    !old.record_timeout(1, Duration::ZERO)
13304                        .unwrap()
13305                        .reopened_after_probe
13306                ),
13307                "inconclusive" => old.record_inconclusive(),
13308                "drop" => drop(old),
13309                _ => unreachable!(),
13310            }
13311            assert!(
13312                matches!(
13313                    breakers.admit("prov"),
13314                    RouteBindAdmission::Refused {
13315                        probe_in_flight: true,
13316                        ..
13317                    }
13318                ),
13319                "{settlement} of a pre-open relay cannot release the real probe"
13320            );
13321            assert!(
13322                probe
13323                    .record_timeout(1, Duration::ZERO)
13324                    .unwrap()
13325                    .reopened_after_probe
13326            );
13327            assert!(matches!(
13328                breakers.admit("prov"),
13329                RouteBindAdmission::Admitted { probe: true, .. }
13330            ));
13331        }
13332        let breakers = RouteBindBreakers::default();
13333        let admit = || match breakers.admit("prov") {
13334            RouteBindAdmission::Admitted { guard, .. } => guard,
13335            _ => panic!("relay admitted"),
13336        };
13337        admit().record_timeout(1, Duration::ZERO);
13338        let mut old_probe = admit();
13339        breakers.reset_for_new_module_connection("prov");
13340        admit().record_timeout(1, Duration::ZERO);
13341        let _new_probe = admit();
13342        old_probe.record_inconclusive();
13343        assert!(matches!(
13344            breakers.admit("prov"),
13345            RouteBindAdmission::Refused {
13346                probe_in_flight: true,
13347                ..
13348            }
13349        ));
13350    }
13351
13352    #[tokio::test]
13353    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13354        for candidate in [false, true] {
13355            let registry = Arc::new(Registry::default());
13356            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13357                [("vault".to_string(), true), ("squatter".to_string(), true)],
13358                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13359            );
13360            let conn = ConnectionId::new(77);
13361            let (ctx, mut rx) = route_ctx(conn);
13362            let initial = capability_manifest("squatter", &[], &[]);
13363            if candidate {
13364                registry
13365                    .register_candidate_with_control_ops(
13366                        initial.clone(),
13367                        PROTOCOL_VERSION,
13368                        conn,
13369                        module_baseline_control_ops(),
13370                    )
13371                    .unwrap();
13372                handler
13373                    .forwarding
13374                    .register_candidate_module_connection(
13375                        conn,
13376                        "squatter".to_string(),
13377                        PROTOCOL_VERSION,
13378                        manifest_concurrency(&initial),
13379                        ctx.egress.clone(),
13380                    )
13381                    .unwrap();
13382            } else {
13383                hello_via_sink(
13384                    &handler,
13385                    &ctx,
13386                    &mut rx,
13387                    hello_frame_with_manifest(initial.clone(), 1),
13388                )
13389                .await;
13390            }
13391            let response = handler
13392                .handle_control_frame(
13393                    &ctx,
13394                    catalog_update_with_capabilities_frame(
13395                        2,
13396                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13397                            .capabilities
13398                            .unwrap(),
13399                    ),
13400                )
13401                .await
13402                .unwrap();
13403            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13404            assert_eq!(
13405                registry
13406                    .get_module_by_connection(conn)
13407                    .unwrap()
13408                    .unwrap()
13409                    .manifest,
13410                initial
13411            );
13412        }
13413    }
13414
13415    #[test]
13416    #[cfg(not(feature = "dev-desktop-approval"))]
13417    fn server_describe_default_build_advertises_no_config_capability() {
13418        let assert_default = |handler: &ControlHandler| {
13419            let request = Frame::build(
13420                FrameType::Request,
13421                control_flags(),
13422                0,
13423                0,
13424                79,
13425                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13426            )
13427            .unwrap();
13428            let responses = handler.handle_server_describe(request).unwrap();
13429            assert_eq!(responses.len(), 1);
13430            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13431            assert_eq!(response["op"], "server.describe");
13432            let capabilities = response["capabilities"]
13433                .as_array()
13434                .expect("capability array");
13435            assert!(
13436                !capabilities.is_empty(),
13437                "exercise an actual describe response, not an empty fixture"
13438            );
13439            assert!(
13440                capabilities
13441                    .iter()
13442                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13443                "a default build must not announce configuration authority: {capabilities:?}"
13444            );
13445        };
13446        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13447        #[cfg(unix)]
13448        {
13449            // A local store does not prove that project-membership validation,
13450            // active-scope usage tracking and approved-program launch selection
13451            // are connected. Defaults must not advertise that authority.
13452            let (_rig, _owner, _supervisor, handler, _spec) =
13453                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13454                );
13455            assert_default(&handler);
13456        }
13457    }
13458
13459    #[test]
13460    fn server_describe_surfaces_required_capability_verdict_fields() {
13461        let registry = Arc::new(Registry::default());
13462        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13463            [
13464                ("consumer".to_string(), true),
13465                ("provider".to_string(), false),
13466            ],
13467            BTreeMap::new(),
13468        );
13469        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13470        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13471            provides: Vec::new(),
13472            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13473                capability: "credentials-provider/v1".to_string(),
13474                need: subc_protocol::manifest::CapabilityNeed::Required,
13475            }],
13476            must_never_reach: Vec::new(),
13477        });
13478        let hello = Frame::build(
13479            FrameType::Hello,
13480            control_flags(),
13481            0,
13482            0,
13483            78,
13484            serde_json::to_vec(&ModuleHelloBody {
13485                manifest: consumer,
13486                protocol_ver: PROTOCOL_VERSION,
13487                control_ops: None,
13488                launch_nonce: None,
13489            })
13490            .expect("HELLO serializes"),
13491        )
13492        .expect("HELLO frame builds");
13493        handler
13494            .handle_control(ConnectionId::new(78), hello)
13495            .expect("consumer registers");
13496        let describe = Frame::build(
13497            FrameType::Request,
13498            control_flags(),
13499            0,
13500            0,
13501            79,
13502            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13503                .expect("request serializes"),
13504        )
13505        .expect("describe frame builds");
13506        let response = handler
13507            .handle_server_describe(describe)
13508            .expect("server.describe succeeds");
13509        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13510        let requirement = &rendered["capability_requirements"][0];
13511        assert_eq!(requirement["consumer"], "consumer");
13512        assert_eq!(requirement["verdict"], "never_provided");
13513        assert_eq!(requirement["episode_seq"], 1);
13514        assert_eq!(requirement["config_satisfiable"], false);
13515        assert_eq!(requirement["runtime_available"], false);
13516        assert!(requirement["detail"]
13517            .as_str()
13518            .expect("detail string")
13519            .contains("credentials-provider/v1"));
13520    }
13521
13522    /// Register a consumer that requires `project-identity/v1` and the provider
13523    /// of it, optionally mark daemon shutdown as begun, then deregister the
13524    /// provider as its connection closes. Returns the `capability.requirement`
13525    /// events that deregistration logged and the verdict the evaluator then
13526    /// holds for the requirement (the one `route.open` refusals read).
13527    fn deregister_required_provider(
13528        daemon_shutdown_begun: bool,
13529    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13530        const CAPABILITY: &str = "project-identity/v1";
13531        let registry = Arc::new(Registry::default());
13532        let daemon_shutdown = DaemonShutdownFlag::default();
13533        let handler = ControlHandler::new(Arc::clone(&registry))
13534            .with_capability_config(
13535                [
13536                    ("consumer".to_string(), true),
13537                    ("provider".to_string(), true),
13538                ],
13539                BTreeMap::new(),
13540            )
13541            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13542        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13543        consumer.capabilities = Some(CapabilityDeclarations {
13544            provides: Vec::new(),
13545            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13546                capability: CAPABILITY.to_string(),
13547                need: subc_protocol::manifest::CapabilityNeed::Required,
13548            }],
13549            must_never_reach: Vec::new(),
13550        });
13551        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13552        let provider_conn = ConnectionId::new(182);
13553        for (conn, manifest, corr) in [
13554            (ConnectionId::new(181), consumer, 181),
13555            (provider_conn, provider, 182),
13556        ] {
13557            let hello = handler
13558                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13559                .expect("module registers");
13560            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13561        }
13562        assert_eq!(
13563            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13564            Some(CapabilityVerdict::Provided),
13565            "the registered provider must satisfy the requirement first"
13566        );
13567        if daemon_shutdown_begun {
13568            daemon_shutdown.set_for_test();
13569        }
13570
13571        let capture = EventCapture::default();
13572        let _subscriber =
13573            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13574        handler
13575            .cleanup_connection(provider_conn)
13576            .expect("provider deregisters");
13577        let events = capture
13578            .events()
13579            .into_iter()
13580            .filter(|event| {
13581                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13582            })
13583            .collect();
13584        (
13585            events,
13586            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13587        )
13588    }
13589
13590    #[test]
13591    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13592        let (events, verdict) = deregister_required_provider(true);
13593        assert_eq!(
13594            verdict,
13595            Some(CapabilityVerdict::NeverProvided),
13596            "shutdown must not change the verdict route.open refusals read"
13597        );
13598        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13599        let event = &events[0];
13600        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13601        assert_eq!(
13602            event.fields.get("cause").map(String::as_str),
13603            Some("\"daemon_shutdown\""),
13604            "{event:?}"
13605        );
13606        assert_eq!(
13607            event.fields.get("verdict").map(String::as_str),
13608            Some("\"never_provided\""),
13609            "{event:?}"
13610        );
13611    }
13612
13613    #[test]
13614    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13615        let (events, verdict) = deregister_required_provider(false);
13616        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13617        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13618        let event = &events[0];
13619        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13620        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13621        assert_eq!(
13622            event.fields.get("verdict").map(String::as_str),
13623            Some("\"never_provided\""),
13624            "{event:?}"
13625        );
13626    }
13627
13628    #[test]
13629    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13630        let registry = Arc::new(Registry::default());
13631        let handler = ControlHandler::new(Arc::clone(&registry));
13632        let hello = handler
13633            .handle_control(
13634                ConnectionId::new(101),
13635                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13636            )
13637            .expect("legacy HELLO registers");
13638        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13639
13640        let request = Frame::build(
13641            FrameType::Request,
13642            control_flags(),
13643            0,
13644            0,
13645            102,
13646            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13647                .expect("catalog request serializes"),
13648        )
13649        .expect("catalog request frame builds");
13650        let response = handler
13651            .handle_catalog_list(request, None)
13652            .expect("catalog list succeeds");
13653        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13654        assert!(
13655            body["modules"][0].get("capabilities").is_none(),
13656            "legacy manifest must retain an absent capabilities field on catalog.list"
13657        );
13658    }
13659
13660    #[test]
13661    fn hello_ack_omits_storage_when_no_storage_config() {
13662        let registry = Arc::new(Registry::default());
13663        let handler = ControlHandler::new(Arc::clone(&registry));
13664        let responses = handler
13665            .handle_control(
13666                ConnectionId::new(1),
13667                hello_frame("aft", PROTOCOL_VERSION, 7),
13668            )
13669            .unwrap();
13670        let ack = parse_ack(&responses[0]);
13671        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13672        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13673    }
13674
13675    #[tokio::test]
13676    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13677        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13678        let registry = Arc::new(Registry::default());
13679        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13680        let responses = handler
13681            .handle_control(
13682                ConnectionId::new(1),
13683                hello_frame("aft", PROTOCOL_VERSION, 7),
13684            )
13685            .unwrap();
13686        let ack = parse_ack(&responses[0]);
13687        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13688
13689        let described = handler
13690            .handle_control_frame(
13691                &route_ctx(ConnectionId::new(2)).0,
13692                Frame::build(
13693                    FrameType::Request,
13694                    control_flags(),
13695                    0,
13696                    0,
13697                    9,
13698                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13699                )
13700                .unwrap(),
13701            )
13702            .await
13703            .unwrap();
13704        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13705            serde_json::from_slice(&described[0].body).unwrap()
13706        else {
13707            panic!("server.describe answered with another shape");
13708        };
13709        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13710    }
13711
13712    #[test]
13713    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13714        // With a central sqlite storage policy, each registering module gets its
13715        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13716        let registry = Arc::new(Registry::default());
13717        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13718            crate::daemon_config::StorageConfig::Sqlite {
13719                data_home: std::path::PathBuf::from("/data"),
13720            },
13721        ));
13722
13723        let responses = handler
13724            .handle_control(
13725                ConnectionId::new(1),
13726                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13727            )
13728            .unwrap();
13729        let ack = parse_ack(&responses[0]);
13730        assert_eq!(
13731            ack.storage,
13732            Some(serde_json::json!({
13733                "module_id": "alfonso-routing",
13734                "storage_namespace": "default",
13735                "isolation": { "kind": "module" },
13736                "backend": {
13737                    "backend": "sqlite",
13738                    "path": "/data/cortexkit/alfonso-routing/store.db"
13739                }
13740            })),
13741            "the delivered descriptor is the module's own sqlite store path"
13742        );
13743    }
13744
13745    #[test]
13746    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13747        let registry = Arc::new(Registry::default());
13748        let handler = ControlHandler::new(Arc::clone(&registry));
13749        let conn = ConnectionId::new(1);
13750        let responses = handler
13751            .handle_control(
13752                conn,
13753                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13754            )
13755            .unwrap();
13756        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13757        let registration = registry.get_module("aft").unwrap().unwrap();
13758        assert_eq!(registration.control_ops, module_baseline_control_ops());
13759
13760        let frame =
13761            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13762        assert!(handler
13763            .guard_module_control_op(&frame, "aft", "route.bind")
13764            .unwrap()
13765            .is_none());
13766        let error = handler
13767            .guard_module_control_op(&frame, "aft", "test.synthetic")
13768            .unwrap()
13769            .expect("synthetic ungranted op should be rejected");
13770        assert_eq!(error.header.ty, FrameType::Error);
13771        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13772    }
13773
13774    #[test]
13775    fn hello_control_ops_some_adds_optional_grants() {
13776        let registry = Arc::new(Registry::default());
13777        let handler = ControlHandler::new(Arc::clone(&registry));
13778        handler
13779            .handle_control(
13780                ConnectionId::new(1),
13781                hello_frame_with_control_ops(
13782                    "aft",
13783                    PROTOCOL_VERSION,
13784                    7,
13785                    Some(vec![
13786                        "future.synthetic".to_string(),
13787                        "route.bind".to_string(),
13788                    ]),
13789                ),
13790            )
13791            .unwrap();
13792        let registration = registry.get_module("aft").unwrap().unwrap();
13793        assert_eq!(
13794            registration.control_ops,
13795            vec![
13796                "route.bind".to_string(),
13797                "route.status".to_string(),
13798                "future.synthetic".to_string(),
13799            ]
13800        );
13801        let frame =
13802            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13803        assert!(handler
13804            .guard_module_control_op(&frame, "aft", "future.synthetic")
13805            .unwrap()
13806            .is_none());
13807    }
13808
13809    #[tokio::test]
13810    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13811        let registry = Arc::new(Registry::default());
13812        let forwarding = Arc::new(ForwardingTable::default());
13813        let handler =
13814            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13815        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13816        hello_via_sink(
13817            &handler,
13818            &module_ctx,
13819            &mut module_rx,
13820            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13821        )
13822        .await;
13823
13824        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13825        let responses = handler
13826            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13827            .await
13828            .unwrap();
13829        assert_eq!(responses.len(), 1);
13830        assert_eq!(responses[0].header.ty, FrameType::Error);
13831        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13832        assert!(module_rx.try_recv().is_err());
13833    }
13834
13835    #[tokio::test]
13836    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13837        let registry = Arc::new(Registry::default());
13838        let forwarding = Arc::new(ForwardingTable::default());
13839        let handler =
13840            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13841        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13842        hello_via_sink(
13843            &handler,
13844            &module_ctx,
13845            &mut module_rx,
13846            hello_frame_with_control_ops(
13847                "aft",
13848                PROTOCOL_VERSION,
13849                7,
13850                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13851            ),
13852        )
13853        .await;
13854
13855        let project_root = unique_project_root("demux");
13856        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13857        let route_handler = handler.clone();
13858        let route_task = tokio::spawn(async move {
13859            route_handler
13860                .handle_control_frame(
13861                    &route_client_ctx,
13862                    route_open_frame(100, "aft", project_root),
13863                )
13864                .await
13865                .unwrap()
13866        });
13867        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13868            .await
13869            .unwrap()
13870            .unwrap();
13871        assert!(matches!(
13872            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13873            ModuleControlRequest::RouteBind { .. }
13874        ));
13875
13876        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13877        let health_handler = handler.clone();
13878        let health_task = tokio::spawn(async move {
13879            health_handler
13880                .handle_control_frame(
13881                    &health_client_ctx,
13882                    supervisor_health_probe_frame(101, "aft"),
13883                )
13884                .await
13885                .unwrap()
13886        });
13887        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13888            .await
13889            .unwrap()
13890            .unwrap();
13891        assert_eq!(
13892            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13893            ModuleControlRequest::HealthCheck {}
13894        );
13895
13896        handler
13897            .handle_control_frame(
13898                &module_ctx,
13899                health_response(health_frame.header.corr, HealthStatus::Degraded),
13900            )
13901            .await
13902            .unwrap();
13903        let health_response = health_task.await.unwrap();
13904        assert_eq!(health_response.len(), 1);
13905        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13906            ClientControlResponse::SupervisorHealthProbe {
13907                module_id,
13908                status,
13909                detail,
13910                metrics,
13911            } => {
13912                assert_eq!(module_id, "aft");
13913                assert_eq!(status, HealthStatus::Degraded);
13914                assert_eq!(detail.as_deref(), Some("warming"));
13915                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13916            }
13917            other => panic!("unexpected health response: {other:?}"),
13918        }
13919
13920        handler
13921            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13922            .await
13923            .unwrap();
13924        let route_response = route_task.await.unwrap();
13925        assert!(route_response.is_empty());
13926        let published = route_client_rx.recv().await.unwrap();
13927        assert!(matches!(
13928            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13929            ClientControlResponse::RouteOpen { .. }
13930        ));
13931    }
13932
13933    /// Start one `route.open` on `client_connection` and return its still-running
13934    /// handler task together with the `route.bind` the module received for it.
13935    /// The handler blocks until the module answers, so it has to run as a task
13936    /// while the test drives the module side.
13937    async fn relay_route_open(
13938        handler: &ControlHandler,
13939        client_connection: ConnectionId,
13940        client_egress: &FrameSink,
13941        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13942        corr: u64,
13943        module_id: &str,
13944        project_root_label: &str,
13945    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13946        let ctx = RouteCtx {
13947            connection_id: client_connection,
13948            egress: client_egress.clone(),
13949        };
13950        let handler = handler.clone();
13951        let project_root = unique_project_root(project_root_label);
13952        let module_id = module_id.to_string();
13953        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13954        let task = tokio::spawn(async move {
13955            let _guard = tracing::dispatcher::set_default(&dispatch);
13956            handler
13957                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13958                .await
13959                .unwrap()
13960        });
13961        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13962            .await
13963            .expect("module receives the relayed route.bind")
13964            .expect("module egress is open");
13965        (task, bind.frame)
13966    }
13967
13968    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13969        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13970            ModuleControlRequest::RouteBind {
13971                route_channel,
13972                epoch,
13973                ..
13974            } => (route_channel, epoch),
13975            other => panic!("expected a route.bind request, got {other:?}"),
13976        }
13977    }
13978
13979    fn published_route(frame: &Frame) -> (u16, u32) {
13980        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13981            ClientControlResponse::RouteOpen {
13982                route_channel,
13983                route_epoch,
13984                ..
13985            } => (route_channel, route_epoch),
13986            other => panic!("expected a route.open response, got {other:?}"),
13987        }
13988    }
13989
13990    /// Reproduction of a production outage. A client had `route.open`s in
13991    /// flight to a module and was already marked closing -- its egress had refused a
13992    /// module frame, so the daemon asked its connection to end -- while its sink
13993    /// was still open. When the module acked those binds, the daemon refused to
13994    /// commit a route for a closing client, and that refusal was returned from
13995    /// the MODULE connection's frame handler, where a router error that has no
13996    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13997    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13998    /// its tools for hours -- one client's teardown took down a connection
13999    /// carrying ~170 other routes.
14000    ///
14001    /// The window is opened here by calling the production path that opens it
14002    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
14003    /// state that matters is "in `closing_connections`, sink still open, relay
14004    /// still pending", and it lasts only from the close request until the
14005    /// connection loop reacts to it; a socket-level test can flood a client into
14006    /// that escalation but cannot pin the module's ack inside the window. Closing
14007    /// the socket instead takes the other path entirely -- connection teardown
14008    /// removes the pending relay under the same lock, so the ack finds nothing.
14009    #[tokio::test]
14010    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
14011        let registry = Arc::new(Registry::default());
14012        let forwarding = Arc::new(ForwardingTable::default());
14013        let handler =
14014            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
14015
14016        let module_connection = ConnectionId::new(30);
14017        let (module_ctx, mut module_rx) = route_ctx(module_connection);
14018        hello_via_sink(
14019            &handler,
14020            &module_ctx,
14021            &mut module_rx,
14022            hello_frame("aft", PROTOCOL_VERSION, 7),
14023        )
14024        .await;
14025
14026        let dying_client = ConnectionId::new(31);
14027        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
14028
14029        // A published route on the dying client. The escalation below only marks
14030        // a connection closing for a route it has already published.
14031        let (first_task, first_bind) = relay_route_open(
14032            &handler,
14033            dying_client,
14034            &dying_ctx.egress,
14035            &mut module_rx,
14036            100,
14037            "aft",
14038            "closing-first",
14039        )
14040        .await;
14041        handler
14042            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
14043            .await
14044            .unwrap();
14045        assert!(first_task.await.unwrap().is_empty());
14046        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
14047
14048        // A second route.open from the same client, relayed and awaiting its ack.
14049        let (second_task, second_bind) = relay_route_open(
14050            &handler,
14051            dying_client,
14052            &dying_ctx.egress,
14053            &mut module_rx,
14054            101,
14055            "aft",
14056            "closing-second",
14057        )
14058        .await;
14059        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
14060
14061        // The window: the client is closing, its sink is still open, and its
14062        // second bind is still pending.
14063        assert!(forwarding
14064            .escalate_client_delivery_failure(
14065                dying_client,
14066                first_channel,
14067                first_epoch,
14068                CloseReason::new(
14069                    "module_to_client_delivery_failed",
14070                    "client egress refused a module frame",
14071                ),
14072                crate::forwarding::UndeliveredFrame {
14073                    module_id: None,
14074                    sink: &dying_ctx.egress,
14075                },
14076            )
14077            .unwrap());
14078        assert!(!dying_ctx.egress.is_closed());
14079
14080        // The frame that used to end the module connection.
14081        let ack = handler
14082            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
14083            .await;
14084        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
14085        if module_loop_error.is_some() {
14086            // What the server's connection loop does with a router error that has
14087            // no ERROR-frame translation: end the connection, which releases the
14088            // module's registration and every route on it.
14089            handler.cleanup_connection(module_connection).unwrap();
14090        }
14091        // Read the module's next frame before opening the co-tenant's route, so
14092        // the GOODBYE assertion below is about THIS ack and not about later
14093        // traffic. `None` means the module was told nothing.
14094        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
14095            .await
14096            .ok()
14097            .flatten();
14098
14099        // 1. The module connection is still registered.
14100        assert!(
14101            registry
14102                .get_module_by_connection(module_connection)
14103                .unwrap()
14104                .is_some(),
14105            "one client's closing connection ended the shared module connection: \
14106             {module_loop_error:?}"
14107        );
14108        // ...and still serving: another client can open and use a route on it.
14109        let cotenant = ConnectionId::new(32);
14110        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
14111        let (cotenant_task, cotenant_bind) = relay_route_open(
14112            &handler,
14113            cotenant,
14114            &cotenant_ctx.egress,
14115            &mut module_rx,
14116            102,
14117            "aft",
14118            "closing-cotenant",
14119        )
14120        .await;
14121        handler
14122            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
14123            .await
14124            .unwrap();
14125        assert!(cotenant_task.await.unwrap().is_empty());
14126        let (cotenant_channel, cotenant_epoch) =
14127            published_route(&cotenant_rx.recv().await.unwrap());
14128        assert!(matches!(
14129            forwarding
14130                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
14131                .unwrap(),
14132            DataRoute::Client(DataRouteState::Bound(_))
14133        ));
14134
14135        // 2. The module was told to drop the binding it created for the route
14136        //    that will never be published.
14137        let goodbye = post_ack_module_frame
14138            .expect("module receives a GOODBYE for the abandoned route channel");
14139        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14140        assert_eq!(goodbye.header.channel, abandoned_channel);
14141        assert_eq!(goodbye.header.epoch, abandoned_epoch);
14142
14143        // 3. The dying client received nothing: no route was ever published to
14144        //    it. Its route.open is answered as unavailable, which the connection
14145        //    loop would write to a socket that is already going away.
14146        assert!(dying_rx.try_recv().is_err());
14147        let second_response = second_task.await.unwrap();
14148        assert_eq!(second_response.len(), 1);
14149        assert_eq!(
14150            parse_error(&second_response[0])["code"],
14151            "target_unavailable"
14152        );
14153    }
14154
14155    /// One `catalog.list` as a client sees it: the generation and the listed
14156    /// module ids with their readiness.
14157    async fn catalog_snapshot(
14158        handler: &ControlHandler,
14159        client_ctx: &RouteCtx,
14160        corr: u64,
14161    ) -> (u64, Vec<(String, bool)>) {
14162        let body =
14163            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
14164        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
14165        let reply = handler
14166            .handle_control_frame(client_ctx, request)
14167            .await
14168            .unwrap()
14169            .pop()
14170            .unwrap();
14171        let ClientControlResponse::CatalogList {
14172            generation,
14173            modules,
14174            ..
14175        } = serde_json::from_slice(&reply.body).unwrap()
14176        else {
14177            panic!("not a catalog.list reply");
14178        };
14179        (
14180            generation,
14181            modules
14182                .into_iter()
14183                .map(|entry| (entry.module_id, entry.ready))
14184                .collect(),
14185        )
14186    }
14187
14188    /// A handler whose HELLO for module "aft" on connection 40 is parked
14189    /// between reserving its registry entry and installing its forwarding
14190    /// endpoint. Returns the handler, the two-party barrier (wait once to know
14191    /// the HELLO is parked, once more to release it), the HELLO's thread, and
14192    /// the module's context and receiver.
14193    fn hello_held_before_forwarding() -> (
14194        ControlHandler,
14195        Arc<std::sync::Barrier>,
14196        std::thread::JoinHandle<Vec<Frame>>,
14197        RouteCtx,
14198        mpsc::Receiver<crate::router::OutboundFrame>,
14199    ) {
14200        let hold = Arc::new(std::sync::Barrier::new(2));
14201        let handler = ControlHandler::with_forwarding(
14202            Arc::new(Registry::default()),
14203            Arc::new(ForwardingTable::default()),
14204        )
14205        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
14206        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14207        let hello = {
14208            let handler = handler.clone();
14209            let module_ctx = module_ctx.clone();
14210            std::thread::spawn(move || {
14211                handler
14212                    .handle_hello(
14213                        module_ctx.connection_id,
14214                        Some(module_ctx.egress.clone()),
14215                        hello_frame("aft", PROTOCOL_VERSION, 7),
14216                    )
14217                    .unwrap()
14218            })
14219        };
14220        (handler, hold, hello, module_ctx, module_rx)
14221    }
14222
14223    /// If a lookup can acquire the registry while publication is parked, let
14224    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
14225    /// after the lookup has tried the lock. Both schedules avoid timing guesses
14226    /// and return the actual lookup result, including an unpublished snapshot
14227    /// when the publication lock is missing.
14228    fn lookup_during_hello_publication<T: Send + 'static>(
14229        registry: &Registry,
14230        hold: &std::sync::Barrier,
14231        lookup: impl FnOnce() -> T + Send + 'static,
14232    ) -> T {
14233        let attempted = registry.observe_next_lock_attempt();
14234        let reader = std::thread::spawn(lookup);
14235        if attempted.recv().unwrap() {
14236            let result = reader.join().unwrap();
14237            hold.wait();
14238            result
14239        } else {
14240            hold.wait();
14241            reader.join().unwrap()
14242        }
14243    }
14244
14245    #[test]
14246    fn catalog_read_after_hello_ack_waits_for_publication() {
14247        let registry = Arc::new(Registry::default());
14248        let hold = Arc::new(std::sync::Barrier::new(2));
14249        let mut handler = ControlHandler::with_forwarding(
14250            Arc::clone(&registry),
14251            Arc::new(ForwardingTable::default()),
14252        );
14253        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
14254        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14255        let hello = {
14256            let handler = handler.clone();
14257            std::thread::spawn(move || {
14258                handler
14259                    .handle_hello(
14260                        module_ctx.connection_id,
14261                        Some(module_ctx.egress),
14262                        hello_frame("aft", PROTOCOL_VERSION, 7),
14263                    )
14264                    .unwrap()
14265            })
14266        };
14267        hold.wait();
14268        assert_eq!(
14269            module_rx.try_recv().unwrap().frame.header.ty,
14270            FrameType::HelloAck
14271        );
14272        let replies = lookup_during_hello_publication(&registry, &hold, move || {
14273            // A different connection can issue catalog.list as soon as the
14274            // module has read its ACK, even while HELLO has not returned.
14275            let request = Frame::build(
14276                FrameType::Request,
14277                control_flags(),
14278                0,
14279                0,
14280                300,
14281                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
14282            )
14283            .unwrap();
14284            handler.handle_catalog_list(request, None).unwrap()
14285        });
14286        assert!(hello.join().unwrap().is_empty());
14287        let ClientControlResponse::CatalogList {
14288            generation,
14289            modules,
14290            ..
14291        } = serde_json::from_slice(&replies[0].body).unwrap()
14292        else {
14293            panic!("not a catalog.list reply");
14294        };
14295        assert_eq!(
14296            modules
14297                .iter()
14298                .map(|entry| entry.module_id.as_str())
14299                .collect::<Vec<_>>(),
14300            vec!["aft"]
14301        );
14302        assert_eq!(generation, 1);
14303    }
14304
14305    /// While a HELLO has reserved its registry entry but its forwarding
14306    /// endpoint is not installed yet, `route.open` to the module can only be
14307    /// refused. `catalog.list` must not list the module in that window: a
14308    /// client that opens a route as soon as it sees a module listed and ready
14309    /// would be refused for a module the daemon had just advertised. The
14310    /// refusal in the window stays the retryable `target_unavailable`, never
14311    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14312    /// Once the HELLO completes, the module is listed and a route to it opens.
14313    #[tokio::test]
14314    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14315        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14316        let client = ConnectionId::new(41);
14317        let (client_ctx, mut client_rx) = route_ctx(client);
14318
14319        hold.wait();
14320        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14321        assert!(handler.registry.get_module("aft").unwrap().is_some());
14322        assert!(!handler
14323            .forwarding
14324            .has_live_module_connection("aft")
14325            .unwrap());
14326        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14327        assert!(
14328            listed.is_empty(),
14329            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14330        );
14331        let refused = handler
14332            .handle_control_frame(
14333                &client_ctx,
14334                route_open_frame(301, "aft", unique_project_root("listed-window")),
14335            )
14336            .await
14337            .unwrap();
14338        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14339        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14340        let duplicate = handler
14341            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14342            .await
14343            .unwrap();
14344        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14345
14346        hold.wait();
14347        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14348        let ack = module_rx.try_recv().unwrap().frame;
14349        assert_eq!(ack.header.ty, FrameType::HelloAck);
14350        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14351        assert_eq!(listed, vec![("aft".to_string(), true)]);
14352
14353        let (open_task, bind) = relay_route_open(
14354            &handler,
14355            client,
14356            &client_ctx.egress,
14357            &mut module_rx,
14358            303,
14359            "aft",
14360            "listed-after",
14361        )
14362        .await;
14363        assert!(handler
14364            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14365            .await
14366            .unwrap()
14367            .is_empty());
14368        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14369        published_route(&client_rx.try_recv().unwrap().frame);
14370    }
14371
14372    /// A catalog watcher keys on the generation: when it changes, it re-reads
14373    /// the listing. So the generation must advance exactly when the module
14374    /// appears. If it advanced while the module was still hidden, a watcher
14375    /// would read the new generation without the module, and the module would
14376    /// later appear under that same generation with nothing telling the
14377    /// watcher to look again.
14378    #[tokio::test]
14379    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14380        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14381        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14382        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14383
14384        hold.wait();
14385        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14386        assert!(listed.is_empty());
14387        assert_eq!(
14388            during, before,
14389            "the generation moved while the module was not listed"
14390        );
14391
14392        hold.wait();
14393        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14394        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14395        assert_eq!(listed, vec![("aft".to_string(), true)]);
14396        assert_eq!(
14397            after,
14398            before + 1,
14399            "the module appeared without exactly one generation bump"
14400        );
14401    }
14402
14403    /// A HELLO whose forwarding endpoint cannot be installed (here the
14404    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14405    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14406    /// and the catalog generation where it was.
14407    #[tokio::test]
14408    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14409        let registry = Arc::new(Registry::default());
14410        let handler = ControlHandler::with_forwarding(
14411            Arc::clone(&registry),
14412            Arc::new(ForwardingTable::default()),
14413        );
14414        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14415        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14416        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14417        drop(module_rx);
14418
14419        let replies = handler
14420            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14421            .await
14422            .unwrap();
14423        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14424        assert!(registry.get_module("aft").unwrap().is_none());
14425        assert!(registry
14426            .get_module_by_connection(module_ctx.connection_id)
14427            .unwrap()
14428            .is_none());
14429        assert_eq!(
14430            catalog_snapshot(&handler, &client_ctx, 301).await,
14431            (before, Vec::new())
14432        );
14433    }
14434
14435    /// A handler whose `route.open` parks after queueing the route.bind and
14436    /// before marking it enqueued, with module "aft" registered on connection
14437    /// 40. Returns the two-party barrier that parks and releases it.
14438    async fn route_open_held_after_bind_send() -> (
14439        ControlHandler,
14440        Arc<tokio::sync::Barrier>,
14441        RouteCtx,
14442        mpsc::Receiver<crate::router::OutboundFrame>,
14443    ) {
14444        let hold = Arc::new(tokio::sync::Barrier::new(2));
14445        let handler = ControlHandler::with_forwarding(
14446            Arc::new(Registry::default()),
14447            Arc::new(ForwardingTable::default()),
14448        )
14449        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14450        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14451        hello_via_sink(
14452            &handler,
14453            &module_ctx,
14454            &mut module_rx,
14455            hello_frame("aft", PROTOCOL_VERSION, 7),
14456        )
14457        .await;
14458        (handler, hold, module_ctx, module_rx)
14459    }
14460
14461    /// A fast module acks the route.bind, and the reader commits the route,
14462    /// before `route.open` has marked the relay enqueued. The daemon used to
14463    /// read the missing relay as an abandoned bind and send the module a
14464    /// GOODBYE for the route it had just committed: the client was told its
14465    /// route was open, the module unbound the channel, and the client's first
14466    /// request was dropped on the module side as unbound.
14467    #[tokio::test]
14468    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14469        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14470        let client = ConnectionId::new(41);
14471        let (client_ctx, mut client_rx) = route_ctx(client);
14472
14473        let (open_task, bind) = relay_route_open(
14474            &handler,
14475            client,
14476            &client_ctx.egress,
14477            &mut module_rx,
14478            200,
14479            "aft",
14480            "acked-before-mark",
14481        )
14482        .await;
14483        let (module_channel, module_epoch) = route_bind_channel(&bind);
14484        // route.open is now parked between queueing the bind and marking it.
14485        hold.wait().await;
14486
14487        // The module answers inside that window, and the route commits.
14488        assert!(handler
14489            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14490            .await
14491            .unwrap()
14492            .is_empty());
14493        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14494
14495        hold.wait().await;
14496        assert!(
14497            open_task.await.unwrap().is_empty(),
14498            "route.open answers accepted"
14499        );
14500
14501        // Every frame route.open could have sent is already queued, because it
14502        // has returned; the module must have been sent nothing.
14503        match module_rx.try_recv() {
14504            Err(mpsc::error::TryRecvError::Empty) => {}
14505            Ok(outbound) => panic!(
14506                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14507                outbound.frame.header.ty,
14508                outbound.frame.header.channel,
14509                outbound.frame.header.epoch
14510            ),
14511            Err(err) => panic!("module egress closed: {err}"),
14512        }
14513
14514        // The client's first request on the route is the next thing the module
14515        // reads, on the binding it just created.
14516        let router = Router::with_control_handler(Arc::new(handler.clone()));
14517        let request = Frame::build(
14518            FrameType::Request,
14519            Flags::new(true, Priority::Interactive, false),
14520            client_channel,
14521            client_epoch,
14522            201,
14523            b"first request".to_vec(),
14524        )
14525        .unwrap();
14526        router
14527            .route_for_connection(&client_ctx, request)
14528            .await
14529            .unwrap();
14530        let delivered = module_rx.try_recv().unwrap().frame;
14531        assert_eq!(delivered.header.ty, FrameType::Request);
14532        assert_eq!(
14533            (delivered.header.channel, delivered.header.epoch),
14534            (module_channel, module_epoch)
14535        );
14536        assert_eq!(delivered.body, b"first request");
14537    }
14538
14539    /// The client goes away while `route.open` is still queueing the bind, so
14540    /// the relay is dropped with no module reply. The teardown cannot send the
14541    /// GOODBYE itself (it could reach the module ahead of the bind), so
14542    /// `route.open` must send it once the bind is queued; otherwise the module
14543    /// keeps a binding the daemon will never commit.
14544    #[tokio::test]
14545    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14546        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14547        let client = ConnectionId::new(42);
14548        let (client_ctx, _client_rx) = route_ctx(client);
14549
14550        let (open_task, bind) = relay_route_open(
14551            &handler,
14552            client,
14553            &client_ctx.egress,
14554            &mut module_rx,
14555            300,
14556            "aft",
14557            "released-before-mark",
14558        )
14559        .await;
14560        let (module_channel, module_epoch) = route_bind_channel(&bind);
14561        hold.wait().await;
14562
14563        handler.cleanup_connection(client).unwrap();
14564        assert!(
14565            module_rx.try_recv().is_err(),
14566            "client teardown must not GOODBYE a bind route.open is still queueing"
14567        );
14568
14569        hold.wait().await;
14570        let response = open_task.await.unwrap();
14571        assert_eq!(response.len(), 1);
14572        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14573
14574        let goodbye = module_rx
14575            .try_recv()
14576            .expect("module is told to drop the binding the daemon abandoned")
14577            .frame;
14578        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14579        assert_eq!(
14580            (goodbye.header.channel, goodbye.header.epoch),
14581            (module_channel, module_epoch)
14582        );
14583        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14584    }
14585
14586    /// The module acks inside the same window, but the client's egress closed
14587    /// first, so the reader refuses to commit. The ack proves the module holds
14588    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14589    /// send a second one.
14590    #[tokio::test]
14591    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14592        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14593        let client = ConnectionId::new(43);
14594        let (client_ctx, client_rx) = route_ctx(client);
14595
14596        let (open_task, bind) = relay_route_open(
14597            &handler,
14598            client,
14599            &client_ctx.egress,
14600            &mut module_rx,
14601            400,
14602            "aft",
14603            "gone-client-before-mark",
14604        )
14605        .await;
14606        let (module_channel, module_epoch) = route_bind_channel(&bind);
14607        hold.wait().await;
14608
14609        drop(client_rx);
14610        assert!(client_ctx.egress.is_closed());
14611        handler
14612            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14613            .await
14614            .unwrap();
14615
14616        hold.wait().await;
14617        let response = open_task.await.unwrap();
14618        assert_eq!(response.len(), 1);
14619        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14620
14621        let goodbye = module_rx
14622            .try_recv()
14623            .expect("module is told to drop the binding it acked")
14624            .frame;
14625        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14626        assert_eq!(
14627            (goodbye.header.channel, goodbye.header.epoch),
14628            (module_channel, module_epoch)
14629        );
14630        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14631        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14632    }
14633
14634    /// The fence at the module-loop boundary, stated as its own contract: which
14635    /// forwarding failures are allowed to end the module connection that is being
14636    /// served. A `ConnectionClosing` naming some client is about that client, and
14637    /// a module connection is shared; the same error naming the module's own
14638    /// connection is about this connection and must stay fatal, as must failures
14639    /// that are about the forwarding table itself.
14640    #[test]
14641    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14642        let handler = ControlHandler::default();
14643        let module_connection = ConnectionId::new(30);
14644        let client_connection = ConnectionId::new(31);
14645
14646        handler
14647            .refuse_to_end_module_connection_for_a_client(
14648                module_connection,
14649                77,
14650                ForwardingError::ConnectionClosing {
14651                    connection_id: client_connection,
14652                },
14653            )
14654            .expect("a closing client must never end the module connection");
14655
14656        assert!(matches!(
14657            handler.refuse_to_end_module_connection_for_a_client(
14658                module_connection,
14659                78,
14660                ForwardingError::ConnectionClosing {
14661                    connection_id: module_connection,
14662                },
14663            ),
14664            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14665                connection_id
14666            })) if connection_id == module_connection
14667        ));
14668        assert!(matches!(
14669            handler.refuse_to_end_module_connection_for_a_client(
14670                module_connection,
14671                79,
14672                ForwardingError::Poisoned,
14673            ),
14674            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14675        ));
14676        assert!(matches!(
14677            handler.refuse_to_end_module_connection_for_a_client(
14678                module_connection,
14679                80,
14680                ForwardingError::StaleModuleEndpoint,
14681            ),
14682            Err(RouterError::Forwarding(
14683                ForwardingError::StaleModuleEndpoint
14684            ))
14685        ));
14686    }
14687
14688    /// The spawn-attestation guard is what stops a connected module from claiming
14689    /// another module's identity and being stamped `Reserved` for it. Every other
14690    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14691    /// correct one is what the rest of the flow needs -- so the guard's rejection
14692    /// branch was never the subject of an assertion, only its acceptance branch.
14693    ///
14694    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14695    /// whole subc-core library suite green; only the forwarding integration tests
14696    /// notice, and they notice for unrelated reasons. This test exists so the
14697    /// refusal itself is asserted where the guard lives: it fails if the identity
14698    /// check stops refusing, which is the direction that matters, since a guard
14699    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14700    #[tokio::test]
14701    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14702        let registry = Arc::new(Registry::default());
14703        let forwarding = Arc::new(ForwardingTable::default());
14704        let supervisor = SupervisorHandle::new();
14705        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14706        let handler =
14707            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14708                .with_supervisor(supervisor);
14709
14710        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14711        hello_via_sink(
14712            &handler,
14713            &target_ctx,
14714            &mut target_rx,
14715            hello_frame("target", PROTOCOL_VERSION, 1),
14716        )
14717        .await;
14718
14719        // A real supervised module id presenting the wrong nonce. This is the
14720        // impersonation case: the attacker knows a privileged module_id, which is
14721        // public, and guesses at the nonce, which is not.
14722        let wrong_nonce = handler
14723            .handle_control_frame(
14724                &route_ctx(ConnectionId::new(91)).0,
14725                route_open_frame_with_admission_facts(
14726                    20,
14727                    "target",
14728                    unique_project_root("admission-facts"),
14729                    Some(subc_control::ConsumerIdentity {
14730                        module_id: "fed".to_string(),
14731                        launch_nonce: "not-the-real-nonce".to_string(),
14732                    }),
14733                    None,
14734                ),
14735            )
14736            .await
14737            .unwrap();
14738        assert_eq!(
14739            parse_error(&wrong_nonce[0])["code"],
14740            "bad_consumer_identity",
14741            "a mismatched launch nonce must be refused, not stamped Reserved"
14742        );
14743
14744        // A module id the supervisor never spawned at all, so no nonce exists to
14745        // compare against. An implementation that treats "no record" as "nothing
14746        // to check" fails open here while passing the case above.
14747        let never_spawned = handler
14748            .handle_control_frame(
14749                &route_ctx(ConnectionId::new(92)).0,
14750                route_open_frame_with_admission_facts(
14751                    21,
14752                    "target",
14753                    unique_project_root("admission-facts"),
14754                    Some(subc_control::ConsumerIdentity {
14755                        module_id: "never-spawned".to_string(),
14756                        launch_nonce: "any-nonce".to_string(),
14757                    }),
14758                    None,
14759                ),
14760            )
14761            .await
14762            .unwrap();
14763        assert_eq!(
14764            parse_error(&never_spawned[0])["code"],
14765            "bad_consumer_identity",
14766            "an unspawned module_id must be refused rather than accepted for lack of a record"
14767        );
14768    }
14769
14770    /// The refusal test above proves the guard says NO. Nothing proved it can say
14771    /// YES, and the difference is not academic: replacing the whole authorization
14772    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14773    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14774    /// library tests GREEN. The one that notices does so by HANGING, because it
14775    /// waits for a bind that can no longer happen.
14776    ///
14777    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14778    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14779    /// hangs too and gets blamed on the runner. So a total revocation of the
14780    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14781    /// to code.
14782    ///
14783    /// The bias is structural rather than accidental. A REFUSAL looks like a
14784    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14785    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14786    /// suite for that reason, and this one is the purest case in the daemon.
14787    ///
14788    /// This test asserts the EFFECT rather than the absence of an error: the module
14789    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14790    /// A guard that admitted nobody would produce no bind at all; one that admitted
14791    /// everybody would stamp the wrong principal, which the refusal test catches.
14792    #[tokio::test]
14793    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14794        let registry = Arc::new(Registry::default());
14795        let forwarding = Arc::new(ForwardingTable::default());
14796        let supervisor = SupervisorHandle::new();
14797        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14798        let handler =
14799            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14800                .with_supervisor(supervisor);
14801
14802        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14803        hello_via_sink(
14804            &handler,
14805            &target_ctx,
14806            &mut target_rx,
14807            hello_frame("target", PROTOCOL_VERSION, 1),
14808        )
14809        .await;
14810
14811        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14812        let route_handler = handler.clone();
14813        let route_task = tokio::spawn(async move {
14814            route_handler
14815                .handle_control_frame(
14816                    &client_ctx,
14817                    route_open_frame_with_admission_facts(
14818                        30,
14819                        "target",
14820                        unique_project_root("admission-facts"),
14821                        Some(subc_control::ConsumerIdentity {
14822                            module_id: "fed".to_string(),
14823                            launch_nonce: "fed-nonce".to_string(),
14824                        }),
14825                        None,
14826                    ),
14827                )
14828                .await
14829                .unwrap()
14830        });
14831
14832        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14833        // the very mutation it exists to catch -- a guard that admits nobody -- no
14834        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14835        // exact defect being fixed: a total revocation detected only as a stalled
14836        // suite, which reads as flakiness and invites a retry. An acceptance test
14837        // that waits for an effect must bound the wait, or a red becomes a hang.
14838        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14839            .await
14840            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14841            .expect("module control channel closed before route.bind");
14842        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14843        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14844            panic!("expected route.bind")
14845        };
14846        assert_eq!(
14847            principal,
14848            Some(Principal::Reserved {
14849                module_id: "fed".to_string()
14850            }),
14851            "a correctly attested consumer must be stamped Reserved for its own id"
14852        );
14853
14854        handler
14855            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14856            .await
14857            .unwrap();
14858        assert!(route_task.await.unwrap().is_empty());
14859        assert!(
14860            matches!(
14861                serde_json::from_slice::<ClientControlResponse>(
14862                    &client_rx.recv().await.unwrap().body
14863                )
14864                .unwrap(),
14865                ClientControlResponse::RouteOpen { .. }
14866            ),
14867            "the route must actually open, not merely avoid an error"
14868        );
14869    }
14870
14871    #[tokio::test(start_paused = true)]
14872    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14873        let registry = Arc::new(Registry::default());
14874        let forwarding = Arc::new(ForwardingTable::default());
14875        let supervisor = SupervisorHandle::new();
14876        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14877        let handler =
14878            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14879                .with_supervisor(supervisor);
14880
14881        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14882        hello_via_sink(
14883            &handler,
14884            &target_ctx,
14885            &mut target_rx,
14886            hello_frame("target", PROTOCOL_VERSION, 1),
14887        )
14888        .await;
14889
14890        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14891        let direct_handler = handler.clone();
14892        let direct_open = tokio::spawn(async move {
14893            direct_handler
14894                .handle_control_frame(
14895                    &direct_ctx,
14896                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14897                )
14898                .await
14899                .unwrap()
14900        });
14901        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14902            .await
14903            .expect("no direct route.bind within 5s")
14904            .expect("target control channel closed before direct route.bind");
14905        handler
14906            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14907            .await
14908            .unwrap();
14909        assert!(direct_open.await.unwrap().is_empty());
14910        let _ = direct_rx.recv().await.unwrap();
14911
14912        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14913        let reserved_handler = handler.clone();
14914        let reserved_open = tokio::spawn(async move {
14915            reserved_handler
14916                .handle_control_frame(
14917                    &reserved_ctx,
14918                    route_open_frame_with_admission_facts(
14919                        3,
14920                        "target",
14921                        unique_project_root("admission-facts"),
14922                        Some(ConsumerIdentity {
14923                            module_id: "fed".to_string(),
14924                            launch_nonce: "fed-nonce".to_string(),
14925                        }),
14926                        None,
14927                    ),
14928                )
14929                .await
14930                .unwrap()
14931        });
14932        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14933            .await
14934            .expect("no reserved route.bind within 5s")
14935            .expect("target control channel closed before reserved route.bind");
14936        handler
14937            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14938            .await
14939            .unwrap();
14940        assert!(reserved_open.await.unwrap().is_empty());
14941        let _ = reserved_rx.recv().await.unwrap();
14942
14943        forwarding
14944            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14945            .unwrap();
14946        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14947        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14948            module_id: Some("target".to_string()),
14949        })
14950        .unwrap();
14951        let census_frame =
14952            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14953        let response = handler
14954            .handle_control_frame(&census_ctx, census_frame)
14955            .await
14956            .unwrap()
14957            .pop()
14958            .unwrap();
14959        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14960        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14961        assert!(matches!(
14962            decoded,
14963            ClientControlResponse::SupervisorRoutes { .. }
14964        ));
14965        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14966        assert_eq!(routes.len(), 2);
14967        assert!(routes.iter().all(|route| route["draining"] == true));
14968        // The census carries WHY: the reason the drain was begun with, in the
14969        // route.closing vocabulary, on every draining route this drain marked.
14970        assert!(
14971            routes.iter().all(|route| route["drain_reason"] == "reload"),
14972            "draining routes must name the drain's reason: {routes:?}"
14973        );
14974        assert!(routes.iter().any(|route| {
14975            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14976        }));
14977        assert!(routes.iter().any(|route| {
14978            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14979        }));
14980
14981        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14982            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14983        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14984            std::fs::write(
14985                &golden_path,
14986                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14987            )
14988            .unwrap();
14989        }
14990        let expected: Value =
14991            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14992        assert_eq!(actual, expected);
14993    }
14994
14995    async fn query_live_roots(
14996        handler: &ControlHandler,
14997        module_ctx: &RouteCtx,
14998    ) -> ModuleControlResponseToModule {
14999        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
15000        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
15001        let response = handler
15002            .handle_control_frame(module_ctx, frame)
15003            .await
15004            .unwrap()
15005            .pop()
15006            .unwrap();
15007        serde_json::from_slice(&response.body).unwrap()
15008    }
15009
15010    #[tokio::test(start_paused = true)]
15011    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
15012        let registry = Arc::new(Registry::default());
15013        let forwarding = Arc::new(ForwardingTable::default());
15014        let handler = ControlHandler::with_forwarding(registry, forwarding);
15015        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
15016        hello_via_sink(
15017            &handler,
15018            &target_ctx,
15019            &mut target_rx,
15020            hello_frame("target", PROTOCOL_VERSION, 1),
15021        )
15022        .await;
15023        let root = unique_project_root("live-roots-known");
15024        let path = ProjectRootId::from_path_allowing_missing(root.path())
15025            .unwrap()
15026            .as_path()
15027            .to_path_buf();
15028        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
15029        let open_handler = handler.clone();
15030        let opened = tokio::spawn(async move {
15031            open_handler
15032                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
15033                .await
15034                .unwrap()
15035        });
15036        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
15037            .await
15038            .unwrap()
15039            .unwrap();
15040        handler
15041            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
15042            .await
15043            .unwrap();
15044        assert!(opened.await.unwrap().is_empty());
15045        let _ = client_rx.recv().await.unwrap();
15046
15047        let root = unique_project_root("live-roots-pending");
15048        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
15049            .unwrap()
15050            .as_path()
15051            .to_path_buf();
15052        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
15053        let open_handler = handler.clone();
15054        let pending = tokio::spawn(async move {
15055            open_handler
15056                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
15057                .await
15058                .unwrap()
15059        });
15060        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
15061            .await
15062            .unwrap()
15063            .unwrap();
15064        let actual = query_live_roots(&handler, &target_ctx).await;
15065        let ModuleControlResponseToModule::LiveRoots {
15066            roots,
15067            unknown_root_bindings,
15068            total_bindings,
15069        } = actual
15070        else {
15071            panic!("expected live roots")
15072        };
15073        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
15074        assert_eq!(unknown_root_bindings, 0);
15075        assert_eq!(
15076            roots.len(),
15077            2,
15078            "root-known arm must retain each canonical root"
15079        );
15080        assert_eq!(
15081            total_bindings,
15082            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15083        );
15084        let counts = roots
15085            .iter()
15086            .map(|root| (root.project_root.clone(), root.bound, root.pending))
15087            .collect::<Vec<_>>();
15088        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
15089        expected.sort_by(|a, b| a.0.cmp(&b.0));
15090        assert_eq!(
15091            counts, expected,
15092            "roots must sort by path and count pending separately"
15093        );
15094        handler
15095            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
15096            .await
15097            .unwrap();
15098        assert!(pending.await.unwrap().is_empty());
15099    }
15100
15101    #[tokio::test(start_paused = true)]
15102    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
15103        let forwarding = Arc::new(ForwardingTable::default());
15104        let handler =
15105            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
15106        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
15107        hello_via_sink(
15108            &handler,
15109            &target_ctx,
15110            &mut target_rx,
15111            hello_frame("target", PROTOCOL_VERSION, 1),
15112        )
15113        .await;
15114        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
15115        let pending = forwarding
15116            .begin_route_bind_relay_for_test(
15117                client_ctx.connection_id,
15118                client_ctx.egress.clone(),
15119                2,
15120                "target",
15121            )
15122            .unwrap();
15123        forwarding
15124            .complete_pending_relay(
15125                target_ctx.connection_id,
15126                pending.corr,
15127                RouteBindRelayOutcome::Accepted,
15128            )
15129            .unwrap();
15130        let actual = query_live_roots(&handler, &target_ctx).await;
15131        let ModuleControlResponseToModule::LiveRoots {
15132            roots,
15133            unknown_root_bindings,
15134            total_bindings,
15135        } = actual
15136        else {
15137            panic!("expected live roots")
15138        };
15139        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
15140        assert_eq!(
15141            unknown_root_bindings, 1,
15142            "unknown-root arm must not read as no bindings"
15143        );
15144        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
15145        assert_eq!(
15146            total_bindings,
15147            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15148        );
15149    }
15150
15151    /// A module reads HELLO_ACK as its first frame and exits on anything else,
15152    /// so the ack has to be on its outbound queue before the module is
15153    /// routable. The connection loop writes a handler's replies only after the
15154    /// handler returns; this test stops in exactly that gap, runs a real
15155    /// route.open from another connection, and only then writes whatever the
15156    /// HELLO handler returned, the way the loop would. If the ack were still a
15157    /// reply, the route.bind request would reach the module first.
15158    #[tokio::test(start_paused = true)]
15159    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
15160        let forwarding = Arc::new(ForwardingTable::default());
15161        let handler =
15162            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
15163        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
15164        let replies = handler
15165            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
15166            .await
15167            .unwrap();
15168        let queued_by_hello = module_rx.len();
15169
15170        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
15171        let open_handler = handler.clone();
15172        let open = tokio::spawn(async move {
15173            open_handler
15174                .handle_control_frame(
15175                    &client_ctx,
15176                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
15177                )
15178                .await
15179                .unwrap()
15180        });
15181        // Let the route.open run until its route.bind is on the module's queue.
15182        let mut spins = 0;
15183        while module_rx.len() == queued_by_hello {
15184            spins += 1;
15185            assert!(spins < 10_000, "route.open never queued a route.bind");
15186            tokio::task::yield_now().await;
15187        }
15188
15189        // Now the connection loop's half: write the HELLO handler's replies.
15190        for reply in replies {
15191            module_ctx.egress.send(reply).await.unwrap();
15192        }
15193
15194        let first = module_rx.recv().await.unwrap().frame;
15195        assert_eq!(
15196            first.header.ty,
15197            FrameType::HelloAck,
15198            "the first frame a registering module reads must be its HELLO_ACK"
15199        );
15200        assert_eq!(first.header.corr, 7);
15201        let second = module_rx.recv().await.unwrap().frame;
15202        assert_eq!(second.header.ty, FrameType::Request);
15203        assert!(
15204            matches!(
15205                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
15206                ModuleControlRequest::RouteBind { .. }
15207            ),
15208            "the route.bind follows the ack"
15209        );
15210        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
15211
15212        handler
15213            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
15214            .await
15215            .unwrap();
15216        assert!(open.await.unwrap().is_empty());
15217        let _ = client_rx.recv().await.unwrap();
15218    }
15219
15220    #[tokio::test(start_paused = true)]
15221    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
15222        let handler = ControlHandler::with_forwarding(
15223            Arc::new(Registry::default()),
15224            Arc::new(ForwardingTable::default()),
15225        );
15226        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
15227        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
15228        hello_via_sink(
15229            &handler,
15230            &first_ctx,
15231            &mut first_rx,
15232            hello_frame("first", PROTOCOL_VERSION, 1),
15233        )
15234        .await;
15235        hello_via_sink(
15236            &handler,
15237            &second_ctx,
15238            &mut second_rx,
15239            hello_frame("second", PROTOCOL_VERSION, 2),
15240        )
15241        .await;
15242        let root = unique_project_root("second-only");
15243        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
15244        let cloned = handler.clone();
15245        let open = tokio::spawn(async move {
15246            cloned
15247                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
15248                .await
15249                .unwrap()
15250        });
15251        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
15252            .await
15253            .unwrap()
15254            .unwrap();
15255        let first = query_live_roots(&handler, &first_ctx).await;
15256        let second = query_live_roots(&handler, &second_ctx).await;
15257        assert!(
15258            matches!(
15259                first,
15260                ModuleControlResponseToModule::LiveRoots {
15261                    total_bindings: 0,
15262                    ..
15263                }
15264            ),
15265            "cross-module scope must not expose another module's roots"
15266        );
15267        assert!(
15268            matches!(
15269                second,
15270                ModuleControlResponseToModule::LiveRoots {
15271                    total_bindings: 1,
15272                    ..
15273                }
15274            ),
15275            "second module must see its pending route"
15276        );
15277        handler
15278            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
15279            .await
15280            .unwrap();
15281        assert!(open.await.unwrap().is_empty());
15282    }
15283
15284    #[tokio::test(start_paused = true)]
15285    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
15286        let handler = ControlHandler::with_forwarding(
15287            Arc::new(Registry::default()),
15288            Arc::new(ForwardingTable::default()),
15289        );
15290        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15291        hello_via_sink(
15292            &handler,
15293            &target_ctx,
15294            &mut target_rx,
15295            hello_frame("target", PROTOCOL_VERSION, 1),
15296        )
15297        .await;
15298        let actual = query_live_roots(&handler, &target_ctx).await;
15299        let ModuleControlResponseToModule::LiveRoots {
15300            roots,
15301            unknown_root_bindings,
15302            total_bindings,
15303        } = actual
15304        else {
15305            panic!("expected live roots")
15306        };
15307        assert!(roots.is_empty());
15308        assert_eq!(unknown_root_bindings, 0);
15309        assert_eq!(total_bindings, 0);
15310        assert_eq!(
15311            total_bindings,
15312            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15313        );
15314    }
15315
15316    /// Read the vendored fed corpus rather than hand-building a package.
15317    ///
15318    /// A hand-built object encodes what the test author believed the carrier
15319    /// emits. These vectors are what it actually emits, and one of them exists
15320    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15321    /// ignores additive unknown fields at the traversal emit terminus."
15322    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15323        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15324            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15325        let text = std::fs::read_to_string(&path)
15326            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15327        let vectors: Vec<(String, Value)> = text
15328            .lines()
15329            .filter(|line| !line.trim().is_empty())
15330            .map(|line| {
15331                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15332                let id = entry["corpus_id"]
15333                    .as_str()
15334                    .expect("every vector carries a corpus_id")
15335                    .to_string();
15336                (id, entry["package"].clone())
15337            })
15338            .collect();
15339        // Pin the count: a corpus that silently shrinks would take its coverage
15340        // with it, and a suite reading N-1 vectors reports the same clean pass
15341        // as one reading N.
15342        assert_eq!(
15343            vectors.len(),
15344            3,
15345            "vendored fed corpus changed size; re-sync from subc-federation"
15346        );
15347
15348        // Pin what makes the corpus DISCRIMINATING, not just present.
15349        //
15350        // The relay test below takes its expected value from the corpus, so the
15351        // corpus supplies the test's power to detect a lossy relay rather than
15352        // its correctness. A relay that dropped unrecognised fields would still
15353        // be caught -- but only by a package carrying fields it does not know.
15354        // Shrink every package to the handful of keys any implementation would
15355        // recognise and the test keeps passing over an input that can no longer
15356        // fail, which is the same clean green as a corpus that shrank away.
15357        //
15358        // So assert the precondition rather than duplicating the packages here:
15359        // at least one vector must carry a field beyond the small common set.
15360        // That is one claim to maintain instead of nine, and it fails loudly if
15361        // a re-sync ever flattens the corpus.
15362        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15363        let richest = vectors
15364            .iter()
15365            .filter_map(|(_, package)| package.as_object())
15366            .map(|object| {
15367                object
15368                    .keys()
15369                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15370                    .count()
15371            })
15372            .max()
15373            .unwrap_or(0);
15374        assert!(
15375            richest >= 2,
15376            "vendored corpus no longer carries a package with unmodelled fields, \
15377             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15378        );
15379
15380        vectors
15381    }
15382
15383    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15384    ///
15385    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15386    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15387    /// three-key object, so a relay that quietly dropped fields it did not
15388    /// recognise would satisfy it. These vectors carry nine keys including ones
15389    /// this crate has no type for, so a typed relay fails here and only here.
15390    #[tokio::test]
15391    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15392        for (corpus_id, package) in fed_admission_facts_vectors() {
15393            let registry = Arc::new(Registry::default());
15394            let forwarding = Arc::new(ForwardingTable::default());
15395            let supervisor = SupervisorHandle::new();
15396            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15397            let handler =
15398                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15399                    .with_supervisor(supervisor)
15400                    .with_admission_facts_config(
15401                        Some("fed".to_string()),
15402                        Some(vec!["target".to_string()]),
15403                    );
15404
15405            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15406            hello_via_sink(
15407                &handler,
15408                &target_ctx,
15409                &mut target_rx,
15410                hello_frame("target", PROTOCOL_VERSION, 1),
15411            )
15412            .await;
15413
15414            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15415            let route_handler = handler.clone();
15416            let expected = package.clone();
15417            let route_task = tokio::spawn(async move {
15418                route_handler
15419                    .handle_control_frame(
15420                        &client_ctx,
15421                        route_open_frame_with_admission_facts(
15422                            20,
15423                            "target",
15424                            unique_project_root("admission-facts"),
15425                            Some(subc_control::ConsumerIdentity {
15426                                module_id: "fed".to_string(),
15427                                launch_nonce: "fed-nonce".to_string(),
15428                            }),
15429                            Some(package),
15430                        ),
15431                    )
15432                    .await
15433                    .unwrap()
15434            });
15435
15436            let bind_frame = target_rx.recv().await.unwrap();
15437            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15438            let ModuleControlRequest::RouteBind {
15439                admission_facts, ..
15440            } = bind
15441            else {
15442                panic!("{corpus_id}: expected route.bind")
15443            };
15444            assert_eq!(
15445                admission_facts,
15446                Some(expected),
15447                "{corpus_id}: relay must not add, drop or reshape any field"
15448            );
15449
15450            handler
15451                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15452                .await
15453                .unwrap();
15454            route_task.await.unwrap();
15455        }
15456    }
15457
15458    #[tokio::test]
15459    async fn route_bind_never_relays_the_openers_build_class() {
15460        let registry = Arc::new(Registry::default());
15461        let forwarding = Arc::new(ForwardingTable::default());
15462        let handler =
15463            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15464        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15465        hello_via_sink(
15466            &handler,
15467            &target_ctx,
15468            &mut target_rx,
15469            hello_frame("target", PROTOCOL_VERSION, 1),
15470        )
15471        .await;
15472
15473        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15474        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15475        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15476            busy_refusals: None,
15477            target: RouteTarget::ToolProvider {
15478                module_id: "target".to_string(),
15479            },
15480            identity,
15481            consumer_identity: None,
15482            consumer_capabilities: None,
15483            role_versions: None,
15484            admission_facts: None,
15485            scope: None,
15486        })
15487        .unwrap();
15488        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15489
15490        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15491        let route_handler = handler.clone();
15492        let route_task = tokio::spawn(async move {
15493            route_handler
15494                .handle_control_frame(&client_ctx, open)
15495                .await
15496                .unwrap()
15497        });
15498        let bind_frame = target_rx.recv().await.unwrap();
15499        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15500        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15501            panic!("expected route.bind")
15502        };
15503        assert_eq!(
15504            identity.build_class, None,
15505            "route.bind carried the build class"
15506        );
15507        assert!(
15508            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15509            "the route.bind bytes still name build_class"
15510        );
15511        handler
15512            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15513            .await
15514            .unwrap();
15515        route_task.await.unwrap();
15516    }
15517
15518    #[tokio::test]
15519    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15520        let registry = Arc::new(Registry::default());
15521        let forwarding = Arc::new(ForwardingTable::default());
15522        let supervisor = SupervisorHandle::new();
15523        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15524        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15525        let handler =
15526            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15527                .with_supervisor(supervisor)
15528                .with_admission_facts_config(
15529                    Some("fed".to_string()),
15530                    Some(vec!["target".to_string()]),
15531                );
15532
15533        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15534        hello_via_sink(
15535            &handler,
15536            &target_ctx,
15537            &mut target_rx,
15538            hello_frame("target", PROTOCOL_VERSION, 1),
15539        )
15540        .await;
15541        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15542        hello_via_sink(
15543            &handler,
15544            &other_ctx,
15545            &mut other_rx,
15546            hello_frame("other", PROTOCOL_VERSION, 2),
15547        )
15548        .await;
15549
15550        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15551        let expected_facts = facts.clone();
15552        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15553        let route_handler = handler.clone();
15554        let route_task = tokio::spawn(async move {
15555            route_handler
15556                .handle_control_frame(
15557                    &client_ctx,
15558                    route_open_frame_with_admission_facts(
15559                        10,
15560                        "target",
15561                        unique_project_root("admission-facts"),
15562                        Some(subc_control::ConsumerIdentity {
15563                            module_id: "fed".to_string(),
15564                            launch_nonce: "fed-nonce".to_string(),
15565                        }),
15566                        Some(facts.clone()),
15567                    ),
15568                )
15569                .await
15570                .unwrap()
15571        });
15572        let bind_frame = target_rx.recv().await.unwrap();
15573        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15574        let ModuleControlRequest::RouteBind {
15575            admission_facts, ..
15576        } = bind
15577        else {
15578            panic!("expected route.bind")
15579        };
15580        assert_eq!(admission_facts, Some(expected_facts));
15581        handler
15582            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15583            .await
15584            .unwrap();
15585        assert!(route_task.await.unwrap().is_empty());
15586        assert!(matches!(
15587            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15588                .unwrap(),
15589            ClientControlResponse::RouteOpen { .. }
15590        ));
15591
15592        let direct = handler
15593            .handle_control_frame(
15594                &route_ctx(ConnectionId::new(73)).0,
15595                route_open_frame_with_admission_facts(
15596                    11,
15597                    "target",
15598                    unique_project_root("admission-facts"),
15599                    None,
15600                    Some(json!({"x": 1})),
15601                ),
15602            )
15603            .await
15604            .unwrap();
15605        assert_eq!(
15606            parse_error(&direct[0])["code"],
15607            "admission_facts_not_permitted"
15608        );
15609
15610        let different_reserved = handler
15611            .handle_control_frame(
15612                &route_ctx(ConnectionId::new(77)).0,
15613                route_open_frame_with_admission_facts(
15614                    15,
15615                    "target",
15616                    unique_project_root("admission-facts"),
15617                    Some(subc_control::ConsumerIdentity {
15618                        module_id: "other".to_string(),
15619                        launch_nonce: "other-nonce".to_string(),
15620                    }),
15621                    Some(json!({"x": 1})),
15622                ),
15623            )
15624            .await
15625            .unwrap();
15626        assert_eq!(
15627            parse_error(&different_reserved[0])["code"],
15628            "admission_facts_not_permitted"
15629        );
15630
15631        let other_target = handler
15632            .handle_control_frame(
15633                &route_ctx(ConnectionId::new(74)).0,
15634                route_open_frame_with_admission_facts(
15635                    12,
15636                    "other",
15637                    unique_project_root("admission-facts"),
15638                    Some(subc_control::ConsumerIdentity {
15639                        module_id: "fed".to_string(),
15640                        launch_nonce: "fed-nonce".to_string(),
15641                    }),
15642                    Some(json!({"x": 1})),
15643                ),
15644            )
15645            .await
15646            .unwrap();
15647        assert_eq!(
15648            parse_error(&other_target[0])["code"],
15649            "admission_facts_target_not_allowed"
15650        );
15651
15652        let nonexistent = handler
15653            .handle_control_frame(
15654                &route_ctx(ConnectionId::new(75)).0,
15655                route_open_frame_with_admission_facts(
15656                    13,
15657                    "missing",
15658                    unique_project_root("admission-facts"),
15659                    None,
15660                    Some(json!({"x": 1})),
15661                ),
15662            )
15663            .await
15664            .unwrap();
15665        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15666
15667        let described = handler
15668            .handle_control_frame(
15669                &route_ctx(ConnectionId::new(76)).0,
15670                Frame::build(
15671                    FrameType::Request,
15672                    control_flags(),
15673                    0,
15674                    0,
15675                    14,
15676                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15677                )
15678                .unwrap(),
15679            )
15680            .await
15681            .unwrap();
15682        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15683            serde_json::from_slice(&described[0].body).unwrap()
15684        else {
15685            panic!("expected server.describe response")
15686        };
15687        assert!(capabilities
15688            .iter()
15689            .any(|cap| cap == "admission_facts_relay_v1"));
15690    }
15691
15692    #[tokio::test]
15693    async fn admission_facts_without_configured_carrier_are_rejected() {
15694        let registry = Arc::new(Registry::default());
15695        let forwarding = Arc::new(ForwardingTable::default());
15696        let handler = ControlHandler::with_forwarding(registry, forwarding);
15697        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15698        hello_via_sink(
15699            &handler,
15700            &target_ctx,
15701            &mut target_rx,
15702            hello_frame("target", PROTOCOL_VERSION, 1),
15703        )
15704        .await;
15705
15706        let responses = handler
15707            .handle_control_frame(
15708                &route_ctx(ConnectionId::new(79)).0,
15709                route_open_frame_with_admission_facts(
15710                    16,
15711                    "target",
15712                    unique_project_root("admission-facts"),
15713                    None,
15714                    Some(json!({"x": 1})),
15715                ),
15716            )
15717            .await
15718            .unwrap();
15719        assert_eq!(
15720            parse_error(&responses[0])["code"],
15721            "admission_facts_not_permitted"
15722        );
15723    }
15724
15725    #[tokio::test]
15726    async fn route_open_relays_consumer_capabilities_verbatim() {
15727        let registry = Arc::new(Registry::default());
15728        let forwarding = Arc::new(ForwardingTable::default());
15729        let handler =
15730            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15731        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15732        hello_via_sink(
15733            &handler,
15734            &module_ctx,
15735            &mut module_rx,
15736            hello_frame("aft", PROTOCOL_VERSION, 7),
15737        )
15738        .await;
15739
15740        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15741        let expected_for_request = expected.clone();
15742        let project_root = unique_project_root("consumer-capabilities-present");
15743        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15744        let route_handler = handler.clone();
15745        let route_task = tokio::spawn(async move {
15746            route_handler
15747                .handle_control_frame(
15748                    &client_ctx,
15749                    route_open_frame_with_consumer_capabilities(
15750                        401,
15751                        "aft",
15752                        project_root,
15753                        Some(expected_for_request),
15754                    ),
15755                )
15756                .await
15757                .unwrap()
15758        });
15759        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15760            .await
15761            .unwrap()
15762            .unwrap();
15763        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15764        let ModuleControlRequest::RouteBind {
15765            consumer_capabilities,
15766            ..
15767        } = bind
15768        else {
15769            panic!("expected route.bind request, got {bind:?}");
15770        };
15771        assert_eq!(consumer_capabilities, Some(expected.clone()));
15772
15773        handler
15774            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15775            .await
15776            .unwrap();
15777        let route_response = route_task.await.unwrap();
15778        assert!(route_response.is_empty());
15779        let published = client_rx.recv().await.unwrap();
15780        assert!(matches!(
15781            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15782            ClientControlResponse::RouteOpen { .. }
15783        ));
15784    }
15785
15786    #[tokio::test]
15787    async fn route_open_without_consumer_capabilities_relays_none() {
15788        let registry = Arc::new(Registry::default());
15789        let forwarding = Arc::new(ForwardingTable::default());
15790        let handler =
15791            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15792        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15793        hello_via_sink(
15794            &handler,
15795            &module_ctx,
15796            &mut module_rx,
15797            hello_frame("aft", PROTOCOL_VERSION, 7),
15798        )
15799        .await;
15800
15801        let project_root = unique_project_root("consumer-capabilities-absent");
15802        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15803        let route_handler = handler.clone();
15804        let route_task = tokio::spawn(async move {
15805            route_handler
15806                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15807                .await
15808                .unwrap()
15809        });
15810        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15811            .await
15812            .unwrap()
15813            .unwrap();
15814        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15815        let ModuleControlRequest::RouteBind {
15816            consumer_capabilities,
15817            ..
15818        } = bind
15819        else {
15820            panic!("expected route.bind request, got {bind:?}");
15821        };
15822        assert_eq!(consumer_capabilities, None);
15823
15824        handler
15825            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15826            .await
15827            .unwrap();
15828        let route_response = route_task.await.unwrap();
15829        assert!(route_response.is_empty());
15830        let published = client_rx.recv().await.unwrap();
15831        assert!(matches!(
15832            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15833            ClientControlResponse::RouteOpen { .. }
15834        ));
15835    }
15836
15837    /// Opens a route to a freshly registered `aft` with `sent` as the
15838    /// route.open's role_versions, acks the bind, and returns the role_versions
15839    /// the module's bind carried.
15840    async fn bind_role_versions_for(
15841        sent: Option<BTreeMap<String, String>>,
15842        connection: u64,
15843    ) -> Option<BTreeMap<String, String>> {
15844        let registry = Arc::new(Registry::default());
15845        let forwarding = Arc::new(ForwardingTable::default());
15846        let handler =
15847            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15848        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15849        hello_via_sink(
15850            &handler,
15851            &module_ctx,
15852            &mut module_rx,
15853            hello_frame("aft", PROTOCOL_VERSION, 7),
15854        )
15855        .await;
15856        let project_root = unique_project_root("role-versions");
15857        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15858        let route_handler = handler.clone();
15859        let route_task = tokio::spawn(async move {
15860            route_handler
15861                .handle_control_frame(
15862                    &client_ctx,
15863                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15864                )
15865                .await
15866                .unwrap()
15867        });
15868        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15869            .await
15870            .expect("a well-formed route.open reaches the module as a bind")
15871            .unwrap();
15872        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15873        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15874            panic!("expected route.bind request, got {bind:?}");
15875        };
15876        handler
15877            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15878            .await
15879            .unwrap();
15880        assert!(route_task.await.unwrap().is_empty());
15881        let published = client_rx.recv().await.unwrap();
15882        assert!(matches!(
15883            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15884            ClientControlResponse::RouteOpen { .. }
15885        ));
15886        role_versions
15887    }
15888
15889    #[tokio::test]
15890    async fn route_open_relays_role_versions_verbatim() {
15891        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15892        assert_eq!(
15893            bind_role_versions_for(Some(sent.clone()), 141).await,
15894            Some(sent)
15895        );
15896    }
15897
15898    /// An empty map declares nothing, so the provider sees no field rather
15899    /// than an empty object it would have to treat as a second "none".
15900    #[tokio::test]
15901    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15902        assert_eq!(bind_role_versions_for(None, 143).await, None);
15903        assert_eq!(
15904            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15905            None
15906        );
15907    }
15908
15909    #[tokio::test]
15910    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15911        let registry = Arc::new(Registry::default());
15912        let forwarding = Arc::new(ForwardingTable::default());
15913        let handler =
15914            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15915        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15916        hello_via_sink(
15917            &handler,
15918            &module_ctx,
15919            &mut module_rx,
15920            hello_frame("aft", PROTOCOL_VERSION, 7),
15921        )
15922        .await;
15923
15924        let nine: BTreeMap<String, String> = (0..9)
15925            .map(|index| (format!("role-{index}"), "v1".to_string()))
15926            .collect();
15927        for (label, malformed) in [
15928            (
15929                "invalid role name",
15930                role_versions(&[("Tool_Provider", "v1")]),
15931            ),
15932            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15933            ("nine entries", nine),
15934        ] {
15935            // A refused open answers at once; one that reached the module
15936            // would wait for its bind ack and trip this timeout.
15937            let responses = tokio::time::timeout(
15938                Duration::from_secs(1),
15939                handler.handle_control_frame(
15940                    &route_ctx(ConnectionId::new(148)).0,
15941                    route_open_frame_with_role_versions(
15942                        404,
15943                        "aft",
15944                        unique_project_root("role-versions-malformed"),
15945                        Some(malformed),
15946                    ),
15947                ),
15948            )
15949            .await
15950            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15951            .unwrap();
15952            assert_eq!(responses.len(), 1, "{label}");
15953            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15954            let error = parse_error(&responses[0]);
15955            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15956            assert_eq!(
15957                error["detail"]["field"], "role_versions",
15958                "{label}: {error}"
15959            );
15960            assert!(
15961                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15962                "{label}: a malformed declaration is terminal"
15963            );
15964            assert!(
15965                module_rx.try_recv().is_err(),
15966                "{label}: the module must never see a bind"
15967            );
15968        }
15969    }
15970
15971    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15972    /// consumer can tell this daemon forwards the field from one that would
15973    /// drop it.
15974    #[tokio::test]
15975    async fn route_role_versions_capability_is_advertised() {
15976        let handler = ControlHandler::new(Arc::new(Registry::default()));
15977        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15978        let ack = hello_via_sink(
15979            &handler,
15980            &ctx,
15981            &mut rx,
15982            hello_frame("m", PROTOCOL_VERSION, 1),
15983        )
15984        .await;
15985        let ack = parse_ack(&ack);
15986        assert!(
15987            ack.subc_capabilities
15988                .iter()
15989                .any(|c| c == "route-role-versions/v1"),
15990            "{:?}",
15991            ack.subc_capabilities
15992        );
15993
15994        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15995        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15996        let reply = handler
15997            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15998            .await
15999            .unwrap()
16000            .pop()
16001            .unwrap();
16002        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16003            serde_json::from_slice(&reply.body).unwrap()
16004        else {
16005            panic!("not a server.describe reply");
16006        };
16007        assert!(
16008            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
16009            "{capabilities:?}"
16010        );
16011    }
16012
16013    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
16014    /// catalog entry without `events` (the module declares none) from a daemon
16015    /// that never reports declared events.
16016    #[tokio::test]
16017    async fn catalog_events_capability_is_advertised() {
16018        let handler = ControlHandler::new(Arc::new(Registry::default()));
16019        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16020        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16021        let reply = handler
16022            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
16023            .await
16024            .unwrap()
16025            .pop()
16026            .unwrap();
16027        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16028            serde_json::from_slice(&reply.body).unwrap()
16029        else {
16030            panic!("not a server.describe reply");
16031        };
16032        assert!(
16033            capabilities
16034                .iter()
16035                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
16036            "{capabilities:?}"
16037        );
16038    }
16039
16040    #[tokio::test]
16041    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
16042        let handler = ControlHandler::new(Arc::new(Registry::default()));
16043        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
16044        let ack = hello_via_sink(
16045            &handler,
16046            &module,
16047            &mut module_rx,
16048            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
16049        )
16050        .await;
16051        let ack = parse_ack(&ack);
16052        assert!(
16053            ack.subc_capabilities
16054                .iter()
16055                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
16056            "{:?}",
16057            ack.subc_capabilities
16058        );
16059        assert!(ack
16060            .subc_capabilities
16061            .iter()
16062            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
16063
16064        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
16065        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16066        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16067        let reply = handler
16068            .handle_control_frame(&client, frame)
16069            .await
16070            .unwrap()
16071            .pop()
16072            .unwrap();
16073        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16074            serde_json::from_slice(&reply.body).unwrap()
16075        else {
16076            panic!("not a server.describe reply");
16077        };
16078        assert!(
16079            capabilities
16080                .iter()
16081                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
16082            "{capabilities:?}"
16083        );
16084        assert!(capabilities
16085            .iter()
16086            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
16087    }
16088
16089    #[tokio::test]
16090    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
16091        let handler = ControlHandler::new(Arc::new(Registry::default()));
16092        let (module, mut rx) = route_ctx(ConnectionId::new(156));
16093        let ack = hello_via_sink(
16094            &handler,
16095            &module,
16096            &mut rx,
16097            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
16098        )
16099        .await;
16100        assert!(parse_ack(&ack)
16101            .subc_capabilities
16102            .iter()
16103            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
16104        assert!(parse_ack(&ack)
16105            .subc_capabilities
16106            .iter()
16107            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
16108        let (client, _rx) = route_ctx(ConnectionId::new(157));
16109        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16110        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16111        let reply = handler
16112            .handle_control_frame(&client, frame)
16113            .await
16114            .unwrap()
16115            .pop()
16116            .unwrap();
16117        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16118            serde_json::from_slice(&reply.body).unwrap()
16119        else {
16120            panic!("server.describe reply")
16121        };
16122        assert!(capabilities
16123            .iter()
16124            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
16125        assert!(capabilities
16126            .iter()
16127            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
16128    }
16129
16130    #[tokio::test]
16131    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
16132        let handler = ControlHandler::new(Arc::new(Registry::default()));
16133        let (module, mut rx) = route_ctx(ConnectionId::new(158));
16134        let ack = hello_via_sink(
16135            &handler,
16136            &module,
16137            &mut rx,
16138            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
16139        )
16140        .await;
16141        assert!(parse_ack(&ack)
16142            .subc_capabilities
16143            .iter()
16144            .any(|cap| cap == "scope-workdir/v1"));
16145        let (client, _rx) = route_ctx(ConnectionId::new(159));
16146        let frame = Frame::build(
16147            FrameType::Request,
16148            control_flags(),
16149            0,
16150            0,
16151            5,
16152            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
16153        )
16154        .unwrap();
16155        let reply = handler
16156            .handle_control_frame(&client, frame)
16157            .await
16158            .unwrap()
16159            .remove(0);
16160        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16161            serde_json::from_slice(&reply.body).unwrap()
16162        else {
16163            panic!("server.describe reply")
16164        };
16165        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
16166    }
16167
16168    #[tokio::test]
16169    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
16170        let handler = ControlHandler::new(Arc::new(Registry::default()));
16171        let (module, mut rx) = route_ctx(ConnectionId::new(160));
16172        let ack = hello_via_sink(
16173            &handler,
16174            &module,
16175            &mut rx,
16176            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
16177        )
16178        .await;
16179        assert!(parse_ack(&ack)
16180            .subc_capabilities
16181            .iter()
16182            .any(|cap| cap == "worker-runs/v1"));
16183        let (client, _rx) = route_ctx(ConnectionId::new(161));
16184        let frame = Frame::build(
16185            FrameType::Request,
16186            control_flags(),
16187            0,
16188            0,
16189            5,
16190            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
16191        )
16192        .unwrap();
16193        let reply = handler
16194            .handle_control_frame(&client, frame)
16195            .await
16196            .unwrap()
16197            .remove(0);
16198        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16199            serde_json::from_slice(&reply.body).unwrap()
16200        else {
16201            panic!("server.describe reply")
16202        };
16203        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
16204    }
16205
16206    #[tokio::test]
16207    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
16208        let handler = ControlHandler::new(Arc::new(Registry::default()));
16209        let (module, mut rx) = route_ctx(ConnectionId::new(154));
16210        let ack = hello_via_sink(
16211            &handler,
16212            &module,
16213            &mut rx,
16214            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
16215        )
16216        .await;
16217        assert!(parse_ack(&ack)
16218            .subc_capabilities
16219            .iter()
16220            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16221        let (client, _rx) = route_ctx(ConnectionId::new(155));
16222        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16223        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16224        let reply = handler
16225            .handle_control_frame(&client, frame)
16226            .await
16227            .unwrap()
16228            .pop()
16229            .unwrap();
16230        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16231            serde_json::from_slice(&reply.body).unwrap()
16232        else {
16233            panic!("not a server.describe reply")
16234        };
16235        assert!(capabilities
16236            .iter()
16237            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16238    }
16239
16240    #[tokio::test]
16241    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
16242        let registry = Arc::new(Registry::default());
16243        let forwarding = Arc::new(ForwardingTable::default());
16244        let handler =
16245            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
16246                .with_health_probe_timeout(Duration::from_secs(5));
16247        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
16248        hello_via_sink(
16249            &handler,
16250            &module_ctx,
16251            &mut module_rx,
16252            non_routable_hello_frame_with_control_ops(
16253                "mcp",
16254                300,
16255                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
16256            ),
16257        )
16258        .await;
16259        assert!(registry
16260            .get_module("mcp")
16261            .unwrap()
16262            .unwrap()
16263            .manifest
16264            .provides
16265            .is_empty());
16266
16267        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
16268        let route_response = handler
16269            .handle_control_frame(
16270                &route_client_ctx,
16271                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
16272            )
16273            .await
16274            .unwrap();
16275        assert_eq!(route_response[0].header.ty, FrameType::Error);
16276        assert_eq!(
16277            parse_error(&route_response[0])["code"],
16278            "target_unavailable"
16279        );
16280        assert!(parse_error(&route_response[0])["message"]
16281            .as_str()
16282            .unwrap()
16283            .contains("does not provide the requested target"));
16284        assert!(module_rx.try_recv().is_err());
16285
16286        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16287        let health_handler = handler.clone();
16288        let health_task = tokio::spawn(async move {
16289            health_handler
16290                .handle_control_frame(
16291                    &health_client_ctx,
16292                    supervisor_health_probe_frame(302, "mcp"),
16293                )
16294                .await
16295                .unwrap()
16296        });
16297        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16298            .await
16299            .unwrap()
16300            .unwrap();
16301        assert_eq!(
16302            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16303            ModuleControlRequest::HealthCheck {}
16304        );
16305        handler
16306            .handle_control_frame(
16307                &module_ctx,
16308                health_response(health_frame.header.corr, HealthStatus::Ok),
16309            )
16310            .await
16311            .unwrap();
16312        let health_response = health_task.await.unwrap();
16313        assert_eq!(health_response[0].header.ty, FrameType::Response);
16314        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16315            ClientControlResponse::SupervisorHealthProbe {
16316                module_id, status, ..
16317            } => {
16318                assert_eq!(module_id, "mcp");
16319                assert_eq!(status, HealthStatus::Ok);
16320            }
16321            other => panic!("unexpected health response: {other:?}"),
16322        }
16323
16324        // Exercise the forwarding cleanup path directly while leaving the registry
16325        // advertisement in place. If cleanup leaves a stale control sink behind,
16326        // the next probe will enqueue onto it and wait for the long probe timeout
16327        // instead of returning an immediate no-connection error.
16328        forwarding
16329            .cleanup_connection(module_ctx.connection_id)
16330            .unwrap();
16331        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16332        let cleanup_response = tokio::time::timeout(
16333            Duration::from_millis(200),
16334            handler.handle_control_frame(
16335                &cleanup_probe_ctx,
16336                supervisor_health_probe_frame(303, "mcp"),
16337            ),
16338        )
16339        .await
16340        .expect("probe should fail immediately when the control lane is gone")
16341        .unwrap();
16342        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16343        assert_eq!(
16344            parse_error(&cleanup_response[0])["code"],
16345            "target_unavailable"
16346        );
16347        assert!(parse_error(&cleanup_response[0])["message"]
16348            .as_str()
16349            .unwrap()
16350            .contains("no module connection"));
16351
16352        handler
16353            .cleanup_connection(module_ctx.connection_id)
16354            .unwrap();
16355    }
16356
16357    #[tokio::test]
16358    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16359        let registry = Arc::new(Registry::default());
16360        let supervisor_handle = SupervisorHandle::new();
16361        let supervisor =
16362            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16363                .with_handle(supervisor_handle.clone())
16364                .with_connection_file_path(
16365                    std::env::temp_dir()
16366                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16367                );
16368        let module = supervisor
16369            .supervise_configured(
16370                ModuleSpec {
16371                    script: None,
16372                    carry_containment: false,
16373                    module_id: "warming".to_string(),
16374                    program: fake_aft_stub_path(),
16375                    args: Vec::new(),
16376                    env: Vec::new(),
16377                    reserved: false,
16378                    reserved_prefixes: Vec::new(),
16379                    protocol: ModuleProtocol::Subc,
16380                    overlap: Default::default(),
16381                },
16382                true,
16383            )
16384            .unwrap();
16385        assert_eq!(module.state().unwrap(), ModuleState::Running);
16386
16387        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16388        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16389        let response = handler
16390            .handle_control_frame(
16391                &ctx,
16392                route_open_frame(304, "warming", unique_project_root("warming")),
16393            )
16394            .await
16395            .unwrap();
16396        module.stop().await.unwrap();
16397
16398        assert_eq!(response[0].header.ty, FrameType::Error);
16399        let error = parse_error(&response[0]);
16400        assert_eq!(error["code"], "module_warming");
16401        assert!(error["message"]
16402            .as_str()
16403            .unwrap()
16404            .contains("state=running, enabled=true, live=false"));
16405    }
16406
16407    #[test]
16408    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16409        let handler = ControlHandler::new(Arc::new(Registry::default()));
16410        let capture = EventCapture::default();
16411        let _subscriber =
16412            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16413        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16414        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16415        let pending = (0..limit).collect::<Vec<_>>();
16416        let response = handler
16417            .route_open_capacity_refusal(
16418                &ctx,
16419                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16420                "busy",
16421                pending.len(),
16422                limit,
16423            )
16424            .unwrap();
16425        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16426        let event = capture
16427            .events()
16428            .into_iter()
16429            .find(|event| {
16430                event.target == "control"
16431                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16432            })
16433            .expect("connection admission refusal event");
16434        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16435        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16436        // Refused before `handle_route_open` parses the request, so the caller
16437        // fields are read from the frame itself.
16438        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16439        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16440    }
16441
16442    #[test]
16443    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16444        let handler = ControlHandler::new(Arc::new(Registry::default()));
16445        let capture = EventCapture::default();
16446        let _subscriber =
16447            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16448        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16449        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16450        let guards = (0..limit)
16451            .map(|_| {
16452                handler
16453                    .route_bind_concurrency
16454                    .try_admit("busy", limit)
16455                    .unwrap()
16456            })
16457            .collect::<Vec<_>>();
16458        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16459            Err(in_flight) => in_flight,
16460            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16461        };
16462        let response = handler
16463            .route_open_target_capacity_refusal(
16464                &ctx,
16465                &RouteOpenCaller::unknown(),
16466                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16467                "busy",
16468                in_flight,
16469            )
16470            .unwrap();
16471        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16472        let event = capture
16473            .events()
16474            .into_iter()
16475            .find(|event| {
16476                event.target == "control"
16477                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16478            })
16479            .expect("target admission refusal event");
16480        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16481        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16482        drop(guards);
16483    }
16484
16485    #[cfg(unix)]
16486    #[tokio::test(start_paused = true)]
16487    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16488        let registry = Arc::new(Registry::default());
16489        let handle = SupervisorHandle::new();
16490        let supervisor =
16491            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16492                .with_handle(handle.clone());
16493        let module = supervisor
16494            .spawn(crate::ModuleSpec {
16495                script: None,
16496                carry_containment: false,
16497                module_id: "retry-list".into(),
16498                program: PathBuf::from("/bin/sh"),
16499                args: vec!["-c".into(), "exit 17".into()],
16500                env: vec![],
16501                reserved: false,
16502                reserved_prefixes: vec![],
16503                protocol: ModuleProtocol::None,
16504                overlap: Default::default(),
16505            })
16506            .unwrap();
16507        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16508        while module.state().unwrap() != crate::ModuleState::Failed {
16509            assert!(
16510                std::time::Instant::now() < deadline,
16511                "waiting for budget failure"
16512            );
16513            tokio::task::yield_now().await;
16514        }
16515        let handler = ControlHandler::new(registry).with_supervisor(handle);
16516        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16517        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16518        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16519        assert_eq!(body["modules"][0]["state"], "failed");
16520        let retry = body["modules"][0]["next_retry_at_ms"]
16521            .as_u64()
16522            .expect("scheduled retry on the wire");
16523        let now = std::time::SystemTime::now()
16524            .duration_since(std::time::UNIX_EPOCH)
16525            .unwrap()
16526            .as_millis() as u64;
16527        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16528        module.set_enabled(false).await.unwrap();
16529        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16530        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16531        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16532        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16533    }
16534
16535    #[tokio::test]
16536    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16537        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16538        let supervisor =
16539            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16540        let module = supervisor
16541            .spawn(crate::ModuleSpec {
16542                script: None,
16543                carry_containment: false,
16544                module_id: "pid-read-budget".into(),
16545                program: std::env::current_exe().unwrap(),
16546                args: vec![
16547                    "--exact".into(),
16548                    "control::tests::pid_resource_read_fixture".into(),
16549                ],
16550                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16551                    .into_iter()
16552                    .map(|key| (key.into(), dir.display().to_string()))
16553                    .chain(std::iter::once((
16554                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16555                        "1".into(),
16556                    )))
16557                    .collect(),
16558                reserved: false,
16559                reserved_prefixes: Vec::new(),
16560                protocol: ModuleProtocol::None,
16561                overlap: Default::default(),
16562            })
16563            .unwrap();
16564        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16565        while !matches!(
16566            module.child_resource_usage(),
16567            subc_control::ChildResourceUsage::Measured(_)
16568        ) {
16569            assert!(
16570                tokio::time::Instant::now() < ready_deadline,
16571                "fixture process was not measurable"
16572            );
16573            tokio::time::sleep(Duration::from_millis(10)).await;
16574        }
16575        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16576        let reading = {
16577            let _guard = crate::subtree_resources::fault_read_guard().await;
16578            crate::subtree_resources::read_process(module.clone()).await
16579        };
16580        stop_resource_fixture(&module, &dir).await;
16581        assert!(
16582            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16583            "{reading:?}"
16584        );
16585    }
16586
16587    #[test]
16588    fn pid_resource_read_fixture() {
16589        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16590            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16591            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16592            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16593                std::thread::sleep(Duration::from_millis(5));
16594            }
16595            std::fs::write(dir.join("module-stopped"), "").unwrap();
16596        }
16597    }
16598
16599    async fn stop_resource_fixture(
16600        module: &crate::supervise::SupervisedModule,
16601        dir: &std::path::Path,
16602    ) {
16603        let stopping = module.stop();
16604        tokio::pin!(stopping);
16605        tokio::select! {
16606            result = &mut stopping => result.unwrap(),
16607            () = async {
16608                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16609                    tokio::time::sleep(Duration::from_millis(5)).await;
16610                }
16611                std::fs::write(dir.join("stop-module"), "").unwrap();
16612            } => stopping.await.unwrap(),
16613        }
16614        #[cfg(windows)]
16615        assert!(
16616            dir.join("module-stopped").exists(),
16617            "the resource fixture must exit cooperatively, not wait for the drain kill"
16618        );
16619        assert_eq!(
16620            module.state().unwrap(),
16621            crate::supervise::ModuleState::Stopped
16622        );
16623    }
16624
16625    #[tokio::test]
16626    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16627        let registry = Arc::new(Registry::default());
16628        let handle = SupervisorHandle::new();
16629        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16630            .with_handle(handle.clone());
16631        supervisor
16632            .supervise_configured(
16633                crate::ModuleSpec {
16634                    script: None,
16635                    module_id: "disabled-resource-reading".into(),
16636                    program: std::env::current_exe().unwrap(),
16637                    args: Vec::new(),
16638                    env: Vec::new(),
16639                    reserved: false,
16640                    reserved_prefixes: Vec::new(),
16641                    protocol: ModuleProtocol::None,
16642                    overlap: Default::default(),
16643                    carry_containment: false,
16644                },
16645                false,
16646            )
16647            .unwrap();
16648        let handler = ControlHandler::new(registry).with_supervisor(handle);
16649        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16650        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16651        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16652        assert!(body["modules"][0].get("tree").is_none());
16653        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16654    }
16655
16656    #[tokio::test]
16657    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16658        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16659        let registry = Arc::new(Registry::default());
16660        let handle = SupervisorHandle::new();
16661        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16662            .with_handle(handle.clone());
16663        let module = supervisor
16664            .spawn(crate::ModuleSpec {
16665                script: None,
16666                carry_containment: false,
16667                module_id: "list-process-priority".into(),
16668                program: std::env::current_exe().unwrap(),
16669                args: vec![
16670                    "--exact".into(),
16671                    "control::tests::pid_resource_read_fixture".into(),
16672                ],
16673                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16674                    .into_iter()
16675                    .map(|key| (key.into(), dir.display().to_string()))
16676                    .chain(std::iter::once((
16677                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16678                        "1".into(),
16679                    )))
16680                    .collect(),
16681                reserved: false,
16682                reserved_prefixes: Vec::new(),
16683                protocol: ModuleProtocol::None,
16684                overlap: Default::default(),
16685            })
16686            .unwrap();
16687        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16688        loop {
16689            let image = module.running_image_agreement().await;
16690            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16691                break;
16692            }
16693            assert!(
16694                tokio::time::Instant::now() < ready_deadline,
16695                "the fixture process never became observable: {image:?}"
16696            );
16697            tokio::time::sleep(Duration::from_millis(10)).await;
16698        }
16699        let guard = crate::subtree_resources::fault_read_guard().await;
16700        let (target, release, _) = crate::subtree_resources::held();
16701        module.set_subtree_target_for_test(target);
16702        let handler = ControlHandler::new(registry).with_supervisor(handle);
16703        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16704        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16705        drop(release);
16706        drop(guard);
16707        stop_resource_fixture(&module, &dir).await;
16708        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16709        assert_eq!(
16710            body["modules"][0]["resources"]["status"], "measured",
16711            "the optional tree timeout must not discard the process reading: {body}"
16712        );
16713        assert!(body["modules"][0].get("tree").is_none());
16714        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16715        assert_eq!(
16716            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16717            "the tree timeout must not hide a completed image observation"
16718        );
16719    }
16720
16721    #[cfg(any(target_os = "linux", target_os = "macos"))]
16722    #[tokio::test]
16723    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16724        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16725            .with_daemon_provenance(
16726                std::process::id(),
16727                0,
16728                Some(std::env::current_exe().unwrap()),
16729                None,
16730                None,
16731            );
16732        let (probe, release, began) = ExecutableIdentityProbe::held();
16733        handler.daemon_provenance.probe = probe;
16734        let observe = |handler: ControlHandler, corr| {
16735            tokio::spawn(async move {
16736                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16737                let frame =
16738                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16739                        .unwrap();
16740                handler
16741                    .handle_supervisor_provenance(&ctx, frame, None)
16742                    .await
16743                    .unwrap()
16744            })
16745        };
16746        let explicit = observe(handler.clone(), 114);
16747        began.await.unwrap();
16748        let concurrent = observe(handler.clone(), 115);
16749        // Keep explicit provenance waiting on its first image observation beyond
16750        // the list deadline; release it only after the concurrent list replies.
16751        tokio::time::sleep(Duration::from_millis(300)).await;
16752        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16753        let list = tokio::time::timeout(
16754            Duration::from_secs(1),
16755            handler.handle_supervisor_list(frame),
16756        )
16757        .await;
16758        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16759        drop(release);
16760        let replies = explicit.await.unwrap();
16761        let concurrent_replies = concurrent.await.unwrap();
16762        assert!(
16763            explicit_was_pending,
16764            "explicit provenance must await the full observation"
16765        );
16766        let list = list
16767            .expect("a concurrent explicit probe must not stall list")
16768            .unwrap();
16769        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16770        assert_eq!(list_body["op"], "supervisor.list");
16771        for replies in [replies, concurrent_replies] {
16772            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16773            assert_eq!(
16774                body["daemon"]["daemon_observed"]["running_image"]["status"],
16775                "match"
16776            );
16777        }
16778    }
16779
16780    #[tokio::test]
16781    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16782        let registry = Arc::new(Registry::default());
16783        let handle = SupervisorHandle::new();
16784        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16785            .with_handle(handle.clone());
16786        let module = supervisor
16787            .supervise_configured(
16788                crate::ModuleSpec {
16789                    script: None,
16790                    carry_containment: false,
16791                    module_id: "memory-read".into(),
16792                    program: PathBuf::from("disabled-module"),
16793                    args: Vec::new(),
16794                    env: Vec::new(),
16795                    reserved: false,
16796                    reserved_prefixes: Vec::new(),
16797                    protocol: ModuleProtocol::Subc,
16798                    overlap: Default::default(),
16799                },
16800                true,
16801            )
16802            .unwrap();
16803        let _guard = crate::subtree_resources::fault_read_guard().await;
16804        let (target, release, began) = crate::subtree_resources::held();
16805        // Optional list work may be skipped when its deadline is already spent.
16806        // Establish the stalled fixture before asking the list to observe it.
16807        let stalled_target = target.clone();
16808        let stalled = tokio::task::spawn_blocking(move || {
16809            stalled_target.tree(&subc_os::ProcessTable::default())
16810        });
16811        began.await.unwrap();
16812        module.set_subtree_target_for_test(target);
16813        let handler = ControlHandler::new(registry).with_supervisor(handle);
16814        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16815        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16816        let replies = handler
16817            .handle_client_control_request(
16818                &ctx,
16819                frame,
16820                ClientControlRequest::SupervisorList {},
16821                &mut None,
16822            )
16823            .await
16824            .unwrap();
16825        assert!(
16826            replies.is_empty(),
16827            "list reply must be detached from the connection reader"
16828        );
16829        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16830        let replies = handler
16831            .handle_client_control_request(
16832                &ctx,
16833                frame,
16834                ClientControlRequest::SupervisorSpawnSnapshot {},
16835                &mut None,
16836            )
16837            .await
16838            .unwrap();
16839        assert_eq!(
16840            replies.len(),
16841            1,
16842            "another request must complete while the subtree read stalls"
16843        );
16844        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16845            .await
16846            .unwrap()
16847            .unwrap();
16848        release.send(()).unwrap();
16849        drop(release);
16850        stalled.await.unwrap();
16851        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16852        assert!(
16853            body["modules"][0].get("tree").is_none(),
16854            "an unknown tree reading must be omitted after the bounded read expires"
16855        );
16856        // Lists export completed work rather than measuring synchronously.
16857        // Complete a refresh after the fixture is released before asserting
16858        // that a later list contains its measured tree.
16859        handler
16860            .resource_tracker
16861            .read(handler.supervisor.list(), false, "released_tree_fixture")
16862            .await;
16863        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16864        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16865        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16866        assert_eq!(
16867            body["modules"][0]["tree"]["source"], "process_tree",
16868            "the next request must export the completed refresh"
16869        );
16870        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16871    }
16872
16873    #[tokio::test]
16874    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16875        use subc_control::{
16876            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16877            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16878            TreeReading, TreeSource,
16879        };
16880        let registry = Arc::new(Registry::default());
16881        let handle = SupervisorHandle::new();
16882        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16883            .with_handle(handle.clone());
16884        supervisor
16885            .supervise_configured(
16886                crate::ModuleSpec {
16887                    script: None,
16888                    carry_containment: false,
16889                    module_id: "budget-worker".into(),
16890                    program: PathBuf::from("disabled-module"),
16891                    args: Vec::new(),
16892                    env: Vec::new(),
16893                    reserved: false,
16894                    reserved_prefixes: Vec::new(),
16895                    protocol: ModuleProtocol::Subc,
16896                    overlap: Default::default(),
16897                },
16898                true,
16899            )
16900            .unwrap();
16901        let handler = ControlHandler::new(registry).with_supervisor(handle);
16902        let now = u64::try_from(
16903            std::time::SystemTime::now()
16904                .duration_since(std::time::UNIX_EPOCH)
16905                .unwrap()
16906                .as_millis(),
16907        )
16908        .unwrap();
16909        let measured = now - 1_000;
16910        let hour = CpuLastHour::new(100, 60_000);
16911        let daemon = DaemonResources::new(7, 1, "test")
16912            .with_measured_at_ms(Some(measured))
16913            .with_resources(Some(ChildResourceUsage::Measured(
16914                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16915            )))
16916            .with_cpu_last_hour(Some(hour.clone()));
16917        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16918            .with_measured_at_ms(Some(measured))
16919            .with_cpu_last_hour(Some(hour.clone()));
16920        let tree = TreeReading::new(
16921            150,
16922            50,
16923            ChildMemoryKind::ResidentSet,
16924            1,
16925            TreeSource::ProcessTree,
16926        )
16927        .with_measured_at_ms(Some(measured));
16928        handler.resource_tracker.seed_committed_for_test(
16929            &handler.supervisor.list(),
16930            crate::resource_totals::Readings {
16931                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16932                daemon: Some(daemon),
16933                agent_commands: Some(vec![agents]),
16934                ..Default::default()
16935            },
16936            now,
16937        );
16938        list_diagnostics::scope(async {
16939            tokio::time::sleep(Duration::from_millis(110)).await;
16940            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16941            let request =
16942                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16943            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16944            let ClientControlResponse::SupervisorList {
16945                modules,
16946                daemon,
16947                agent_commands,
16948                ..
16949            } = serde_json::from_slice(&replies[0].body).unwrap()
16950            else {
16951                panic!("expected a list response")
16952            };
16953            assert!(matches!(
16954                modules[0].resources,
16955                Some(ChildResourceUsage::Unavailable {
16956                    reason: ChildResourceUnavailableReason::Unreadable
16957                })
16958            ));
16959            assert_eq!(
16960                (
16961                    modules[0].tree.as_ref().unwrap().cpu_ms,
16962                    modules[0].tree.as_ref().unwrap().measured_at_ms
16963                ),
16964                (150, Some(measured))
16965            );
16966            let daemon = daemon.unwrap();
16967            let agents = agent_commands.unwrap();
16968            assert_eq!(daemon.measured_at_ms, Some(measured));
16969            assert_eq!(
16970                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16971                (1, 50, Some(measured))
16972            );
16973            for hour in [
16974                modules[0].cpu_last_hour.as_ref(),
16975                daemon.cpu_last_hour.as_ref(),
16976                agents[0].cpu_last_hour.as_ref(),
16977            ] {
16978                let hour = hour.unwrap();
16979                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16980            }
16981        })
16982        .await;
16983    }
16984
16985    #[tokio::test]
16986    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16987        let registry = Arc::new(Registry::default());
16988        let handle = SupervisorHandle::new();
16989        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16990            .with_handle(handle.clone());
16991        supervisor
16992            .supervise_configured(
16993                crate::ModuleSpec {
16994                    script: None,
16995                    carry_containment: false,
16996                    module_id: "drift".into(),
16997                    program: PathBuf::from("disabled-module"),
16998                    args: Vec::new(),
16999                    env: Vec::new(),
17000                    reserved: false,
17001                    reserved_prefixes: Vec::new(),
17002                    protocol: ModuleProtocol::Subc,
17003                    overlap: Default::default(),
17004                },
17005                false,
17006            )
17007            .unwrap();
17008        let handler = ControlHandler::new(registry).with_supervisor(handle);
17009        for configured in [None, Some(false), Some(true)] {
17010            handler.capability_evaluator.configure(
17011                configured.map(|enabled| ("drift".to_string(), enabled)),
17012                BTreeMap::new(),
17013            );
17014            let frame =
17015                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
17016            let replies = handler
17017                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
17018                .await
17019                .unwrap();
17020            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
17021            assert!(body.get("configured_enabled").is_none());
17022            assert_eq!(body["op"], "supervisor.ack");
17023            let frame =
17024                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
17025            let replies = handler.handle_supervisor_list(frame).await.unwrap();
17026            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
17027            assert_eq!(
17028                body["modules"][0].get("configured_enabled"),
17029                configured.map(Value::Bool).as_ref()
17030            );
17031            assert!(body["modules"][0].get("tree").is_none());
17032            assert!(body["modules"][0].get("subtree").is_none());
17033        }
17034    }
17035
17036    #[tokio::test(flavor = "current_thread")]
17037    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
17038        let handler = ControlHandler::new(Arc::new(Registry::default()));
17039        let capture = EventCapture::default();
17040        let _subscriber =
17041            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17042        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
17043        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
17044
17045        let _ = handler
17046            .handle_client_control_request(
17047                &ctx,
17048                frame,
17049                ClientControlRequest::SupervisorSetEnabled {
17050                    module_id: "broca".to_string(),
17051                    enabled: false,
17052                },
17053                &mut None,
17054            )
17055            .await
17056            .unwrap();
17057
17058        let events = capture
17059            .events()
17060            .into_iter()
17061            .filter(|event| {
17062                event.target == "control"
17063                    && event.fields.get("message").map(String::as_str)
17064                        == Some("supervisor request received")
17065            })
17066            .collect::<Vec<_>>();
17067        assert_eq!(events.len(), 1, "one supervisor request log line");
17068        let event = &events[0];
17069        assert_eq!(event.level, tracing::Level::INFO);
17070        assert_eq!(
17071            event.fields.get("op"),
17072            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
17073        );
17074        assert_eq!(
17075            event.fields.get("module_id"),
17076            Some(&"\"broca\"".to_string())
17077        );
17078        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
17079        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
17080        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
17081    }
17082
17083    #[tokio::test(flavor = "current_thread")]
17084    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
17085        let registry = Arc::new(Registry::default());
17086        let module_connection = ConnectionId::new(303);
17087        registry
17088            .register_with_control_ops(
17089                manifest("aft", PROTOCOL_VERSION),
17090                PROTOCOL_VERSION,
17091                module_connection,
17092                module_baseline_control_ops(),
17093            )
17094            .unwrap();
17095        let handler = ControlHandler::new(registry);
17096        let capture = EventCapture::default();
17097        let _subscriber =
17098            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17099        let (ctx, _rx) = route_ctx(module_connection);
17100        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
17101
17102        let _ = handler
17103            .handle_client_control_request(
17104                &ctx,
17105                frame,
17106                ClientControlRequest::SupervisorSetEnabled {
17107                    module_id: "broca".to_string(),
17108                    enabled: false,
17109                },
17110                &mut None,
17111            )
17112            .await
17113            .unwrap();
17114
17115        let callers = capture
17116            .events()
17117            .into_iter()
17118            .filter(|event| {
17119                event.fields.get("message").map(String::as_str)
17120                    == Some("supervisor request received")
17121            })
17122            .map(|event| event.fields.get("caller").cloned())
17123            .collect::<Vec<_>>();
17124        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
17125    }
17126
17127    #[tokio::test(flavor = "current_thread")]
17128    async fn supervisor_list_does_not_log_request_received() {
17129        let handler = ControlHandler::new(Arc::new(Registry::default()));
17130        let capture = EventCapture::default();
17131        let _subscriber =
17132            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17133        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
17134        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
17135
17136        handler
17137            .handle_client_control_request(
17138                &ctx,
17139                frame,
17140                ClientControlRequest::SupervisorList {},
17141                &mut None,
17142            )
17143            .await
17144            .unwrap();
17145
17146        assert!(capture.events().into_iter().all(|event| {
17147            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
17148        }));
17149    }
17150
17151    #[tokio::test(flavor = "current_thread")]
17152    async fn supervisor_rescan_preview_does_not_log_request_received() {
17153        let handler = ControlHandler::new(Arc::new(Registry::default()));
17154        let capture = EventCapture::default();
17155        let _subscriber =
17156            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17157        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
17158        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
17159
17160        handler
17161            .handle_client_control_request(
17162                &ctx,
17163                frame,
17164                ClientControlRequest::SupervisorRescan { preview: true },
17165                &mut None,
17166            )
17167            .await
17168            .unwrap();
17169
17170        assert!(capture.events().into_iter().all(|event| {
17171            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
17172        }));
17173    }
17174
17175    struct ApproveOperator;
17176    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
17177        fn prompt(
17178            &self,
17179            _: &str,
17180            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
17181        ) -> crate::operator_confirm::ProviderResult {
17182            crate::operator_confirm::ProviderResult::Approved
17183        }
17184    }
17185
17186    #[tokio::test]
17187    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
17188        assert_eq!(
17189            ControlHandler::default().privileged_operator_prompt,
17190            PrivilegedOperatorPrompt::Log
17191        );
17192        for (initial, changed, running) in [
17193            ("log", "enforce", PrivilegedOperatorPrompt::Log),
17194            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
17195        ] {
17196            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
17197            let path = dir.join("subc.jsonc");
17198            std::fs::write(
17199                &path,
17200                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
17201            )
17202            .unwrap();
17203            let config = crate::daemon_config::load(&path).unwrap().unwrap();
17204            let registry = Arc::new(Registry::default());
17205            let handle = SupervisorHandle::new();
17206            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
17207                .with_handle(handle.clone());
17208            let handler = ControlHandler::new(registry)
17209                .with_supervisor(handle)
17210                .with_privileged_operator_prompt(config.privileged_operator_prompt)
17211                .with_supervisor_rescan(supervisor, &path, config.port);
17212            handler.forwarding.operator_confirms().configure(
17213                Arc::new(ApproveOperator),
17214                crate::operator_confirm::OperatorLimits::default(),
17215            );
17216            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
17217
17218            for (disk_mode, needs_restart) in [
17219                (Some(initial), false),
17220                (Some(changed), true),
17221                (Some(changed), true),
17222                (None, running == PrivilegedOperatorPrompt::Enforce),
17223                (Some(initial), false),
17224            ] {
17225                let mut doc = json!({"version":1});
17226                if let Some(mode) = disk_mode {
17227                    doc["privileged_operator_prompt"] = json!(mode);
17228                }
17229                std::fs::write(&path, doc.to_string()).unwrap();
17230                for preview in [true, false] {
17231                    let request = ClientControlRequest::SupervisorRescan { preview };
17232                    let frame = Frame::build(
17233                        FrameType::Request,
17234                        control_flags(),
17235                        0,
17236                        0,
17237                        1,
17238                        serde_json::to_vec(&request).unwrap(),
17239                    )
17240                    .unwrap();
17241                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17242                    assert_eq!(frames.len(), 1);
17243                    let ClientControlResponse::SupervisorRescan { result } =
17244                        serde_json::from_slice(&frames[0].body).unwrap()
17245                    else {
17246                        panic!("expected a rescan response");
17247                    };
17248                    let expected = if needs_restart {
17249                        vec!["privileged_operator_prompt"]
17250                    } else {
17251                        Vec::new()
17252                    };
17253                    assert_eq!(result.restart_required, expected);
17254                    assert_eq!(handler.privileged_operator_prompt, running);
17255                    assert_eq!(
17256                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
17257                        running
17258                    );
17259                }
17260            }
17261        }
17262    }
17263
17264    #[tokio::test]
17265    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
17266        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
17267        let path = dir.join("subc.jsonc");
17268        let registry = Arc::new(Registry::default());
17269        let handle = SupervisorHandle::new();
17270        let supervisor =
17271            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
17272        let handler = ControlHandler::new(registry)
17273            .with_supervisor(handle)
17274            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
17275            .with_supervisor_rescan(supervisor, &path, None);
17276        handler.forwarding.operator_confirms().configure(
17277            Arc::new(ApproveOperator),
17278            crate::operator_confirm::OperatorLimits::default(),
17279        );
17280        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17281        for preview in [true, false] {
17282            std::fs::write(
17283                &path,
17284                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17285            )
17286            .unwrap();
17287            let request = ClientControlRequest::SupervisorRescan { preview };
17288            let frame = Frame::build(
17289                FrameType::Request,
17290                control_flags(),
17291                0,
17292                0,
17293                1,
17294                serde_json::to_vec(&request).unwrap(),
17295            )
17296            .unwrap();
17297            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17298            assert_eq!(frames.len(), 1);
17299            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17300            assert_eq!(
17301                handler.privileged_operator_prompt,
17302                PrivilegedOperatorPrompt::Enforce
17303            );
17304        }
17305    }
17306
17307    /// One wire code has several senders, so the refusal line names the check
17308    /// that refused. This drives the shared refusal path for ordinary refusals
17309    /// with an unregistered
17310    /// target and requires the branch label on the event.
17311    #[tokio::test]
17312    async fn route_open_refusal_names_the_check_that_refused() {
17313        let handler = ControlHandler::new(Arc::new(Registry::default()));
17314        let capture = EventCapture::default();
17315        let _subscriber =
17316            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17317        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17318        let response = handler
17319            .handle_control_frame(
17320                &ctx,
17321                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17322            )
17323            .await
17324            .unwrap();
17325
17326        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17327        let event = capture
17328            .events()
17329            .into_iter()
17330            .find(|event| {
17331                event.target == "control"
17332                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17333            })
17334            .expect("route.open refusal event");
17335        assert_eq!(
17336            event.fields.get("reason"),
17337            Some(&"\"not_registered\"".to_string())
17338        );
17339    }
17340
17341    #[tokio::test]
17342    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17343        let registry = Arc::new(Registry::default());
17344        let supervisor_handle = SupervisorHandle::new();
17345        let supervisor =
17346            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17347                .with_handle(supervisor_handle.clone())
17348                .with_connection_file_path(std::env::temp_dir().join(format!(
17349                    "subc-route-open-refusal-info-{}",
17350                    std::process::id()
17351                )));
17352        let module = supervisor
17353            .supervise_configured(
17354                ModuleSpec {
17355                    script: None,
17356                    carry_containment: false,
17357                    module_id: "warming".to_string(),
17358                    program: fake_aft_stub_path(),
17359                    args: Vec::new(),
17360                    env: Vec::new(),
17361                    reserved: false,
17362                    reserved_prefixes: Vec::new(),
17363                    protocol: ModuleProtocol::Subc,
17364                    overlap: Default::default(),
17365                },
17366                true,
17367            )
17368            .unwrap();
17369        assert_eq!(module.state().unwrap(), ModuleState::Running);
17370
17371        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17372        assert!(handler
17373            .counters()
17374            .snapshot()
17375            .get("route_open_refused_by_code")
17376            .is_none());
17377        let capture = EventCapture::default();
17378        let _subscriber =
17379            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17380        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17381        let response = handler
17382            .handle_control_frame(
17383                &ctx,
17384                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17385            )
17386            .await
17387            .unwrap();
17388        module.stop().await.unwrap();
17389
17390        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17391        let event = capture
17392            .events()
17393            .into_iter()
17394            .find(|event| {
17395                event.target == "control"
17396                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17397            })
17398            .expect("route.open refusal event");
17399        assert_eq!(
17400            event.fields.get("module_id"),
17401            Some(&"\"warming\"".to_string())
17402        );
17403        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17404        assert_eq!(
17405            event.fields.get("reason"),
17406            Some(&"\"supervised_not_registered\"".to_string())
17407        );
17408        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17409        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17410        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17411        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17412        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17413        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17414        assert_eq!(
17415            handler.counters().snapshot()["route_open_refused_by_code"],
17416            json!({ "module_warming": 1 })
17417        );
17418    }
17419
17420    const OUTAGE_START: &str = "route.open refusing module: not serving";
17421    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17422
17423    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17424        capture
17425            .events()
17426            .into_iter()
17427            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17428            .collect()
17429    }
17430
17431    fn supervise_stub(
17432        registry: &Arc<Registry>,
17433        module_id: &str,
17434        enabled: bool,
17435    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17436        let supervisor_handle = SupervisorHandle::new();
17437        let supervisor =
17438            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17439                .with_handle(supervisor_handle.clone())
17440                .with_connection_file_path(std::env::temp_dir().join(format!(
17441                    "subc-route-outage-{module_id}-{}",
17442                    std::process::id()
17443                )));
17444        let module = supervisor
17445            .supervise_configured(
17446                ModuleSpec {
17447                    script: None,
17448                    carry_containment: false,
17449                    module_id: module_id.to_string(),
17450                    program: fake_aft_stub_path(),
17451                    args: Vec::new(),
17452                    env: Vec::new(),
17453                    reserved: false,
17454                    reserved_prefixes: Vec::new(),
17455                    protocol: ModuleProtocol::Subc,
17456                    overlap: Default::default(),
17457                },
17458                enabled,
17459            )
17460            .unwrap();
17461        (supervisor_handle, module)
17462    }
17463
17464    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17465        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17466            module_id: module_id.to_string(),
17467            drain_timeout_ms: Some(50),
17468        })
17469        .unwrap();
17470        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17471    }
17472
17473    /// Two handlers built over one forwarding table must share one outage
17474    /// tracker; separate trackers would each log their own opening line for
17475    /// the same outage.
17476    #[test]
17477    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17478        let registry = Arc::new(Registry::default());
17479        let forwarding = Arc::new(ForwardingTable::default());
17480        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17481        let second = ControlHandler::with_forwarding(registry, forwarding);
17482        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17483    }
17484
17485    /// A client can name any module id it likes. Refusing an unknown one,
17486    /// however often, must not create outage state or outage lines, or the
17487    /// tracker would be a memory sink any client could fill.
17488    #[tokio::test(flavor = "current_thread")]
17489    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17490        let handler = ControlHandler::new(Arc::new(Registry::default()));
17491        let capture = EventCapture::default();
17492        let _subscriber =
17493            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17494        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17495        for corr in 0..8 {
17496            let response = handler
17497                .handle_control_frame(
17498                    &ctx,
17499                    route_open_frame(
17500                        380 + corr,
17501                        &format!("nobody-{corr}"),
17502                        unique_project_root("outage-unknown"),
17503                    ),
17504                )
17505                .await
17506                .unwrap();
17507            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17508        }
17509
17510        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17511        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17512        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17513    }
17514
17515    /// Drives the refusal path end to end: a supervised module that served
17516    /// before and stopped being registered with no instruction to stop is a
17517    /// WARN, and the same module refused after an operator `supervisor.restart`
17518    /// is an INFO.
17519    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17520    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17521        let registry = Arc::new(Registry::default());
17522        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17523        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17524        let capture = EventCapture::default();
17525        let _subscriber =
17526            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17527        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17528        // The stub never registers, so pretend it served once: otherwise every
17529        // refusal would fall in its startup window.
17530        handler.route_outages.record_accepted("outage-restart");
17531
17532        let response = handler
17533            .handle_control_frame(
17534                &ctx,
17535                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17536            )
17537            .await
17538            .unwrap();
17539        assert_eq!(response[0].header.ty, FrameType::Error);
17540        let starts = outage_lines(&capture, OUTAGE_START);
17541        assert_eq!(starts.len(), 1, "{starts:?}");
17542        assert_eq!(starts[0].level, tracing::Level::WARN);
17543        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17544        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17545        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17546        handler.route_outages.record_accepted("outage-restart");
17547        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17548
17549        // The missing connection file makes the stub exit immediately. Restart
17550        // is deliberately deferred while that exit is being recorded; Failed
17551        // means the zero restart budget and terminal record have been published.
17552        tokio::time::timeout(Duration::from_secs(10), async {
17553            while module.state().unwrap() != crate::ModuleState::Failed {
17554                tokio::task::yield_now().await;
17555            }
17556        })
17557        .await
17558        .expect("stub exit must be recorded before the operator restart");
17559
17560        let restart = handler
17561            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17562            .await
17563            .unwrap();
17564        assert_eq!(
17565            restart[0].header.ty,
17566            FrameType::Response,
17567            "{:?}",
17568            parse_error(&restart[0])
17569        );
17570        handler
17571            .handle_control_frame(
17572                &ctx,
17573                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17574            )
17575            .await
17576            .unwrap();
17577        module.stop().await.unwrap();
17578
17579        let starts = outage_lines(&capture, OUTAGE_START);
17580        assert_eq!(starts.len(), 2, "{starts:?}");
17581        assert_eq!(starts[1].level, tracing::Level::INFO);
17582        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17583    }
17584
17585    /// A restart refused before it touched the module (here: the module is
17586    /// disabled) must clear its operator mark, so the next real outage is
17587    /// still reported as a warning.
17588    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17589    async fn failed_operator_restart_leaves_no_operator_mark() {
17590        let registry = Arc::new(Registry::default());
17591        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17592        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17593        let capture = EventCapture::default();
17594        let _subscriber =
17595            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17596        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17597        handler.route_outages.record_accepted("outage-disabled");
17598
17599        let restart = handler
17600            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17601            .await
17602            .unwrap();
17603        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17604        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17605
17606        handler
17607            .handle_control_frame(
17608                &ctx,
17609                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17610            )
17611            .await
17612            .unwrap();
17613        let starts = outage_lines(&capture, OUTAGE_START);
17614        assert_eq!(starts.len(), 1, "{starts:?}");
17615        assert_eq!(starts[0].level, tracing::Level::WARN);
17616    }
17617
17618    #[tokio::test(flavor = "current_thread")]
17619    async fn route_open_unknown_module_escapes_target_module_id() {
17620        let handler = ControlHandler::new(Arc::new(Registry::default()));
17621        let capture = EventCapture::default();
17622        let _subscriber =
17623            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17624        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17625        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17626        let response = handler
17627            .handle_control_frame(
17628                &ctx,
17629                route_open_frame(
17630                    395,
17631                    hostile_module_id,
17632                    unique_project_root("hostile-target-module-id"),
17633                ),
17634            )
17635            .await
17636            .unwrap();
17637
17638        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17639        let event = capture
17640            .events()
17641            .into_iter()
17642            .find(|event| {
17643                event.target == "control"
17644                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17645            })
17646            .expect("route.open unknown-module refusal event");
17647        let logged = event.fields.get("module_id").expect("module_id field");
17648        assert!(!logged.bytes().any(|byte| byte < 0x20));
17649        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17650    }
17651
17652    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17653    /// the daemon-origin bit on the frame the client receives.
17654    #[tokio::test(flavor = "current_thread")]
17655    async fn route_open_refusal_carries_daemon_origin() {
17656        let handler = ControlHandler::new(Arc::new(Registry::default()));
17657        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17658        let response = handler
17659            .handle_control_frame(
17660                &ctx,
17661                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17662            )
17663            .await
17664            .unwrap();
17665
17666        assert_eq!(response.len(), 1);
17667        assert_eq!(response[0].header.ty, FrameType::Error);
17668        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17669        assert!(
17670            response[0].header.flags.is_daemon_origin(),
17671            "route.open refusal must carry daemon origin: {:?}",
17672            response[0].header.flags
17673        );
17674    }
17675
17676    /// The drain `module_reloading` refusal is daemon-synthesized for an
17677    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17678    /// frame the client receives.
17679    #[tokio::test(flavor = "current_thread")]
17680    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17681        let registry = Arc::new(Registry::default());
17682        let forwarding = Arc::new(ForwardingTable::default());
17683        let handler =
17684            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17685        let module_connection = ConnectionId::new(95);
17686        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17687        hello_via_sink(
17688            &handler,
17689            &module_ctx,
17690            &mut module_rx,
17691            hello_frame("aft", PROTOCOL_VERSION, 395),
17692        )
17693        .await;
17694        forwarding
17695            .begin_module_drain("aft", RouteCloseReason::Restart)
17696            .unwrap()
17697            .expect("the module endpoint drains");
17698
17699        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17700        let response = handler
17701            .handle_control_frame(
17702                &client_ctx,
17703                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17704            )
17705            .await
17706            .unwrap();
17707
17708        assert_eq!(response.len(), 1);
17709        assert_eq!(response[0].header.ty, FrameType::Error);
17710        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17711        assert!(
17712            response[0].header.flags.is_daemon_origin(),
17713            "drain module_reloading must carry daemon origin: {:?}",
17714            response[0].header.flags
17715        );
17716    }
17717
17718    /// A module that refuses a bind with a daemon code still cannot mint a
17719    /// daemon refusal: the relayed `module_reloading` body reaches the client
17720    /// with the daemon-origin bit clear.
17721    #[tokio::test(flavor = "current_thread")]
17722    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17723        let registry = Arc::new(Registry::default());
17724        let forwarding = Arc::new(ForwardingTable::default());
17725        let handler =
17726            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17727        let module_connection = ConnectionId::new(95);
17728        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17729        hello_via_sink(
17730            &handler,
17731            &module_ctx,
17732            &mut module_rx,
17733            hello_frame("aft", PROTOCOL_VERSION, 395),
17734        )
17735        .await;
17736
17737        let client_connection = ConnectionId::new(96);
17738        let (client_ctx, _client_rx) = route_ctx(client_connection);
17739        let (route_task, bind) = relay_route_open(
17740            &handler,
17741            client_connection,
17742            &client_ctx.egress,
17743            &mut module_rx,
17744            396,
17745            "aft",
17746            "spoofed-reloading",
17747        )
17748        .await;
17749        // The module sets the origin bit on its own rejection too: neither
17750        // the bit nor the daemon code may survive the relay as daemon-owned.
17751        let rejection = Frame::build(
17752            FrameType::Error,
17753            crate::router::daemon_error_flags(),
17754            0,
17755            0,
17756            bind.header.corr,
17757            serde_json::to_vec(&ErrorBody::new(
17758                "module_reloading",
17759                "module refused route.bind",
17760            ))
17761            .unwrap(),
17762        )
17763        .unwrap();
17764        handler
17765            .handle_control_frame(&module_ctx, rejection)
17766            .await
17767            .unwrap();
17768
17769        let response = route_task.await.unwrap();
17770        assert_eq!(response.len(), 1);
17771        assert_eq!(response[0].header.ty, FrameType::Error);
17772        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17773        assert!(
17774            !response[0].header.flags.is_daemon_origin(),
17775            "a module's own rejection must not carry daemon origin: {:?}",
17776            response[0].header.flags
17777        );
17778    }
17779
17780    #[tokio::test(flavor = "current_thread")]
17781    async fn route_open_module_rejection_uses_daemon_counter_key() {
17782        let registry = Arc::new(Registry::default());
17783        let forwarding = Arc::new(ForwardingTable::default());
17784        let handler =
17785            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17786        let module_connection = ConnectionId::new(95);
17787        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17788        hello_via_sink(
17789            &handler,
17790            &module_ctx,
17791            &mut module_rx,
17792            hello_frame("aft", PROTOCOL_VERSION, 395),
17793        )
17794        .await;
17795
17796        let client_connection = ConnectionId::new(96);
17797        let (client_ctx, _client_rx) = route_ctx(client_connection);
17798        let capture = EventCapture::default();
17799        // tracing-core decides once per callsite whether its events are enabled,
17800        // and caches the answer. If a parallel test with no subscriber reaches
17801        // this callsite first, the cached answer is "disabled" and this test's
17802        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17803        // ask every live subscriber instead, while only this test's default
17804        // receives the events.
17805        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17806        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17807        let _subscriber =
17808            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17809        let (route_task, bind) = relay_route_open(
17810            &handler,
17811            client_connection,
17812            &client_ctx.egress,
17813            &mut module_rx,
17814            396,
17815            "aft",
17816            "hostile-module-code",
17817        )
17818        .await;
17819        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17820        let rejection = Frame::build(
17821            FrameType::Error,
17822            control_flags(),
17823            0,
17824            0,
17825            bind.header.corr,
17826            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17827        )
17828        .unwrap();
17829        handler
17830            .handle_control_frame(&module_ctx, rejection)
17831            .await
17832            .unwrap();
17833
17834        let response = route_task.await.unwrap();
17835        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17836        let counters = handler.counters().snapshot();
17837        assert_eq!(
17838            counters["route_open_refused_by_code"],
17839            json!({ "module_rejected": 1 })
17840        );
17841        assert!(counters["route_open_refused_by_code"]
17842            .get(hostile_code)
17843            .is_none());
17844
17845        let event = capture
17846            .events()
17847            .into_iter()
17848            .find(|event| {
17849                event.target == "control"
17850                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17851            })
17852            .expect("route.open module-rejection refusal event");
17853        let logged = event.fields.get("module_code").expect("module_code field");
17854        assert!(!logged.bytes().any(|byte| byte < 0x20));
17855        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17856    }
17857
17858    #[tokio::test]
17859    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17860        let registry = Arc::new(Registry::default());
17861        let supervisor_handle = SupervisorHandle::new();
17862        let missing_program = std::env::temp_dir().join(format!(
17863            "subc-route-open-missing-program-{}",
17864            std::process::id()
17865        ));
17866        let supervisor =
17867            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17868                .with_handle(supervisor_handle.clone());
17869        let module = supervisor
17870            .supervise_configured(
17871                ModuleSpec {
17872                    script: None,
17873                    carry_containment: false,
17874                    module_id: "failed".to_string(),
17875                    program: missing_program,
17876                    args: Vec::new(),
17877                    env: Vec::new(),
17878                    reserved: false,
17879                    reserved_prefixes: Vec::new(),
17880                    protocol: ModuleProtocol::Subc,
17881                    overlap: Default::default(),
17882                },
17883                true,
17884            )
17885            .unwrap();
17886        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17887
17888        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17889        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17890        let response = handler
17891            .handle_control_frame(
17892                &ctx,
17893                route_open_frame(305, "failed", unique_project_root("failed")),
17894            )
17895            .await
17896            .unwrap();
17897
17898        assert_eq!(response[0].header.ty, FrameType::Error);
17899        let error = parse_error(&response[0]);
17900        assert_eq!(error["code"], "target_unavailable");
17901        assert!(error["message"]
17902            .as_str()
17903            .unwrap()
17904            .contains("state=failed, enabled=true, live=false"));
17905    }
17906
17907    #[tokio::test]
17908    async fn route_open_role_mismatch_remains_target_unavailable() {
17909        let registry = Arc::new(Registry::default());
17910        let handler = ControlHandler::new(Arc::clone(&registry));
17911        handler
17912            .handle_control(
17913                ConnectionId::new(41),
17914                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17915            )
17916            .unwrap();
17917
17918        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17919        let response = handler
17920            .handle_control_frame(
17921                &ctx,
17922                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17923            )
17924            .await
17925            .unwrap();
17926
17927        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17928        assert!(parse_error(&response[0])["message"]
17929            .as_str()
17930            .unwrap()
17931            .contains("does not provide the requested target"));
17932    }
17933
17934    #[tokio::test]
17935    async fn route_open_inactive_registration_remains_target_unavailable() {
17936        let registry = Arc::new(Registry::default());
17937        let handler = ControlHandler::new(Arc::clone(&registry));
17938        handler
17939            .handle_control(
17940                ConnectionId::new(43),
17941                hello_frame("inactive", PROTOCOL_VERSION, 308),
17942            )
17943            .unwrap();
17944        assert!(registry
17945            .set_module_state_for_test("inactive", ChannelState::Closed)
17946            .unwrap());
17947
17948        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17949        let response = handler
17950            .handle_control_frame(
17951                &ctx,
17952                route_open_frame(309, "inactive", unique_project_root("inactive")),
17953            )
17954            .await
17955            .unwrap();
17956
17957        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17958        assert!(parse_error(&response[0])["message"]
17959            .as_str()
17960            .unwrap()
17961            .contains("is not active"));
17962    }
17963
17964    #[tokio::test]
17965    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17966        let registry = Arc::new(Registry::default());
17967        let forwarding = Arc::new(ForwardingTable::default());
17968        let supervisor_handle = SupervisorHandle::new();
17969        let supervisor =
17970            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17971                .with_forwarding(Arc::clone(&forwarding))
17972                .with_handle(supervisor_handle.clone());
17973        let module = supervisor
17974            .supervise_configured(
17975                crate::ModuleSpec {
17976                    script: None,
17977                    carry_containment: false,
17978                    module_id: "late-health-response".to_string(),
17979                    program: PathBuf::from("disabled-module"),
17980                    args: Vec::new(),
17981                    env: Vec::new(),
17982                    reserved: false,
17983                    reserved_prefixes: Vec::new(),
17984                    protocol: ModuleProtocol::Subc,
17985                    overlap: Default::default(),
17986                },
17987                false,
17988            )
17989            .unwrap();
17990        let handler =
17991            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17992                .with_supervisor(supervisor_handle);
17993        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17994        handler
17995            .handle_control_frame(
17996                &module_ctx,
17997                hello_frame_with_control_ops(
17998                    "late-health-response",
17999                    PROTOCOL_VERSION,
18000                    7,
18001                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
18002                ),
18003            )
18004            .await
18005            .unwrap();
18006        let probe_started_at = Instant::now() - Duration::from_millis(80);
18007        let pending = forwarding
18008            .begin_health_probe_rpc_for(
18009                "late-health-response",
18010                MODULE_CONTROL_OP_HEALTH_CHECK,
18011                probe_started_at,
18012                Instant::now() - Duration::from_millis(1),
18013            )
18014            .unwrap();
18015        assert!(forwarding
18016            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
18017            .unwrap());
18018
18019        let responses = handler
18020            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
18021            .await
18022            .unwrap();
18023
18024        assert!(responses.is_empty());
18025        let health = module.status().unwrap().health;
18026        assert_eq!(health.late_answer_count, 1);
18027        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
18028    }
18029
18030    #[tokio::test]
18031    async fn health_probe_timeout_and_module_death_are_typed() {
18032        let registry = Arc::new(Registry::default());
18033        let forwarding = Arc::new(ForwardingTable::default());
18034        let handler =
18035            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18036                .with_health_probe_timeout(Duration::from_millis(50));
18037        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
18038        hello_via_sink(
18039            &handler,
18040            &module_ctx,
18041            &mut module_rx,
18042            hello_frame_with_control_ops(
18043                "aft",
18044                PROTOCOL_VERSION,
18045                7,
18046                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
18047            ),
18048        )
18049        .await;
18050
18051        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
18052        let responses = handler
18053            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
18054            .await
18055            .unwrap();
18056        assert_eq!(responses[0].header.ty, FrameType::Error);
18057        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
18058        let _ = module_rx.try_recv();
18059
18060        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
18061        let health_handler = handler.clone();
18062        let death_task = tokio::spawn(async move {
18063            health_handler
18064                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
18065                .await
18066                .unwrap()
18067        });
18068        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
18069            .await
18070            .unwrap()
18071            .unwrap();
18072        handler
18073            .cleanup_connection(module_ctx.connection_id)
18074            .unwrap();
18075        let responses = death_task.await.unwrap();
18076        assert_eq!(responses[0].header.ty, FrameType::Error);
18077        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
18078    }
18079
18080    #[test]
18081    fn hello_requires_exact_protocol_version() {
18082        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
18083            let registry = Arc::new(Registry::default());
18084            let handler = ControlHandler::new(Arc::clone(&registry));
18085            let responses = handler
18086                .handle_control(
18087                    ConnectionId::new(connection),
18088                    hello_frame("aft", offered, 9),
18089                )
18090                .unwrap();
18091
18092            assert_eq!(responses.len(), 1);
18093            assert_eq!(responses[0].header.ty, FrameType::Error);
18094            let error = parse_error(&responses[0]);
18095            assert_eq!(error["code"], "version_unsupported");
18096            assert!(registry.get_module("aft").unwrap().is_none());
18097            assert_eq!(registry.active_registration_count().unwrap(), 0);
18098        }
18099    }
18100
18101    #[test]
18102    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
18103        let registry = Arc::new(Registry::default());
18104        let forwarding = Arc::new(ForwardingTable::default());
18105        let handler =
18106            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18107        let module_connection = ConnectionId::new(301);
18108        let registration = registry
18109            .register_with_control_ops(
18110                manifest("aft-push", PROTOCOL_VERSION),
18111                PROTOCOL_VERSION,
18112                module_connection,
18113                module_baseline_control_ops(),
18114            )
18115            .unwrap();
18116        let (module_tx, _module_rx) = mpsc::channel(8);
18117        let endpoint = forwarding
18118            .register_module_connection(
18119                module_connection,
18120                "aft-push".to_string(),
18121                PROTOCOL_VERSION,
18122                manifest_concurrency(&registration.manifest),
18123                FrameSink::new(module_tx),
18124            )
18125            .unwrap();
18126
18127        // A push op this version does not know is ignored (forward-compat), not errored.
18128        let unknown = Frame::build(
18129            FrameType::Push,
18130            control_flags(),
18131            0,
18132            0,
18133            5,
18134            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
18135        )
18136        .unwrap();
18137        let out = handler.handle_status_update(endpoint, unknown).unwrap();
18138        assert!(
18139            out.is_empty(),
18140            "unknown push op must be ignored, got {out:?}"
18141        );
18142
18143        // A malformed body for a KNOWN op is a real error worth surfacing.
18144        let malformed = Frame::build(
18145            FrameType::Push,
18146            control_flags(),
18147            0,
18148            0,
18149            6,
18150            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
18151        )
18152        .unwrap();
18153        let out = handler.handle_status_update(endpoint, malformed).unwrap();
18154        assert_eq!(out.len(), 1);
18155        assert_eq!(out[0].header.ty, FrameType::Error);
18156        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
18157    }
18158
18159    #[test]
18160    fn hello_rejected_when_connection_already_owns_client_routes() {
18161        let registry = Arc::new(Registry::default());
18162        let forwarding = Arc::new(ForwardingTable::default());
18163        let handler =
18164            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18165        // Commits a client route on connection 202 (bound to a module on conn 101).
18166        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
18167        let client_connection = ConnectionId::new(202);
18168
18169        // That same connection now tries to register as a module: rejected, so one
18170        // connection never holds both client-route and module-endpoint state.
18171        let responses = handler
18172            .handle_control(
18173                client_connection,
18174                hello_frame("aft-second", PROTOCOL_VERSION, 9),
18175            )
18176            .unwrap();
18177        assert_eq!(responses[0].header.ty, FrameType::Error);
18178        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
18179        assert!(registry.get_module("aft-second").unwrap().is_none());
18180    }
18181
18182    #[tokio::test]
18183    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
18184        let registry = Arc::new(Registry::default());
18185        let forwarding = Arc::new(ForwardingTable::default());
18186        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
18187        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
18188        hello_via_sink(
18189            &handler,
18190            &module_ctx,
18191            &mut module_rx,
18192            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
18193        )
18194        .await;
18195        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
18196        let pending = forwarding
18197            .begin_route_bind_relay_for_test(
18198                client_ctx.connection_id,
18199                client_ctx.egress.clone(),
18200                2,
18201                "alpha",
18202            )
18203            .unwrap();
18204        forwarding
18205            .complete_pending_relay(
18206                module_ctx.connection_id,
18207                pending.corr,
18208                RouteBindRelayOutcome::Accepted,
18209            )
18210            .unwrap();
18211        client_rx.try_recv().unwrap();
18212        for module_id in ["beta", "alpha"] {
18213            let replies = handler
18214                .handle_control_frame(
18215                    &module_ctx,
18216                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
18217                )
18218                .await
18219                .unwrap();
18220            assert_eq!(replies.len(), 1, "second HELLO must be refused");
18221            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
18222        }
18223        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
18224        assert!(registry.get_module("beta").unwrap().is_none());
18225        assert!(matches!(
18226            forwarding
18227                .lookup_data_route(
18228                    client_ctx.connection_id,
18229                    pending.client_channel,
18230                    pending.client_epoch,
18231                )
18232                .unwrap(),
18233            DataRoute::Client(DataRouteState::Bound(_))
18234        ));
18235        assert!(handler
18236            .hello_launch_nonces
18237            .lock()
18238            .unwrap()
18239            .presented(module_ctx.connection_id, Some("alpha-nonce")));
18240        assert!(module_rx.try_recv().is_err());
18241    }
18242
18243    #[test]
18244    fn reserved_module_hello_requires_matching_launch_nonce() {
18245        let registry = Arc::new(Registry::default());
18246        let supervisor = SupervisorHandle::new();
18247        // The supervisor recorded the nonce it injected when it spawned the reserved
18248        // module; the HELLO verifier checks against the same shared handle.
18249        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
18250        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18251
18252        // A HELLO with NO nonce is rejected.
18253        let no_nonce = handler
18254            .handle_control(
18255                ConnectionId::new(1),
18256                hello_frame("vault", PROTOCOL_VERSION, 1),
18257            )
18258            .unwrap();
18259        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
18260        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
18261        assert!(registry.get_module("vault").unwrap().is_none());
18262
18263        // A HELLO with the WRONG nonce is rejected.
18264        let wrong = handler
18265            .handle_control(
18266                ConnectionId::new(2),
18267                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
18268            )
18269            .unwrap();
18270        assert_eq!(wrong[0].header.ty, FrameType::Error);
18271        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
18272        assert!(registry.get_module("vault").unwrap().is_none());
18273
18274        // A HELLO with the CORRECT nonce registers.
18275        let ok = handler
18276            .handle_control(
18277                ConnectionId::new(3),
18278                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
18279            )
18280            .unwrap();
18281        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18282        assert!(registry.get_module("vault").unwrap().is_some());
18283    }
18284
18285    #[test]
18286    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18287        let registry = Arc::new(Registry::default());
18288        let supervisor = SupervisorHandle::new();
18289        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18290        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18291        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18292
18293        let squat = handler
18294            .handle_control(
18295                ConnectionId::new(1),
18296                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18297            )
18298            .unwrap();
18299        assert_eq!(squat[0].header.ty, FrameType::Error);
18300        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18301        assert!(parse_error(&squat[0])["message"]
18302            .as_str()
18303            .unwrap()
18304            .contains("fed:"));
18305
18306        let accepted_peer = handler
18307            .handle_control(
18308                ConnectionId::new(2),
18309                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18310            )
18311            .unwrap();
18312        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18313
18314        let accepted_short = handler
18315            .handle_control(
18316                ConnectionId::new(3),
18317                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18318            )
18319            .unwrap();
18320        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18321
18322        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18323            let response = handler
18324                .handle_control(
18325                    ConnectionId::new(conn),
18326                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18327                )
18328                .unwrap();
18329            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18330        }
18331    }
18332
18333    #[test]
18334    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18335        let registry = Arc::new(Registry::default());
18336        let supervisor = SupervisorHandle::new();
18337        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18338        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18339        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18340        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18341
18342        let owner_nonce = handler
18343            .handle_control(
18344                ConnectionId::new(1),
18345                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18346            )
18347            .unwrap();
18348        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18349        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18350        assert!(registry.get_module("fed:special").unwrap().is_none());
18351
18352        let exact_nonce = handler
18353            .handle_control(
18354                ConnectionId::new(2),
18355                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18356            )
18357            .unwrap();
18358        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18359        assert!(registry.get_module("fed:special").unwrap().is_some());
18360    }
18361
18362    #[test]
18363    fn non_reserved_module_ignores_launch_nonce() {
18364        let registry = Arc::new(Registry::default());
18365        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18366        // registration succeeds whether a spawned process echoes a nonce or not.
18367        let handler = ControlHandler::new(Arc::clone(&registry));
18368        let no_nonce = handler
18369            .handle_control(
18370                ConnectionId::new(1),
18371                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18372            )
18373            .unwrap();
18374        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18375        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18376
18377        let echoed_nonce = handler
18378            .handle_control(
18379                ConnectionId::new(2),
18380                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18381            )
18382            .unwrap();
18383        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18384        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18385    }
18386
18387    #[test]
18388    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18389        let handler = ControlHandler::default();
18390        let conn = ConnectionId::new(1);
18391        let malformed = Frame::build(
18392            FrameType::Hello,
18393            control_flags(),
18394            0,
18395            0,
18396            3,
18397            b"{not json".to_vec(),
18398        )
18399        .unwrap();
18400
18401        let error = handler.handle_control(conn, malformed).unwrap();
18402        assert_eq!(error[0].header.ty, FrameType::Error);
18403        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18404
18405        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18406        let pong = handler.handle_control(conn, ping).unwrap();
18407        assert_eq!(pong[0].header.ty, FrameType::Pong);
18408        assert_eq!(pong[0].header.corr, 4);
18409    }
18410
18411    #[test]
18412    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18413        let registry = Arc::new(Registry::default());
18414        let handler = ControlHandler::new(Arc::clone(&registry));
18415
18416        handler
18417            .handle_control(
18418                ConnectionId::new(1),
18419                hello_frame("aft", PROTOCOL_VERSION, 1),
18420            )
18421            .unwrap();
18422        let duplicate = handler
18423            .handle_control(
18424                ConnectionId::new(2),
18425                hello_frame("aft", PROTOCOL_VERSION, 2),
18426            )
18427            .unwrap();
18428
18429        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18430        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18431        let registration = registry.get_module("aft").unwrap().unwrap();
18432        assert_eq!(registration.connection_id, ConnectionId::new(1));
18433    }
18434
18435    #[test]
18436    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18437        let registry = Arc::new(Registry::default());
18438        let forwarding = Arc::new(ForwardingTable::default());
18439        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18440        let handler =
18441            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18442                .with_process_liveness(process_liveness);
18443        let (ctx, route_channel, route_epoch) =
18444            bind_liveness_route(&registry, &forwarding, "aft-dead");
18445        let responses = handler
18446            .handle_route_poll(
18447                &ctx,
18448                route_poll_frame(41, PollKind::Liveness, route_channel),
18449                route_channel,
18450                route_epoch,
18451                PollKind::Liveness,
18452            )
18453            .unwrap();
18454
18455        assert_eq!(responses.len(), 1);
18456        assert_eq!(responses[0].header.ty, FrameType::Response);
18457        assert_route_poll_liveness(&responses[0], false);
18458    }
18459
18460    #[test]
18461    fn liveness_poll_without_process_source_uses_bound_route() {
18462        let registry = Arc::new(Registry::default());
18463        let forwarding = Arc::new(ForwardingTable::default());
18464        let handler =
18465            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18466        let (ctx, route_channel, route_epoch) =
18467            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18468        let responses = handler
18469            .handle_route_poll(
18470                &ctx,
18471                route_poll_frame(42, PollKind::Liveness, route_channel),
18472                route_channel,
18473                route_epoch,
18474                PollKind::Liveness,
18475            )
18476            .unwrap();
18477
18478        assert_route_poll_liveness(&responses[0], true);
18479    }
18480
18481    #[test]
18482    fn liveness_poll_untracked_process_source_uses_bound_route() {
18483        let registry = Arc::new(Registry::default());
18484        let forwarding = Arc::new(ForwardingTable::default());
18485        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18486        let handler =
18487            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18488                .with_process_liveness(process_liveness);
18489        let (ctx, route_channel, route_epoch) =
18490            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18491        let responses = handler
18492            .handle_route_poll(
18493                &ctx,
18494                route_poll_frame(43, PollKind::Liveness, route_channel),
18495                route_channel,
18496                route_epoch,
18497                PollKind::Liveness,
18498            )
18499            .unwrap();
18500
18501        assert_route_poll_liveness(&responses[0], true);
18502    }
18503
18504    #[tokio::test]
18505    async fn unknown_op_returns_unknown_control_op() {
18506        let handler = ControlHandler::default();
18507        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18508        let request = Frame::build(
18509            FrameType::Request,
18510            control_flags(),
18511            0,
18512            0,
18513            55,
18514            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18515        )
18516        .unwrap();
18517
18518        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18519
18520        assert_eq!(response.len(), 1);
18521        assert_eq!(response[0].header.ty, FrameType::Error);
18522        assert_eq!(response[0].header.corr, 55);
18523        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18524    }
18525
18526    #[tokio::test]
18527    async fn supervisor_provenance_rejects_unknown_exact_module() {
18528        let handler = ControlHandler::default();
18529        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18530        let request = Frame::build(
18531            FrameType::Request,
18532            control_flags(),
18533            0,
18534            0,
18535            57,
18536            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18537        )
18538        .unwrap();
18539
18540        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18541
18542        assert_eq!(response.len(), 1);
18543        assert_eq!(response[0].header.ty, FrameType::Error);
18544        assert_eq!(response[0].header.corr, 57);
18545        let error = parse_error(&response[0]);
18546        assert_eq!(error["code"], "unknown_module");
18547        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18548    }
18549
18550    #[test]
18551    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18552        let expected = subc_control::RunningImageAgreement::Unavailable {
18553            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18554        };
18555        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18556        assert_eq!(handler.provenance_probe_override, Some(expected));
18557    }
18558
18559    #[test]
18560    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18561        let verdict = reload_verdict(
18562            std::path::Path::new("/bin/new"),
18563            Some(std::path::Path::new("/bin/old")),
18564            subc_control::RunningImageAgreement::Unavailable {
18565                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18566            },
18567        );
18568        assert!(matches!(
18569            verdict.path,
18570            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18571                if configured == std::path::Path::new("/bin/new")
18572                    && spawned_from == std::path::Path::new("/bin/old")
18573        ));
18574    }
18575
18576    #[test]
18577    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18578        use subc_control::{
18579            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18580        };
18581        let configured = crate::supervise::ModuleSpec {
18582            script: None,
18583            carry_containment: false,
18584            module_id: "legacy".into(),
18585            program: "/module".into(),
18586            args: Vec::new(),
18587            env: Vec::new(),
18588            reserved: false,
18589            reserved_prefixes: Vec::new(),
18590            protocol: subc_control::ModuleProtocol::Subc,
18591            overlap: Default::default(),
18592        };
18593        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18594        assert_eq!(
18595            launch_spec_agreement(&configured, false, Some(&digest)),
18596            Agreement::Unavailable {
18597                reason: Reason::NotRunning
18598            }
18599        );
18600        assert_eq!(
18601            launch_spec_agreement(&configured, true, None),
18602            Agreement::Unavailable {
18603                reason: Reason::SpawnedSpecUnavailable
18604            }
18605        );
18606        assert_eq!(
18607            launch_spec_agreement(&configured, true, Some(&digest)),
18608            Agreement::Match
18609        );
18610    }
18611
18612    #[cfg(windows)]
18613    #[test]
18614    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18615        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18616        let configured = dir.join("module.exe");
18617        std::fs::write(&configured, b"executable path fixture").unwrap();
18618        let spawned = std::fs::canonicalize(&configured).unwrap();
18619        assert_ne!(
18620            configured, spawned,
18621            "fixture must exercise different path spellings"
18622        );
18623        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18624        let lower_case = configured.to_string_lossy().to_lowercase();
18625        for spelling in [
18626            &configured,
18627            Path::new(&forward_slashes),
18628            Path::new(&lower_case),
18629        ] {
18630            let verdict = reload_verdict(
18631                spelling,
18632                Some(&spawned),
18633                subc_control::RunningImageAgreement::Unavailable {
18634                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18635                },
18636            );
18637            assert_eq!(
18638                verdict.path,
18639                ReloadPathAgreement::Match,
18640                "configured {spelling:?}, spawned {spawned:?}"
18641            );
18642        }
18643    }
18644
18645    #[cfg(windows)]
18646    #[test]
18647    fn windows_reload_path_keeps_different_existing_program_pending() {
18648        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18649        let old = dir.join("old.exe");
18650        let new = dir.join("new.exe");
18651        std::fs::write(&old, b"same executable content").unwrap();
18652        std::fs::copy(&old, &new).unwrap();
18653        let spawned = std::fs::canonicalize(&old).unwrap();
18654        let image = subc_control::RunningImageAgreement::Unavailable {
18655            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18656        };
18657        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18658        assert!(
18659            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18660            if configured == new && spawned_from == spawned)
18661        );
18662        let missing = dir.join("missing.exe");
18663        assert!(matches!(
18664            reload_verdict(&missing, Some(&spawned), image).path,
18665            ReloadPathAgreement::Mismatch { .. }
18666        ));
18667    }
18668
18669    #[test]
18670    fn reload_verdict_detects_replaced_image_at_same_path() {
18671        let image = subc_control::RunningImageAgreement::Mismatch {
18672            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18673                digest: "old".into(),
18674            },
18675            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18676                digest: "new".into(),
18677            },
18678        };
18679        let verdict = reload_verdict(
18680            std::path::Path::new("/bin/same"),
18681            Some(std::path::Path::new("/bin/same")),
18682            image.clone(),
18683        );
18684        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18685        assert_eq!(verdict.image, image);
18686    }
18687
18688    #[test]
18689    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18690        let image = subc_control::RunningImageAgreement::Unavailable {
18691            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18692        };
18693        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18694        assert_eq!(
18695            verdict.path,
18696            subc_control::ReloadPathAgreement::Unavailable {
18697                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18698            }
18699        );
18700        assert_eq!(verdict.image, image);
18701
18702        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18703            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18704        };
18705        let verdict = reload_verdict(
18706            std::path::Path::new("/bin/same"),
18707            Some(std::path::Path::new("/bin/same")),
18708            unconfirmed.clone(),
18709        );
18710        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18711        assert_eq!(verdict.image, unconfirmed);
18712    }
18713
18714    #[test]
18715    fn reload_verdict_preserves_each_image_unavailability_reason() {
18716        use subc_control::RunningImageUnavailableReason as Reason;
18717
18718        for reason in [
18719            Reason::NotRunning,
18720            Reason::UnsupportedPlatform,
18721            Reason::RunningExecutableUnreadable,
18722            Reason::SpawnedPathUnreadable,
18723            Reason::HashFailed,
18724            Reason::ProcessIdentityUnconfirmed,
18725            Reason::Unknown("future_probe_reason".to_string()),
18726        ] {
18727            let image = subc_control::RunningImageAgreement::Unavailable {
18728                reason: reason.clone(),
18729            };
18730            let verdict = reload_verdict(
18731                std::path::Path::new("/bin/same"),
18732                Some(std::path::Path::new("/bin/same")),
18733                image.clone(),
18734            );
18735            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18736            assert_eq!(verdict.image, image, "{reason:?}");
18737        }
18738    }
18739
18740    #[tokio::test]
18741    async fn malformed_control_bodies_return_invalid_control_body() {
18742        let handler = ControlHandler::default();
18743        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18744
18745        for (corr, body) in [
18746            (56, br#"{"route_channel":1}"#.as_slice()),
18747            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18748            (
18749                58,
18750                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18751            ),
18752        ] {
18753            let request = Frame::build(
18754                FrameType::Request,
18755                control_flags(),
18756                0,
18757                0,
18758                corr,
18759                body.to_vec(),
18760            )
18761            .unwrap();
18762            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18763
18764            assert_eq!(response.len(), 1);
18765            assert_eq!(response[0].header.ty, FrameType::Error);
18766            assert_eq!(response[0].header.corr, corr);
18767            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18768        }
18769    }
18770
18771    #[tokio::test]
18772    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18773        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18774        let registry = Arc::new(Registry::default());
18775        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18776        let router = Router::with_control_handler(Arc::clone(&control));
18777        let connection = router.begin_connection();
18778        let (ctx, mut rx) = route_ctx(connection.id());
18779
18780        router
18781            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18782            .await
18783            .unwrap();
18784        let response = rx.recv().await.unwrap();
18785        let ack = parse_ack(&response);
18786        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18787        let channel = 1;
18788
18789        let goodbye =
18790            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18791        router.route_for_connection(&ctx, goodbye).await.unwrap();
18792        assert!(rx.try_recv().is_err());
18793        assert!(registry.get_module("aft").unwrap().is_none());
18794
18795        router
18796            .route_for_connection(&ctx, channel_request(channel, 13))
18797            .await
18798            .unwrap();
18799        let error_frame = rx.recv().await.unwrap();
18800        assert_eq!(error_frame.header.ty, FrameType::Error);
18801        assert_eq!(error_frame.header.channel, channel);
18802        let captured = crate::router::test_log::captured_logs(&logs);
18803        assert_eq!(
18804            captured
18805                .lines()
18806                .filter(|line| {
18807                    line.contains("module_id=aft")
18808                        && line.contains("reason=explicit_goodbye")
18809                        && line.contains("module registration ended")
18810                })
18811                .count(),
18812            1,
18813            "unexpected GOODBYE registry log: {captured}"
18814        );
18815    }
18816
18817    #[tokio::test]
18818    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18819        let registry = Arc::new(Registry::default());
18820        let handler = ControlHandler::new(registry).with_capability_config(
18821            [("prov".to_string(), true), ("cons".to_string(), true)],
18822            BTreeMap::new(),
18823        );
18824        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18825        register_capability_manifest(
18826            &handler,
18827            &provider_ctx,
18828            &mut provider_rx,
18829            capability_manifest("prov", &["thing/v1"], &[]),
18830            1,
18831        )
18832        .await;
18833        let mut consumer = capability_manifest("cons", &[], &[]);
18834        consumer.capabilities.as_mut().unwrap().requires.push(
18835            subc_protocol::manifest::CapabilityRequirement {
18836                capability: "thing/v1".to_string(),
18837                need: subc_protocol::manifest::CapabilityNeed::Required,
18838            },
18839        );
18840        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18841        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18842        assert_eq!(
18843            handler.capability_evaluator.verdict("cons", "thing/v1"),
18844            Some(CapabilityVerdict::Provided)
18845        );
18846        let (mut client_rx, _) = open_route_for_capability_test(
18847            &handler,
18848            &provider_ctx,
18849            &mut provider_rx,
18850            703,
18851            3,
18852            "prov",
18853            None,
18854        )
18855        .await;
18856        let goodbye =
18857            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18858        handler
18859            .handle_control_frame(&provider_ctx, goodbye)
18860            .await
18861            .unwrap();
18862        assert_eq!(
18863            handler.capability_evaluator.verdict("cons", "thing/v1"),
18864            Some(CapabilityVerdict::NeverProvided)
18865        );
18866        let closed = client_rx
18867            .try_recv()
18868            .expect("GOODBYE pushes route.closed before route GOODBYE");
18869        assert!(
18870            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18871            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18872        );
18873        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18874        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18875    }
18876
18877    struct RouteClosedFixture {
18878        handler: ControlHandler,
18879        #[cfg(unix)]
18880        supervisor: Supervisor,
18881        module_ctx: RouteCtx,
18882        #[cfg(unix)]
18883        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18884        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18885        route: Arc<crate::forwarding::RouteBinding>,
18886    }
18887
18888    async fn route_closed_fixture() -> RouteClosedFixture {
18889        let registry = Arc::new(Registry::default());
18890        let handler = ControlHandler::new(Arc::clone(&registry));
18891        #[cfg(unix)]
18892        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18893            .with_forwarding(Arc::clone(&handler.forwarding));
18894        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18895        register_capability_manifest(
18896            &handler,
18897            &module_ctx,
18898            &mut module_rx,
18899            capability_manifest("prov", &[], &[]),
18900            1,
18901        )
18902        .await;
18903        let (client_rx, bind) = open_route_for_capability_test(
18904            &handler,
18905            &module_ctx,
18906            &mut module_rx,
18907            702,
18908            2,
18909            "prov",
18910            None,
18911        )
18912        .await;
18913        let ModuleControlRequest::RouteBind {
18914            route_channel: channel,
18915            epoch: route_epoch,
18916            ..
18917        } = bind
18918        else {
18919            panic!("expected route.bind");
18920        };
18921        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18922            handler
18923                .forwarding
18924                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18925                .unwrap()
18926        else {
18927            panic!("the acknowledged route must be bound");
18928        };
18929        RouteClosedFixture {
18930            handler,
18931            #[cfg(unix)]
18932            supervisor,
18933            module_ctx,
18934            #[cfg(unix)]
18935            module_rx,
18936            client_rx,
18937            route,
18938        }
18939    }
18940
18941    impl RouteClosedFixture {
18942        #[cfg(unix)]
18943        async fn cut(&mut self) {
18944            let notices = async {
18945                let mut draining = self.module_rx.recv().await.unwrap();
18946                assert!(matches!(
18947                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18948                        &draining.body
18949                    )
18950                    .unwrap(),
18951                    subc_protocol::session::ModuleControlCommand::Draining {
18952                        reason: RouteCloseReason::Disable,
18953                        ..
18954                    }
18955                ));
18956                draining.flushed.take().unwrap().send(()).unwrap();
18957                let mut closing = self.client_rx.recv().await.unwrap();
18958                assert!(matches!(
18959                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18960                    ClientControlPush::RouteClosing {
18961                        reason: RouteCloseReason::Restart,
18962                        ..
18963                    }
18964                ));
18965                closing.flushed.take().unwrap().send(()).unwrap();
18966            };
18967            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18968            result.unwrap();
18969        }
18970
18971        fn disconnect(&mut self) -> ClientControlPush {
18972            self.handler
18973                .cleanup_connection(self.module_ctx.connection_id)
18974                .unwrap();
18975            let closed = self.client_rx.try_recv().unwrap();
18976            assert_eq!(closed.header.ty, FrameType::Push);
18977            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18978            assert!(matches!(
18979                &push,
18980                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18981                    if channels == &[self.route.client_channel]
18982            ));
18983            assert_eq!(
18984                self.client_rx.try_recv().unwrap().header.ty,
18985                FrameType::Goodbye
18986            );
18987            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18988            push
18989        }
18990    }
18991
18992    #[cfg(unix)]
18993    #[tokio::test(start_paused = true)]
18994    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18995        let mut fixture = route_closed_fixture().await;
18996        fixture.cut().await;
18997        assert!(matches!(
18998            fixture.disconnect(),
18999            ClientControlPush::RouteClosed {
19000                reason: RouteCloseReason::Restart,
19001                drained: true,
19002                ..
19003            }
19004        ));
19005    }
19006
19007    #[cfg(unix)]
19008    #[tokio::test(start_paused = true)]
19009    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
19010        let mut fixture = route_closed_fixture().await;
19011        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
19012        let started = tokio::time::Instant::now();
19013        fixture.cut().await;
19014        assert!(started.elapsed() >= Duration::from_secs(2));
19015        assert_eq!(fixture.route.flow.in_flight(), 1);
19016        assert!(matches!(
19017            fixture.disconnect(),
19018            ClientControlPush::RouteClosed {
19019                reason: RouteCloseReason::Restart,
19020                drained: false,
19021                ..
19022            }
19023        ));
19024    }
19025
19026    #[tokio::test]
19027    async fn module_connection_crash_reports_crash_and_not_drained() {
19028        let mut fixture = route_closed_fixture().await;
19029        // The server calls cleanup_connection on module EOF. Without a planned
19030        // daemon shutdown, that disconnect must remain a crash with no prior
19031        // route.closing notice, even when the route has no in-flight calls.
19032        assert!(matches!(
19033            fixture.disconnect(),
19034            ClientControlPush::RouteClosed {
19035                reason: RouteCloseReason::Crash,
19036                drained: false,
19037                ..
19038            }
19039        ));
19040    }
19041
19042    #[tokio::test]
19043    async fn dropping_router_connection_releases_registration() {
19044        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19045        let registry = Arc::new(Registry::default());
19046        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
19047        let router = Router::with_control_handler(Arc::clone(&control));
19048        let connection = router.begin_connection();
19049        let connection_id = connection.id();
19050        let (ctx, mut rx) = route_ctx(connection_id);
19051
19052        router
19053            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
19054            .await
19055            .unwrap();
19056        let response = rx.recv().await.unwrap();
19057        let ack = parse_ack(&response);
19058        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
19059        assert!(registry.get_module("aft").unwrap().is_some());
19060
19061        drop(connection);
19062
19063        assert!(registry.get_module("aft").unwrap().is_none());
19064        assert_eq!(registry.active_registration_count().unwrap(), 0);
19065
19066        control
19067            .cleanup_connection(ConnectionId::new(u64::MAX))
19068            .unwrap();
19069        let captured = crate::router::test_log::captured_logs(&logs);
19070        println!("captured registry lifecycle logs:\n{captured}");
19071        let events: Vec<_> = captured
19072            .lines()
19073            .filter(|line| {
19074                line.contains("module registered module_id=aft ")
19075                    || line.contains("module registration ended")
19076            })
19077            .collect();
19078        assert_eq!(
19079            events.len(),
19080            2,
19081            "unexpected registry lifecycle logs: {captured}"
19082        );
19083        assert!(events[0].contains("module registered module_id=aft "));
19084        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
19085        assert!(events[1].contains(&format!(
19086            "module_id=aft connection_id={}",
19087            connection_id.get()
19088        )));
19089        assert!(events[1].contains("reason=connection_closed"));
19090        assert!(events[1].contains("module registration ended"));
19091        assert_eq!(
19092            captured
19093                .lines()
19094                .filter(|line| line.contains("module registered module_id=aft "))
19095                .count(),
19096            1,
19097            "legacy registration admission line must appear once: {captured}"
19098        );
19099    }
19100
19101    #[tokio::test]
19102    async fn hello_registration_keeps_legacy_module_registered_line_once() {
19103        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19104        let registry = Arc::new(Registry::default());
19105        let control = ControlHandler::new(Arc::clone(&registry));
19106        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
19107        hello_via_sink(
19108            &control,
19109            &ctx,
19110            &mut rx,
19111            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
19112        )
19113        .await;
19114
19115        let captured = crate::router::test_log::captured_logs(&logs);
19116        let admissions: Vec<_> = captured
19117            .lines()
19118            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
19119            .collect();
19120        assert_eq!(
19121            admissions.len(),
19122            1,
19123            "legacy admission line must remain exactly once: {captured}"
19124        );
19125        assert!(admissions[0].contains("routable_provider=true"));
19126        assert!(admissions[0].contains("connection_id=777"));
19127    }
19128
19129    fn capability_manifest(
19130        module_id: &str,
19131        provides: &[&str],
19132        must_never_reach: &[&str],
19133    ) -> ModuleManifest {
19134        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
19135        manifest.capabilities = Some(CapabilityDeclarations {
19136            provides: provides
19137                .iter()
19138                .map(|capability| (*capability).to_string())
19139                .collect(),
19140            requires: Vec::new(),
19141            must_never_reach: must_never_reach
19142                .iter()
19143                .map(|capability| (*capability).to_string())
19144                .collect(),
19145        });
19146        manifest
19147    }
19148
19149    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
19150        Frame::build(
19151            FrameType::Hello,
19152            control_flags(),
19153            0,
19154            0,
19155            corr,
19156            serde_json::to_vec(&ModuleHelloBody {
19157                protocol_ver: manifest.protocol_ver,
19158                manifest,
19159                control_ops: None,
19160                launch_nonce: None,
19161            })
19162            .expect("capability test HELLO serializes"),
19163        )
19164        .expect("capability test HELLO frame builds")
19165    }
19166
19167    fn catalog_update_with_capabilities_frame(
19168        corr: u64,
19169        capabilities: CapabilityDeclarations,
19170    ) -> Frame {
19171        Frame::build(
19172            FrameType::Request,
19173            control_flags(),
19174            0,
19175            0,
19176            corr,
19177            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
19178                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
19179                capabilities: Some(capabilities),
19180                ready: None,
19181            })
19182            .expect("capability catalog.update serializes"),
19183        )
19184        .expect("capability catalog.update frame builds")
19185    }
19186
19187    async fn register_capability_manifest(
19188        handler: &ControlHandler,
19189        ctx: &RouteCtx,
19190        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
19191        manifest: ModuleManifest,
19192        corr: u64,
19193    ) {
19194        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
19195    }
19196
19197    async fn open_route_for_capability_test(
19198        handler: &ControlHandler,
19199        target_ctx: &RouteCtx,
19200        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
19201        client_connection_id: u64,
19202        corr: u64,
19203        target_module_id: &str,
19204        consumer_identity: Option<ConsumerIdentity>,
19205    ) -> (
19206        mpsc::Receiver<crate::router::OutboundFrame>,
19207        ModuleControlRequest,
19208    ) {
19209        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
19210        let route_handler = handler.clone();
19211        let target_module_id = target_module_id.to_string();
19212        let route_task = tokio::spawn(async move {
19213            route_handler
19214                .handle_control_frame(
19215                    &client_ctx,
19216                    route_open_frame_with_admission_facts(
19217                        corr,
19218                        &target_module_id,
19219                        unique_project_root("admission-facts"),
19220                        consumer_identity,
19221                        None,
19222                    ),
19223                )
19224                .await
19225                .expect("capability test route.open succeeds")
19226        });
19227        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
19228            .await
19229            .expect("capability test route.open must reach route.bind")
19230            .expect("target control receiver stays open");
19231        let bind_request: ModuleControlRequest =
19232            serde_json::from_slice(&bind.body).expect("route.bind decodes");
19233        handler
19234            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
19235            .await
19236            .expect("capability test route.bind ACK succeeds");
19237        assert!(route_task.await.expect("route.open task joins").is_empty());
19238        let opened = client_rx
19239            .recv()
19240            .await
19241            .expect("successful route.open publishes a response");
19242        assert!(matches!(
19243            serde_json::from_slice::<ClientControlResponse>(&opened.body),
19244            Ok(ClientControlResponse::RouteOpen { .. })
19245        ));
19246        (client_rx, bind_request)
19247    }
19248
19249    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
19250        assert_eq!(frame.header.ty, FrameType::Push);
19251        assert_eq!(frame.header.channel, 0);
19252        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
19253            .expect("route.closed control push decodes");
19254        let ClientControlPush::RouteClosed { channels, .. } = &push else {
19255            panic!("expected route.closed");
19256        };
19257        assert_eq!(channels.len(), 1, "exactly one violating route closed");
19258        let closed_channel = channels[0];
19259        let channels = channels.clone();
19260        assert_eq!(
19261            push,
19262            ClientControlPush::RouteClosed {
19263                module_id: target_module_id.to_string(),
19264                channels,
19265                reason: RouteCloseReason::CapabilityDenied,
19266                drained: false,
19267                abandoned: 0,
19268                excluded_subscriptions: 0,
19269                terminal: Some(false),
19270            }
19271        );
19272        closed_channel
19273    }
19274
19275    #[tokio::test]
19276    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
19277        let registry = Arc::new(Registry::default());
19278        let forwarding = Arc::new(ForwardingTable::default());
19279        let supervisor = SupervisorHandle::new();
19280        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19281        let handler =
19282            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19283                .with_supervisor(supervisor);
19284        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19285        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19286        register_capability_manifest(
19287            &handler,
19288            &target_ctx,
19289            &mut target_rx,
19290            capability_manifest("target", &["credentials-provider/v1"], &[]),
19291            1,
19292        )
19293        .await;
19294        register_capability_manifest(
19295            &handler,
19296            &opener_ctx,
19297            &mut opener_rx,
19298            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19299            2,
19300        )
19301        .await;
19302
19303        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19304        let replies = handler
19305            .handle_control_frame(
19306                &client_ctx,
19307                route_open_frame_with_admission_facts(
19308                    3,
19309                    "target",
19310                    unique_project_root("admission-facts"),
19311                    Some(ConsumerIdentity {
19312                        module_id: "opener".to_string(),
19313                        launch_nonce: "opener-nonce".to_string(),
19314                    }),
19315                    None,
19316                ),
19317            )
19318            .await
19319            .expect("denied route.open returns a typed frame");
19320        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19321        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19322        assert!(
19323            target_rx.try_recv().is_err(),
19324            "forbidden route.open must not relay route.bind"
19325        );
19326    }
19327
19328    #[tokio::test]
19329    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19330        let registry = Arc::new(Registry::default());
19331        let forwarding = Arc::new(ForwardingTable::default());
19332        let supervisor = SupervisorHandle::new();
19333        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19334        let handler =
19335            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19336                .with_supervisor(supervisor);
19337        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19338        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19339        register_capability_manifest(
19340            &handler,
19341            &target_ctx,
19342            &mut target_rx,
19343            capability_manifest("target", &["credentials-provider/v1"], &[]),
19344            1,
19345        )
19346        .await;
19347        register_capability_manifest(
19348            &handler,
19349            &old_opener_ctx,
19350            &mut old_opener_rx,
19351            capability_manifest("opener", &[], &[]),
19352            2,
19353        )
19354        .await;
19355        let (mut client_rx, _) = open_route_for_capability_test(
19356            &handler,
19357            &target_ctx,
19358            &mut target_rx,
19359            712,
19360            3,
19361            "target",
19362            Some(ConsumerIdentity {
19363                module_id: "opener".to_string(),
19364                launch_nonce: "opener-nonce".to_string(),
19365            }),
19366        )
19367        .await;
19368        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19369
19370        handler
19371            .cleanup_connection(old_opener_ctx.connection_id)
19372            .expect("old opener registration cleans up");
19373        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19374        register_capability_manifest(
19375            &handler,
19376            &new_opener_ctx,
19377            &mut new_opener_rx,
19378            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19379            4,
19380        )
19381        .await;
19382
19383        let closed_channel = assert_capability_denied_push(
19384            client_rx
19385                .try_recv()
19386                .expect("HELLO deny addition must emit route.closed")
19387                .frame,
19388            "target",
19389        );
19390        let goodbye = client_rx
19391            .try_recv()
19392            .expect("HELLO deny addition must send the client a route GOODBYE")
19393            .frame;
19394        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19395        assert_eq!(goodbye.header.channel, closed_channel);
19396        assert_ne!(goodbye.header.channel, 0);
19397        assert_ne!(goodbye.header.epoch, 0);
19398        assert!(client_rx.try_recv().is_err());
19399        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19400        assert!(matches!(
19401            target_rx.try_recv(),
19402            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19403        ));
19404    }
19405
19406    #[tokio::test]
19407    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19408        let registry = Arc::new(Registry::default());
19409        let forwarding = Arc::new(ForwardingTable::default());
19410        let supervisor = SupervisorHandle::new();
19411        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19412        let handler =
19413            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19414                .with_supervisor(supervisor);
19415        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19416        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19417        register_capability_manifest(
19418            &handler,
19419            &target_ctx,
19420            &mut target_rx,
19421            capability_manifest("target", &[], &[]),
19422            1,
19423        )
19424        .await;
19425        register_capability_manifest(
19426            &handler,
19427            &opener_ctx,
19428            &mut opener_rx,
19429            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19430            2,
19431        )
19432        .await;
19433        let (mut client_rx, _) = open_route_for_capability_test(
19434            &handler,
19435            &target_ctx,
19436            &mut target_rx,
19437            722,
19438            3,
19439            "target",
19440            Some(ConsumerIdentity {
19441                module_id: "opener".to_string(),
19442                launch_nonce: "opener-nonce".to_string(),
19443            }),
19444        )
19445        .await;
19446        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19447
19448        let replies = handler
19449            .handle_control_frame(
19450                &target_ctx,
19451                catalog_update_with_capabilities_frame(
19452                    4,
19453                    CapabilityDeclarations {
19454                        provides: vec!["credentials-provider/v1".to_string()],
19455                        requires: Vec::new(),
19456                        must_never_reach: Vec::new(),
19457                    },
19458                ),
19459            )
19460            .await
19461            .expect("claim catalog.update succeeds");
19462        assert!(matches!(
19463            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19464            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19465        ));
19466        let closed_channel = assert_capability_denied_push(
19467            client_rx
19468                .try_recv()
19469                .expect("claim addition must emit route.closed")
19470                .frame,
19471            "target",
19472        );
19473        let goodbye = client_rx
19474            .try_recv()
19475            .expect("claim addition must send the client a route GOODBYE")
19476            .frame;
19477        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19478        assert_eq!(goodbye.header.channel, closed_channel);
19479        assert_ne!(goodbye.header.channel, 0);
19480        assert_ne!(goodbye.header.epoch, 0);
19481        assert!(client_rx.try_recv().is_err());
19482        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19483        assert!(matches!(
19484            target_rx.try_recv(),
19485            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19486        ));
19487    }
19488
19489    #[tokio::test]
19490    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19491        let registry = Arc::new(Registry::default());
19492        let forwarding = Arc::new(ForwardingTable::default());
19493        let supervisor = SupervisorHandle::new();
19494        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19495        let handler =
19496            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19497                .with_supervisor(supervisor);
19498        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19499        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19500        register_capability_manifest(
19501            &handler,
19502            &target_ctx,
19503            &mut target_rx,
19504            capability_manifest("target", &["credentials-provider/v1"], &[]),
19505            1,
19506        )
19507        .await;
19508        register_capability_manifest(
19509            &handler,
19510            &opener_ctx,
19511            &mut opener_rx,
19512            capability_manifest("opener", &[], &[]),
19513            2,
19514        )
19515        .await;
19516        let (mut client_rx, _) = open_route_for_capability_test(
19517            &handler,
19518            &target_ctx,
19519            &mut target_rx,
19520            732,
19521            3,
19522            "target",
19523            Some(ConsumerIdentity {
19524                module_id: "opener".to_string(),
19525                launch_nonce: "opener-nonce".to_string(),
19526            }),
19527        )
19528        .await;
19529        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19530
19531        handler
19532            .handle_control_frame(
19533                &target_ctx,
19534                catalog_update_with_capabilities_frame(
19535                    4,
19536                    CapabilityDeclarations {
19537                        provides: Vec::new(),
19538                        requires: Vec::new(),
19539                        must_never_reach: Vec::new(),
19540                    },
19541                ),
19542            )
19543            .await
19544            .expect("claim removal catalog.update succeeds");
19545        assert_eq!(
19546            forwarding.active_binding_count().unwrap(),
19547            1,
19548            "removing an attested target claim must leave the route census unchanged"
19549        );
19550        assert!(
19551            client_rx.try_recv().is_err(),
19552            "claim removal must not emit route.closed or a client route GOODBYE"
19553        );
19554        assert!(
19555            target_rx.try_recv().is_err(),
19556            "claim removal must not send the target a route GOODBYE"
19557        );
19558    }
19559
19560    /// A direct client may open a route to a denied capability provider; this
19561    /// policy applies only to attested supervised module origins, not to direct clients.
19562    #[tokio::test]
19563    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19564        let registry = Arc::new(Registry::default());
19565        let forwarding = Arc::new(ForwardingTable::default());
19566        let supervisor = SupervisorHandle::new();
19567        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19568        let handler =
19569            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19570                .with_supervisor(supervisor);
19571        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19572        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19573        register_capability_manifest(
19574            &handler,
19575            &target_ctx,
19576            &mut target_rx,
19577            capability_manifest("target", &["credentials-provider/v1"], &[]),
19578            1,
19579        )
19580        .await;
19581        register_capability_manifest(
19582            &handler,
19583            &opener_ctx,
19584            &mut opener_rx,
19585            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19586            2,
19587        )
19588        .await;
19589
19590        let (_client_rx, bind) = open_route_for_capability_test(
19591            &handler,
19592            &target_ctx,
19593            &mut target_rx,
19594            742,
19595            3,
19596            "target",
19597            None,
19598        )
19599        .await;
19600        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19601            panic!("direct scope-honesty route must bind");
19602        };
19603        assert_eq!(principal, Some(Principal::Direct));
19604        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19605    }
19606
19607    /// A module that denies a capability receives no self-route exemption when it
19608    /// also attestedly provides that capability.
19609    #[tokio::test]
19610    async fn must_never_reach_self_route_is_capability_forbidden() {
19611        let registry = Arc::new(Registry::default());
19612        let forwarding = Arc::new(ForwardingTable::default());
19613        let supervisor = SupervisorHandle::new();
19614        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19615        let handler =
19616            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19617                .with_supervisor(supervisor);
19618        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19619        register_capability_manifest(
19620            &handler,
19621            &self_ctx,
19622            &mut self_rx,
19623            capability_manifest(
19624                "self-provider",
19625                &["credentials-provider/v1"],
19626                &["credentials-provider/v1"],
19627            ),
19628            1,
19629        )
19630        .await;
19631
19632        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19633        let replies = handler
19634            .handle_control_frame(
19635                &client_ctx,
19636                route_open_frame_with_admission_facts(
19637                    2,
19638                    "self-provider",
19639                    unique_project_root("admission-facts"),
19640                    Some(ConsumerIdentity {
19641                        module_id: "self-provider".to_string(),
19642                        launch_nonce: "self-nonce".to_string(),
19643                    }),
19644                    None,
19645                ),
19646            )
19647            .await
19648            .expect("self-route refusal returns a typed frame");
19649        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19650        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19651        assert!(
19652            self_rx.try_recv().is_err(),
19653            "self denial must not relay route.bind"
19654        );
19655    }
19656
19657    #[test]
19658    fn unsupported_channel_zero_frame_returns_error() {
19659        let handler = ControlHandler::default();
19660        let request = Frame::build(
19661            FrameType::Request,
19662            control_flags(),
19663            0,
19664            0,
19665            21,
19666            b"opaque".to_vec(),
19667        )
19668        .unwrap();
19669
19670        let response = handler
19671            .handle_control(ConnectionId::new(1), request)
19672            .unwrap();
19673
19674        assert_eq!(response[0].header.ty, FrameType::Error);
19675        assert_eq!(
19676            parse_error(&response[0])["code"],
19677            "unsupported_control_frame"
19678        );
19679    }
19680
19681    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19682    /// a swap is not wired yet, so the candidate is registered here directly
19683    /// into the registry and forwarding candidate slots, the way the swap's
19684    /// HELLO admission will.
19685    mod swap {
19686        use super::*;
19687
19688        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19689        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19690
19691        struct Swap {
19692            registry: Arc<Registry>,
19693            forwarding: Arc<ForwardingTable>,
19694            handler: ControlHandler,
19695            incumbent_ctx: RouteCtx,
19696            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19697            candidate_ctx: RouteCtx,
19698            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19699        }
19700
19701        async fn swap_with_incumbent() -> Swap {
19702            let registry = Arc::new(Registry::default());
19703            let forwarding = Arc::new(ForwardingTable::default());
19704            let handler =
19705                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19706            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19707            hello_via_sink(
19708                &handler,
19709                &incumbent_ctx,
19710                &mut incumbent_rx,
19711                hello_frame("aft", PROTOCOL_VERSION, 7),
19712            )
19713            .await;
19714            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19715            Swap {
19716                registry,
19717                forwarding,
19718                handler,
19719                incumbent_ctx,
19720                incumbent_rx,
19721                candidate_ctx,
19722                candidate_rx,
19723            }
19724        }
19725
19726        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19727            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19728            candidate_manifest.ready = ready;
19729            let registration = swap
19730                .registry
19731                .register_candidate_with_control_ops(
19732                    candidate_manifest,
19733                    PROTOCOL_VERSION,
19734                    CANDIDATE,
19735                    module_baseline_control_ops(),
19736                )
19737                .unwrap();
19738            swap.forwarding
19739                .register_candidate_module_connection(
19740                    CANDIDATE,
19741                    "aft".to_string(),
19742                    PROTOCOL_VERSION,
19743                    manifest_concurrency(&registration.manifest),
19744                    swap.candidate_ctx.egress.clone(),
19745                )
19746                .unwrap();
19747        }
19748
19749        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19750            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19751            swap.registry.promote_candidate("aft").unwrap().unwrap();
19752            cutover.incumbent.unwrap()
19753        }
19754
19755        /// A swap candidate's HELLO reserves its candidate registry entry
19756        /// before installing its candidate forwarding endpoint. The swap
19757        /// supervisor promotes a ready candidate as soon as it reads it as
19758        /// registered, and promotion cuts forwarding over to the candidate
19759        /// endpoint, so the lookup the supervisor reads
19760        /// (`Registry::published_registration`) must not return the candidate
19761        /// until that endpoint exists. Otherwise the cutover finds no candidate
19762        /// endpoint and the swap fails as if the candidate had disconnected.
19763        #[tokio::test]
19764        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19765            let mut swap = swap_with_incumbent().await;
19766            let hold = Arc::new(std::sync::Barrier::new(2));
19767            let handler = swap
19768                .handler
19769                .clone()
19770                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19771            handler
19772                .supervisor
19773                .open_swap("aft", "candidate-nonce".to_string());
19774            let hello = {
19775                let handler = handler.clone();
19776                let candidate_ctx = swap.candidate_ctx.clone();
19777                std::thread::spawn(move || {
19778                    handler
19779                        .handle_hello(
19780                            candidate_ctx.connection_id,
19781                            Some(candidate_ctx.egress.clone()),
19782                            hello_frame_with_nonce(
19783                                "aft",
19784                                PROTOCOL_VERSION,
19785                                8,
19786                                Some("candidate-nonce"),
19787                            ),
19788                        )
19789                        .unwrap()
19790                })
19791            };
19792
19793            hold.wait();
19794            // Parked: the candidate slot is claimed but not published, and
19795            // forwarding has no candidate endpoint.
19796            assert!(swap
19797                .registry
19798                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19799                .unwrap()
19800                .is_some());
19801            assert!(swap
19802                .registry
19803                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19804                .unwrap()
19805                .is_none());
19806            assert!(swap
19807                .forwarding
19808                .module_endpoint_for_connection(CANDIDATE)
19809                .unwrap()
19810                .is_none());
19811
19812            hold.wait();
19813            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19814            assert_eq!(
19815                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19816                FrameType::HelloAck
19817            );
19818            let published = swap
19819                .registry
19820                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19821                .unwrap()
19822                .expect("candidate is published once its HELLO completes");
19823            assert_eq!(published.connection_id, CANDIDATE);
19824            assert!(swap
19825                .forwarding
19826                .module_endpoint_for_connection(CANDIDATE)
19827                .unwrap()
19828                .is_some());
19829        }
19830
19831        #[tokio::test]
19832        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19833            let mut swap = swap_with_incumbent().await;
19834            let hold = Arc::new(std::sync::Barrier::new(2));
19835            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19836            swap.handler
19837                .supervisor
19838                .open_swap("aft", "candidate-nonce".to_string());
19839            let hello = {
19840                let handler = swap.handler.clone();
19841                let candidate_ctx = swap.candidate_ctx.clone();
19842                std::thread::spawn(move || {
19843                    handler
19844                        .handle_hello(
19845                            CANDIDATE,
19846                            Some(candidate_ctx.egress),
19847                            hello_frame_with_nonce(
19848                                "aft",
19849                                PROTOCOL_VERSION,
19850                                8,
19851                                Some("candidate-nonce"),
19852                            ),
19853                        )
19854                        .unwrap()
19855                })
19856            };
19857            hold.wait();
19858            assert_eq!(
19859                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19860                FrameType::HelloAck
19861            );
19862            let reader_registry = Arc::clone(&swap.registry);
19863            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19864                reader_registry
19865                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19866                    .unwrap()
19867            });
19868            assert!(hello.join().unwrap().is_empty());
19869            assert_eq!(
19870                published
19871                    .expect("ACK makes candidate publication visible")
19872                    .connection_id,
19873                CANDIDATE
19874            );
19875            assert_eq!(
19876                swap.registry.generation().unwrap(),
19877                1,
19878                "candidate is not a second catalog entry"
19879            );
19880        }
19881
19882        #[tokio::test]
19883        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19884            let mut swap = swap_with_incumbent().await;
19885            let hold = Arc::new(std::sync::Barrier::new(2));
19886            let handler = swap
19887                .handler
19888                .clone()
19889                .with_hello_registry_to_forwarding_hold(hold.clone());
19890            handler
19891                .supervisor
19892                .open_swap("aft", "candidate-nonce".into());
19893            let hello = {
19894                let handler = handler.clone();
19895                let ctx = swap.candidate_ctx.clone();
19896                std::thread::spawn(move || {
19897                    handler
19898                        .handle_hello(
19899                            CANDIDATE,
19900                            Some(ctx.egress),
19901                            hello_frame_with_nonce(
19902                                "aft",
19903                                PROTOCOL_VERSION,
19904                                8,
19905                                Some("candidate-nonce"),
19906                            ),
19907                        )
19908                        .unwrap()
19909                })
19910            };
19911            hold.wait();
19912            assert_eq!(
19913                swap.registry
19914                    .deregister_connection(CANDIDATE)
19915                    .unwrap()
19916                    .len(),
19917                1
19918            );
19919            hold.wait();
19920            assert!(hello.join().unwrap().is_empty());
19921            assert_eq!(
19922                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19923                FrameType::HelloAck
19924            );
19925            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19926            assert_eq!(
19927                handler
19928                    .supervisor
19929                    .swap_hello_admission("aft", Some("candidate-nonce")),
19930                SwapHelloAdmission::Candidate,
19931                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19932            );
19933            handler.supervisor.close_swap("aft");
19934        }
19935
19936        fn keyed_total(counters: &Value, key: &str) -> u64 {
19937            counters[key]
19938                .as_object()
19939                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19940                .unwrap_or(0)
19941        }
19942
19943        #[tokio::test]
19944        async fn replacement_logs_old_end_and_new_admission_once() {
19945            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19946            let mut swap = swap_with_incumbent().await;
19947            swap.handler
19948                .supervisor
19949                .open_swap("aft", "candidate-nonce".to_string());
19950            hello_via_sink(
19951                &swap.handler,
19952                &swap.candidate_ctx,
19953                &mut swap.candidate_rx,
19954                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19955            )
19956            .await;
19957            cutover(&swap);
19958            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19959
19960            let captured = crate::router::test_log::captured_logs(&logs);
19961            println!("captured replacement registry logs:\n{captured}");
19962            let new_admissions: Vec<_> = captured
19963                .lines()
19964                .filter(|line| {
19965                    line.contains("connection_id=40")
19966                        && line.contains("swap candidate registered; not routable until cutover")
19967                })
19968                .collect();
19969            assert_eq!(
19970                new_admissions.len(),
19971                1,
19972                "unexpected admission logs: {captured}"
19973            );
19974            assert!(new_admissions[0].contains("module_id=aft"));
19975            assert!(new_admissions[0].contains("connection_id=40"));
19976            assert!(
19977                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19978            );
19979            assert!(new_admissions[0].contains("ready=true"));
19980
19981            let old_admissions: Vec<_> = captured
19982                .lines()
19983                .filter(|line| {
19984                    line.contains("module registered module_id=aft ")
19985                        && line.contains("connection_id=30")
19986                })
19987                .collect();
19988            assert_eq!(
19989                old_admissions.len(),
19990                1,
19991                "unexpected incumbent admission: {captured}"
19992            );
19993
19994            let old_ends: Vec<_> = captured
19995                .lines()
19996                .filter(|line| {
19997                    line.contains("connection_id=30") && line.contains("module registration ended")
19998                })
19999                .collect();
20000            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
20001            assert!(old_ends[0].contains("module_id=aft"));
20002            assert!(old_ends[0].contains("connection_id=30"));
20003            assert!(old_ends[0].contains("reason=replaced"));
20004            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
20005            assert_eq!(
20006                captured
20007                    .lines()
20008                    .filter(|line| line.contains("module registration promoted"))
20009                    .count(),
20010                1,
20011                "unexpected promotion logs: {captured}"
20012            );
20013        }
20014
20015        /// An ack from the incumbent for a bind it was sent before cutover,
20016        /// arriving before the incumbent is drained. The incumbent is the live
20017        /// connection carrying every other client's routes, so the ack must
20018        /// not end it: the waiting client is told to retry, the reservation is
20019        /// given back, and the incumbent is told to drop just that binding.
20020        #[tokio::test]
20021        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
20022            let mut swap = swap_with_incumbent().await;
20023            let handler = swap.handler.clone();
20024
20025            // A co-tenant route, bound on the incumbent before the swap.
20026            let cotenant = ConnectionId::new(31);
20027            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
20028            let (cotenant_task, cotenant_bind) = relay_route_open(
20029                &handler,
20030                cotenant,
20031                &cotenant_ctx.egress,
20032                &mut swap.incumbent_rx,
20033                100,
20034                "aft",
20035                "swap-cotenant",
20036            )
20037            .await;
20038            handler
20039                .handle_control_frame(
20040                    &swap.incumbent_ctx,
20041                    route_bind_ack(cotenant_bind.header.corr),
20042                )
20043                .await
20044                .unwrap();
20045            assert!(cotenant_task.await.unwrap().is_empty());
20046            let (cotenant_channel, cotenant_epoch) =
20047                published_route(&cotenant_rx.recv().await.unwrap());
20048
20049            // A second route.open, relayed to the incumbent and not yet acked.
20050            let caller = ConnectionId::new(32);
20051            let (caller_ctx, mut caller_rx) = route_ctx(caller);
20052            let (caller_task, caller_bind) = relay_route_open(
20053                &handler,
20054                caller,
20055                &caller_ctx.egress,
20056                &mut swap.incumbent_rx,
20057                101,
20058                "aft",
20059                "swap-caller",
20060            )
20061            .await;
20062            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
20063
20064            register_candidate(&swap, None);
20065            cutover(&swap);
20066
20067            // The incumbent acks after promotion and before any drain.
20068            let ack = handler
20069                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
20070                .await;
20071            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
20072            if module_loop_error.is_some() {
20073                // What the connection loop does with an untranslated router
20074                // error: end the connection, releasing every route on it.
20075                handler.cleanup_connection(INCUMBENT).unwrap();
20076            }
20077
20078            // 1. The incumbent's other routes survive.
20079            assert!(
20080                cotenant_rx.try_recv().is_err(),
20081                "the co-tenant route on the incumbent was torn down by one late ack: \
20082                 {module_loop_error:?}"
20083            );
20084            assert!(matches!(
20085                swap.forwarding
20086                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
20087                    .unwrap(),
20088                DataRoute::Client(DataRouteState::Bound(_))
20089            ));
20090            assert_eq!(module_loop_error, None);
20091            assert!(swap
20092                .registry
20093                .get_module_by_connection(INCUMBENT)
20094                .unwrap()
20095                .is_some());
20096
20097            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
20098            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
20099                .await
20100                .expect("the incumbent is told to drop the abandoned binding")
20101                .unwrap()
20102                .frame;
20103            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
20104            assert_eq!(goodbye.header.channel, abandoned_channel);
20105            assert_eq!(goodbye.header.epoch, abandoned_epoch);
20106            assert!(swap.incumbent_rx.try_recv().is_err());
20107
20108            // 3. The waiting client gets a retryable refusal and no route.
20109            let response = caller_task.await.unwrap();
20110            assert_eq!(response.len(), 1);
20111            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
20112            assert!(caller_rx.try_recv().is_err());
20113
20114            // 4. The reservation pair is given back, and the pending bind
20115            //    settled exactly once: one accepted open (the co-tenant) and one
20116            //    refused open (the caller), nothing counted twice.
20117            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
20118            let counters = handler.counters().snapshot();
20119            assert_eq!(
20120                keyed_total(&counters, "route_open_accepted_by_principal"),
20121                1
20122            );
20123            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
20124            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
20125        }
20126
20127        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
20128        /// id would resolve to the promoted candidate and every new route.open
20129        /// would be refused as reloading, leaving neither process routable.
20130        #[tokio::test]
20131        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
20132            let mut swap = swap_with_incumbent().await;
20133            register_candidate(&swap, None);
20134            let incumbent = cutover(&swap);
20135            swap.forwarding
20136                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
20137                .unwrap()
20138                .expect("the incumbent is still registered");
20139
20140            let client = ConnectionId::new(33);
20141            let (client_ctx, mut client_rx) = route_ctx(client);
20142            let route_handler = swap.handler.clone();
20143            let open_ctx = RouteCtx {
20144                connection_id: client,
20145                egress: client_ctx.egress.clone(),
20146            };
20147            let mut route_task = tokio::spawn(async move {
20148                route_handler
20149                    .handle_control_frame(
20150                        &open_ctx,
20151                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
20152                    )
20153                    .await
20154                    .unwrap()
20155            });
20156            let bind = tokio::select! {
20157                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
20158                response = &mut route_task => {
20159                    let response = response.unwrap();
20160                    panic!(
20161                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
20162                        parse_error(&response[0])["code"]
20163                    );
20164                }
20165            };
20166            swap.handler
20167                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
20168                .await
20169                .unwrap();
20170            assert!(route_task.await.unwrap().is_empty());
20171            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
20172            match swap
20173                .forwarding
20174                .lookup_data_route(client, channel, epoch)
20175                .unwrap()
20176            {
20177                DataRoute::Client(DataRouteState::Bound(route)) => {
20178                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
20179                }
20180                other => panic!("expected a bound route on the candidate, got {other:?}"),
20181            }
20182            assert!(swap.incumbent_rx.try_recv().is_err());
20183        }
20184
20185        /// A candidate declares itself ready with `catalog.update` on its own
20186        /// connection. If the connection-keyed registry lookups searched only the
20187        /// active slot, this would answer `not_registered` and the candidate
20188        /// would never become ready.
20189        #[tokio::test]
20190        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
20191            let swap = swap_with_incumbent().await;
20192            register_candidate(&swap, Some(false));
20193            let update = Frame::build(
20194                FrameType::Request,
20195                control_flags(),
20196                0,
20197                0,
20198                55,
20199                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
20200                    provides: manifest("aft", PROTOCOL_VERSION).provides,
20201                    capabilities: None,
20202                    ready: Some(true),
20203                })
20204                .unwrap(),
20205            )
20206            .unwrap();
20207
20208            let replies = swap
20209                .handler
20210                .handle_control_frame(&swap.candidate_ctx, update)
20211                .await
20212                .unwrap();
20213
20214            assert_eq!(replies.len(), 1);
20215            assert_eq!(
20216                replies[0].header.ty,
20217                FrameType::Response,
20218                "candidate catalog.update was refused: {:?}",
20219                serde_json::from_slice::<Value>(&replies[0].body).ok()
20220            );
20221            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
20222            assert_eq!(
20223                swap.registry
20224                    .get_module("aft")
20225                    .unwrap()
20226                    .unwrap()
20227                    .connection_id,
20228                INCUMBENT
20229            );
20230        }
20231    }
20232
20233    /// The HELLO gate while the supervisor has a swap open: only the nonce it
20234    /// minted for the candidate admits a second process, into the candidate
20235    /// slot, and that check runs ahead of the reserved-module gate.
20236    mod swap_admission {
20237        use super::*;
20238
20239        const INCUMBENT_NONCE: &str = "incumbent-nonce";
20240        const CANDIDATE_NONCE: &str = "candidate-nonce";
20241
20242        fn handler_with_incumbent(
20243            module_id: &str,
20244            reserved: bool,
20245        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
20246            let registry = Arc::new(Registry::default());
20247            let supervisor = SupervisorHandle::new();
20248            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
20249            if reserved {
20250                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
20251            }
20252            let handler =
20253                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
20254            let incumbent = handler
20255                .handle_control(
20256                    ConnectionId::new(1),
20257                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
20258                )
20259                .unwrap();
20260            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
20261            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
20262            (registry, supervisor, handler)
20263        }
20264
20265        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
20266        /// admits every nonce, so while a swap is open the swap gate is the only
20267        /// thing between a key-holder and the candidate slot. A nonce the
20268        /// supervisor did not mint, or none at all, is refused, and neither the
20269        /// incumbent's registration nor the candidate slot moves.
20270        #[test]
20271        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
20272            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
20273
20274            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
20275                let replies = handler
20276                    .handle_control(
20277                        ConnectionId::new(connection),
20278                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
20279                    )
20280                    .unwrap();
20281                assert_eq!(replies[0].header.ty, FrameType::Error);
20282                assert_eq!(
20283                    parse_error(&replies[0])["code"],
20284                    "swap_token_invalid",
20285                    "nonce {nonce:?}"
20286                );
20287            }
20288            assert!(registry.get_candidate("aft").unwrap().is_none());
20289            assert_eq!(
20290                registry.get_module("aft").unwrap().unwrap().connection_id,
20291                ConnectionId::new(1)
20292            );
20293
20294            // Control: the minted token is admitted, into the candidate slot,
20295            // and only once.
20296            let admitted = handler
20297                .handle_control(
20298                    ConnectionId::new(4),
20299                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20300                )
20301                .unwrap();
20302            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20303            assert_eq!(
20304                registry
20305                    .get_candidate("aft")
20306                    .unwrap()
20307                    .unwrap()
20308                    .connection_id,
20309                ConnectionId::new(4)
20310            );
20311            assert_eq!(
20312                registry.get_module("aft").unwrap().unwrap().connection_id,
20313                ConnectionId::new(1),
20314                "the candidate must not take the active slot"
20315            );
20316            let replayed = handler
20317                .handle_control(
20318                    ConnectionId::new(5),
20319                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20320                )
20321                .unwrap();
20322            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20323
20324            // The case only this gate covers: the incumbent has died mid-swap,
20325            // so its duplicate refusal is gone too, and without the gate a
20326            // key-holder would take the id's ACTIVE slot.
20327            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20328            let squatter = handler
20329                .handle_control(
20330                    ConnectionId::new(6),
20331                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20332                )
20333                .unwrap();
20334            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20335            assert!(
20336                registry.get_module("aft").unwrap().is_none(),
20337                "a squatter took the active slot of an id being swapped"
20338            );
20339        }
20340
20341        /// Design mutation arm (iii). A reserved module's candidate presents a
20342        /// nonce the reserved gate has never seen (that gate holds the
20343        /// incumbent's), so the swap gate must run first or the candidate is
20344        /// refused `reserved_module` and a reserved module can never be swapped.
20345        #[test]
20346        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20347            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20348
20349            let replies = handler
20350                .handle_control(
20351                    ConnectionId::new(2),
20352                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20353                )
20354                .unwrap();
20355
20356            assert_eq!(
20357                replies[0].header.ty,
20358                FrameType::HelloAck,
20359                "reserved candidate refused: {:?}",
20360                serde_json::from_slice::<Value>(&replies[0].body).ok()
20361            );
20362            assert_eq!(
20363                registry
20364                    .get_candidate("vault")
20365                    .unwrap()
20366                    .unwrap()
20367                    .connection_id,
20368                ConnectionId::new(2)
20369            );
20370        }
20371
20372        /// With no swap open the gate is inert: the incumbent's reserved gate
20373        /// and duplicate refusal behave exactly as before.
20374        #[test]
20375        fn without_an_open_swap_the_ordinary_gates_decide() {
20376            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20377            supervisor.close_swap("vault");
20378
20379            let candidate = handler
20380                .handle_control(
20381                    ConnectionId::new(2),
20382                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20383                )
20384                .unwrap();
20385            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20386            let duplicate = handler
20387                .handle_control(
20388                    ConnectionId::new(3),
20389                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20390                )
20391                .unwrap();
20392            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20393            assert!(registry.get_candidate("vault").unwrap().is_none());
20394        }
20395    }
20396
20397    /// `scope.sync` and `scope.describe` through the real control handler: who
20398    /// may sync is decided by the registration and launch nonce of the module
20399    /// connection, never by the request body.
20400    mod scopes {
20401        mod close_reasons {
20402            include!("route_close_reason_tests.rs");
20403        }
20404        mod idle_tests {
20405            use super::*;
20406            include!("scope_idle_tests.rs");
20407        }
20408        mod route_open_timings {
20409            use super::*;
20410            include!("route_open_timing_tests.rs");
20411        }
20412        mod route_open_refusal_log {
20413            use super::*;
20414            include!("route_open_refusal_log_tests.rs");
20415        }
20416        mod activity {
20417            include!("activity_scope_tests.rs");
20418        }
20419        mod delta {
20420            include!("scope_handler_delta_tests.rs");
20421        }
20422        mod watch {
20423            include!("scope_watch_tests.rs");
20424        }
20425        mod call_modes {
20426            include!("scope_call_mode_tests.rs");
20427        }
20428        mod federated {
20429            include!("scope_federated_tests.rs");
20430        }
20431        mod authorize {
20432            include!("route_authorize_tests.rs");
20433        }
20434        #[tokio::test]
20435        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20436            let rig = rig().await;
20437            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20438                "s".into(),
20439                1,
20440                "tool".into(),
20441            ))
20442            .unwrap();
20443            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20444            let (direct, _rx) = wide_ctx(999);
20445            for (ctx, expected) in [
20446                (&rig.owner, FrameType::Response),
20447                (&direct, FrameType::Error),
20448            ] {
20449                let frame =
20450                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20451                        .unwrap();
20452                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20453                assert_eq!(replies[0].header.ty, expected);
20454                if expected == FrameType::Response {
20455                    let reply: subc_control::ScopeServedByReply =
20456                        serde_json::from_slice(&replies[0].body).unwrap();
20457                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20458                } else {
20459                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20460                }
20461            }
20462            let reply = call(
20463                &rig.handler,
20464                &rig.owner,
20465                &ModuleControlRequestFromModule::ScopeDescribe {
20466                    owner: Principal::Reserved {
20467                        module_id: OWNER.into(),
20468                    },
20469                    scope_ref: "s".into(),
20470                },
20471            )
20472            .await;
20473            assert!(matches!(
20474                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20475                ModuleControlResponseToModule::ScopeDescribe { .. }
20476            ));
20477        }
20478
20479        use subc_protocol::scope::{
20480            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20481            ScopeStatus,
20482        };
20483
20484        use super::*;
20485
20486        const OWNER: &str = "prefrontal-core";
20487
20488        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20489            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20490        }
20491
20492        async fn call(
20493            handler: &ControlHandler,
20494            ctx: &RouteCtx,
20495            request: &ModuleControlRequestFromModule,
20496        ) -> Frame {
20497            let body = serde_json::to_vec(request).unwrap();
20498            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20499            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20500            assert_eq!(replies.len(), 1, "{replies:?}");
20501            replies.pop().unwrap()
20502        }
20503
20504        async fn sync(
20505            handler: &ControlHandler,
20506            ctx: &RouteCtx,
20507            generation: u64,
20508            scopes: Vec<ScopeRecord>,
20509        ) -> Result<ModuleControlResponseToModule, String> {
20510            let reply = call(
20511                handler,
20512                ctx,
20513                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20514            )
20515            .await;
20516            match reply.header.ty {
20517                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20518                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20519            }
20520        }
20521
20522        async fn describe(
20523            handler: &ControlHandler,
20524            ctx: &RouteCtx,
20525            owner: &str,
20526            scope_ref: &str,
20527        ) -> ModuleControlResponseToModule {
20528            let reply = call(
20529                handler,
20530                ctx,
20531                &ModuleControlRequestFromModule::ScopeDescribe {
20532                    owner: Principal::Reserved {
20533                        module_id: owner.to_string(),
20534                    },
20535                    scope_ref: scope_ref.to_string(),
20536                },
20537            )
20538            .await;
20539            assert_eq!(
20540                reply.header.ty,
20541                FrameType::Response,
20542                "{:?}",
20543                parse_error(&reply)
20544            );
20545            serde_json::from_slice(&reply.body).unwrap()
20546        }
20547
20548        #[tokio::test]
20549        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20550            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20551            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20552            let mut rig = rig().await;
20553            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20554                .await;
20555            let _bound = rig
20556                .bound(
20557                    Some(AFT),
20558                    PLEXUS,
20559                    Some(
20560                        rig.selector("s", Some(1))
20561                            .with_bind_proof(Some(PROOF.into())),
20562                    ),
20563                )
20564                .await;
20565            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20566            let output = serde_json::to_string(&reply).unwrap();
20567            assert!(output.contains("\"status\":\"live\""));
20568            assert!(!output.contains(PROOF));
20569            assert!(!output.contains(HASH));
20570        }
20571
20572        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20573        async fn module(
20574            handler: &ControlHandler,
20575            connection: u64,
20576            module_id: &str,
20577            nonce: Option<&str>,
20578        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20579            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20580            hello_via_sink(
20581                handler,
20582                &ctx,
20583                &mut rx,
20584                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20585            )
20586            .await;
20587            (ctx, rx)
20588        }
20589
20590        /// `direct` and every other client connection has no registration, so
20591        /// it can neither sync nor own a scope.
20592        #[tokio::test]
20593        async fn a_client_connection_cannot_sync_or_describe() {
20594            let handler = ControlHandler::new(Arc::new(Registry::default()));
20595            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20596            for request in [
20597                ModuleControlRequestFromModule::ScopeSync {
20598                    generation: 1,
20599                    scopes: vec![head("s", 1)],
20600                },
20601                ModuleControlRequestFromModule::ScopeDescribe {
20602                    owner: Principal::Direct,
20603                    scope_ref: "s".to_string(),
20604                },
20605            ] {
20606                let reply = call(&handler, &ctx, &request).await;
20607                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20608            }
20609            assert!(
20610                !handler
20611                    .scopes
20612                    .read()
20613                    .unwrap()
20614                    .describe(
20615                        &Principal::Reserved {
20616                            module_id: OWNER.to_string()
20617                        },
20618                        "s"
20619                    )
20620                    .owner_synced
20621            );
20622        }
20623
20624        /// A module the supervisor did not spawn registers without a launch
20625        /// nonce, so it is never an owner's current launch.
20626        #[tokio::test]
20627        async fn a_module_without_a_supervised_launch_cannot_sync() {
20628            let handler = ControlHandler::new(Arc::new(Registry::default()));
20629            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20630            assert_eq!(
20631                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20632                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20633            );
20634        }
20635
20636        #[tokio::test]
20637        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20638            let supervisor = SupervisorHandle::new();
20639            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20640            let handler = ControlHandler::new(Arc::new(Registry::default()))
20641                .with_supervisor(supervisor.clone());
20642            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20643            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20644                .await
20645                .expect("the current launch syncs");
20646
20647            // A swap candidate registers with the swap token and is refused
20648            // while the incumbent keeps syncing.
20649            supervisor.open_swap(OWNER, "n2".to_string());
20650            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20651            assert_eq!(
20652                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20653                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20654            );
20655            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20656                .await
20657                .expect("the serving owner syncs during the swap");
20658
20659            // The swap fails and is rolled back. The candidate never held sync
20660            // authority, and still cannot sync.
20661            supervisor.close_swap(OWNER);
20662            assert_eq!(
20663                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20664                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20665            );
20666            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20667                .await
20668                .expect("the serving owner syncs after the rollback");
20669            handler.cleanup_connection(candidate.connection_id).unwrap();
20670
20671            // A swap that cuts over. Promotion records the candidate's nonce as
20672            // the module's spawn nonce, which is what `set_spawn_nonce` does
20673            // here; the promoted connection then takes authority at any
20674            // generation and the superseded incumbent is refused.
20675            supervisor.open_swap(OWNER, "n3".to_string());
20676            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20677            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20678            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20679                .await
20680                .expect("the promoted launch takes authority");
20681            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20682                panic!("unexpected reply {reply:?}");
20683            };
20684            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20685            assert_eq!(
20686                sync(&handler, &incumbent, 4, Vec::new()).await,
20687                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20688            );
20689        }
20690
20691        /// Authority dies with its connection: the cleanup path releases it,
20692        /// so the owner's next connection takes it at any generation.
20693        #[tokio::test]
20694        async fn closing_the_authority_connection_frees_sync_authority() {
20695            let supervisor = SupervisorHandle::new();
20696            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20697            let handler = ControlHandler::new(Arc::new(Registry::default()))
20698                .with_supervisor(supervisor.clone());
20699            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20700            sync(&handler, &first, 10, vec![head("s", 1)])
20701                .await
20702                .unwrap();
20703            handler.cleanup_connection(first.connection_id).unwrap();
20704
20705            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20706            sync(&handler, &second, 1, vec![head("s", 1)])
20707                .await
20708                .expect("the next connection takes the released authority");
20709        }
20710
20711        #[tokio::test]
20712        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20713            let supervisor = SupervisorHandle::new();
20714            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20715            let handler =
20716                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20717            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20718            sync(&handler, &first, 10, vec![head("s", 1)])
20719                .await
20720                .unwrap();
20721            handler
20722                .handle_control_frame(
20723                    &first,
20724                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20725                )
20726                .await
20727                .unwrap();
20728            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20729            sync(&handler, &second, 1, vec![head("s", 1)])
20730                .await
20731                .expect("GOODBYE releases authority even if the old socket remains open");
20732        }
20733
20734        #[tokio::test]
20735        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20736            let registry = Arc::new(Registry::default());
20737            let supervisor_handle = SupervisorHandle::new();
20738            let supervisor =
20739                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20740                    .with_handle(supervisor_handle.clone())
20741                    .with_daemon_incarnation("incarnation-7".to_string());
20742            // Configured with enabled: false, so the supervisor lists the
20743            // module without spawning a process for it.
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            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20762            let handler =
20763                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20764            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20765
20766            // Configured but not yet synced: a reader waits for the owner.
20767            let ModuleControlResponseToModule::ScopeDescribe {
20768                status,
20769                daemon_incarnation,
20770                owner_synced,
20771                owner_configured,
20772                scope,
20773                ..
20774            } = describe(&handler, &reader, OWNER, "s").await
20775            else {
20776                panic!("not a describe reply");
20777            };
20778            assert_eq!(status, ScopeStatus::NotLive);
20779            assert_eq!(daemon_incarnation, "incarnation-7");
20780            assert!(!owner_synced);
20781            assert!(owner_configured);
20782            assert!(scope.is_none());
20783
20784            // Not a supervised module: the owner will never sync, and a reader
20785            // refuses rather than waits.
20786            let ModuleControlResponseToModule::ScopeDescribe {
20787                status,
20788                owner_configured,
20789                ..
20790            } = describe(&handler, &reader, "ghost", "s").await
20791            else {
20792                panic!("not a describe reply");
20793            };
20794            assert_eq!(status, ScopeStatus::NotLive);
20795            assert!(!owner_configured);
20796
20797            // Live, with the stamp fields and the computed owner_authorized.
20798            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20799            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20800            let ModuleControlResponseToModule::ScopeDescribe {
20801                status,
20802                scope_epoch,
20803                owner_synced,
20804                scope,
20805                ..
20806            } = describe(&handler, &reader, OWNER, "s").await
20807            else {
20808                panic!("not a describe reply");
20809            };
20810            assert_eq!(status, ScopeStatus::Live);
20811            assert_eq!(scope_epoch, Some(4));
20812            assert!(owner_synced);
20813            let stamp = scope.expect("a live scope carries its stamp");
20814            assert!(
20815                stamp.owner_authorized,
20816                "prefrontal-core is the default authority"
20817            );
20818            assert_eq!(stamp.kind, ScopeKind::Head);
20819        }
20820
20821        #[tokio::test]
20822        async fn scope_authority_owners_decides_owner_authorized() {
20823            let supervisor = SupervisorHandle::new();
20824            supervisor.set_spawn_nonce("broca", "b1".to_string());
20825            let handler = ControlHandler::new(Arc::new(Registry::default()))
20826                .with_supervisor(supervisor)
20827                .with_scope_authority_owners(vec!["broca".to_string()]);
20828            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20829            let mut gated = head("s", 1);
20830            gated.attributes.agent_id = Some("agent".to_string());
20831            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20832            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20833                describe(&handler, &broca, "broca", "s").await
20834            else {
20835                panic!("not a describe reply");
20836            };
20837            assert!(scope.unwrap().owner_authorized);
20838        }
20839
20840        /// With route admission, the stamp, the commit re-check and drains in
20841        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20842        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20843        #[tokio::test]
20844        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20845            let handler = ControlHandler::new(Arc::new(Registry::default()));
20846            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20847            let ack = hello_via_sink(
20848                &handler,
20849                &ctx,
20850                &mut rx,
20851                hello_frame("m", PROTOCOL_VERSION, 1),
20852            )
20853            .await;
20854            let ack = parse_ack(&ack);
20855            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20856                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20857            }
20858            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20859
20860            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20861            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20862            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20863            let reply = handler
20864                .handle_control_frame(&client, frame)
20865                .await
20866                .unwrap()
20867                .pop()
20868                .unwrap();
20869            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20870                serde_json::from_slice(&reply.body).unwrap()
20871            else {
20872                panic!("not a server.describe reply");
20873            };
20874            assert!(
20875                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20876                "{capabilities:?}"
20877            );
20878        }
20879
20880        // ---- route admission, stamps, commit re-check and drains ----------
20881
20882        const PLEXUS: &str = "plexus";
20883        const OTHER: &str = "other";
20884        const AFT: &str = "aft";
20885        const BROCA: &str = "broca";
20886        const MAGIC: &str = "magic-context";
20887
20888        fn nonce(module_id: &str) -> String {
20889            format!("nonce-{module_id}")
20890        }
20891
20892        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20893            let (tx, rx) = mpsc::channel(64);
20894            (
20895                RouteCtx {
20896                    connection_id: ConnectionId::new(connection),
20897                    egress: FrameSink::new(tx),
20898                },
20899                rx,
20900            )
20901        }
20902
20903        /// A daemon with a configured owner (prefrontal-core) registered on its
20904        /// own module connection, two routable targets (plexus, other), and
20905        /// launch nonces minted for the modules that open routes as carriers.
20906        struct Rig {
20907            handler: ControlHandler,
20908            forwarding: Arc<ForwardingTable>,
20909            owner: RouteCtx,
20910            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20911            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20912            generation: u64,
20913            next_connection: u64,
20914            _supervisor: Supervisor,
20915        }
20916
20917        async fn rig() -> Rig {
20918            rig_with_flow_support(true).await
20919        }
20920
20921        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20922            rig_with_scope_capabilities(flow_support, false).await
20923        }
20924
20925        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20926            let mut provides = Vec::new();
20927            if flow_support {
20928                provides.push("flow-scopes/v1");
20929            }
20930            if run_support {
20931                provides.push("agent-run-scopes/v1");
20932            }
20933            rig_with_target_capabilities(&provides).await
20934        }
20935
20936        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20937            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20938            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20939            // Decoder versions alone cannot admit scoped calls: only a capability
20940            // declaration promises the required run or flow behaviour.
20941            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20942            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20943            Frame::build(
20944                FrameType::Hello,
20945                control_flags(),
20946                0,
20947                0,
20948                connection,
20949                serde_json::to_vec(&body).unwrap(),
20950            )
20951            .unwrap()
20952        }
20953
20954        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20955            let registry = Arc::new(Registry::default());
20956            let forwarding = Arc::new(ForwardingTable::default());
20957            let supervisor_handle = SupervisorHandle::new();
20958            let supervisor =
20959                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20960                    .with_handle(supervisor_handle.clone());
20961            supervisor
20962                .supervise_configured(
20963                    ModuleSpec {
20964                        script: None,
20965                        carry_containment: false,
20966                        module_id: OWNER.to_string(),
20967                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20968                        args: Vec::new(),
20969                        env: Vec::new(),
20970                        reserved: false,
20971                        reserved_prefixes: Vec::new(),
20972                        protocol: ModuleProtocol::Subc,
20973                        overlap: Default::default(),
20974                    },
20975                    false,
20976                )
20977                .unwrap();
20978            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20979                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20980            }
20981            let handler =
20982                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20983                    .with_supervisor(supervisor_handle);
20984            let (owner, mut owner_rx) = wide_ctx(1);
20985            hello_via_sink(
20986                &handler,
20987                &owner,
20988                &mut owner_rx,
20989                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20990            )
20991            .await;
20992            let mut modules = BTreeMap::new();
20993            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20994                let (ctx, mut rx) = wide_ctx(connection);
20995                let hello = hello_with_capabilities(module_id, connection, provides);
20996                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20997                modules.insert(module_id.to_string(), (ctx, rx));
20998            }
20999            Rig {
21000                handler,
21001                forwarding,
21002                owner,
21003                _owner_rx: owner_rx,
21004                modules,
21005                generation: 0,
21006                next_connection: 100,
21007                _supervisor: supervisor,
21008            }
21009        }
21010
21011        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
21012            ScopeCarrier::new(Principal::Reserved {
21013                module_id: module_id.to_string(),
21014            })
21015            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
21016        }
21017
21018        /// The scope most tests open under: aft carries to any module, broca
21019        /// only to plexus and other, and the owner delegates as agent-1.
21020        fn session(scope_epoch: u64) -> ScopeRecord {
21021            let mut record = head("s", scope_epoch);
21022            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
21023            record.attributes.agent_id = Some("agent-1".to_string());
21024            record.attributes.delegates = true;
21025            record
21026        }
21027
21028        impl Rig {
21029            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
21030                self.generation += 1;
21031                sync(&self.handler, &self.owner, self.generation, scopes)
21032                    .await
21033                    .expect("the owner's sync is accepted");
21034            }
21035
21036            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21037                ScopeSelector::new(
21038                    Principal::Reserved {
21039                        module_id: OWNER.to_string(),
21040                    },
21041                    scope_ref.to_string(),
21042                    scope_epoch,
21043                )
21044            }
21045
21046            fn open_frame(
21047                &mut self,
21048                opener: Option<&str>,
21049                target: &str,
21050                scope: Option<ScopeSelector>,
21051            ) -> (
21052                RouteCtx,
21053                mpsc::Receiver<crate::router::OutboundFrame>,
21054                Frame,
21055            ) {
21056                self.next_connection += 1;
21057                let (ctx, rx) = wide_ctx(self.next_connection);
21058                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
21059                    busy_refusals: None,
21060                    target: RouteTarget::ToolProvider {
21061                        module_id: target.to_string(),
21062                    },
21063                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
21064                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
21065                        module_id: module_id.to_string(),
21066                        launch_nonce: nonce(module_id),
21067                    }),
21068                    consumer_capabilities: None,
21069                    role_versions: None,
21070                    admission_facts: None,
21071                    scope,
21072                })
21073                .unwrap();
21074                let frame = Frame::build(
21075                    FrameType::Request,
21076                    control_flags(),
21077                    0,
21078                    0,
21079                    self.next_connection,
21080                    body,
21081                )
21082                .unwrap();
21083                (ctx, rx, frame)
21084            }
21085
21086            /// Open and expect a refusal before anything is relayed.
21087            async fn refused(
21088                &mut self,
21089                opener: Option<&str>,
21090                target: &str,
21091                scope: Option<ScopeSelector>,
21092            ) -> String {
21093                self.refusal_body(opener, target, scope).await["code"]
21094                    .as_str()
21095                    .unwrap()
21096                    .to_string()
21097            }
21098
21099            async fn refusal_body(
21100                &mut self,
21101                opener: Option<&str>,
21102                target: &str,
21103                scope: Option<ScopeSelector>,
21104            ) -> Value {
21105                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
21106                let replies = tokio::time::timeout(
21107                    Duration::from_secs(2),
21108                    self.handler.handle_control_frame(&ctx, frame),
21109                )
21110                .await
21111                .expect("the open must be refused before waiting for a bind ack")
21112                .unwrap();
21113                assert_eq!(replies.len(), 1, "{replies:?}");
21114                assert_eq!(replies[0].header.ty, FrameType::Error);
21115                let (_, module_rx) = self.modules.get_mut(target).unwrap();
21116                assert!(
21117                    module_rx.try_recv().is_err(),
21118                    "a refused open relays nothing"
21119                );
21120                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
21121                parse_error(&replies[0])
21122            }
21123
21124            /// Start an open and return its task and the bind the target got.
21125            async fn relayed(
21126                &mut self,
21127                opener: Option<&str>,
21128                target: &str,
21129                scope: Option<ScopeSelector>,
21130            ) -> Relayed {
21131                self.relayed_with_legacy_root(opener, target, scope, None)
21132                    .await
21133            }
21134
21135            async fn relayed_with_legacy_root(
21136                &mut self,
21137                opener: Option<&str>,
21138                target: &str,
21139                scope: Option<ScopeSelector>,
21140                legacy_root: Option<&std::path::Path>,
21141            ) -> Relayed {
21142                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
21143                if let Some(root) = legacy_root {
21144                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
21145                    body["identity"]["project_root"] = serde_json::json!(root);
21146                    frame.body = serde_json::to_vec(&body).unwrap();
21147                }
21148                let handler = self.handler.clone();
21149                let task_ctx = ctx.clone();
21150                let task = tokio::spawn(async move {
21151                    handler
21152                        .handle_control_frame(&task_ctx, frame)
21153                        .await
21154                        .unwrap()
21155                });
21156                let (_, module_rx) = self.modules.get_mut(target).unwrap();
21157                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
21158                    .await
21159                    .expect("the target receives the relayed route.bind")
21160                    .unwrap()
21161                    .frame;
21162                Relayed {
21163                    target: target.to_string(),
21164                    client: ctx,
21165                    client_rx: rx,
21166                    task,
21167                    bind,
21168                }
21169            }
21170
21171            async fn ack(&self, relayed: &Relayed) {
21172                let (module, _) = &self.modules[&relayed.target];
21173                self.handler
21174                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
21175                    .await
21176                    .unwrap();
21177            }
21178
21179            /// Open, ack and return the bound route.
21180            async fn bound(
21181                &mut self,
21182                opener: Option<&str>,
21183                target: &str,
21184                scope: Option<ScopeSelector>,
21185            ) -> Bound {
21186                let relayed = self.relayed(opener, target, scope).await;
21187                self.commit_relayed(relayed).await
21188            }
21189
21190            async fn bound_with_legacy_root(
21191                &mut self,
21192                opener: Option<&str>,
21193                target: &str,
21194                scope: Option<ScopeSelector>,
21195                root: &std::path::Path,
21196            ) -> Bound {
21197                let relayed = self
21198                    .relayed_with_legacy_root(opener, target, scope, Some(root))
21199                    .await;
21200                self.commit_relayed(relayed).await
21201            }
21202
21203            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
21204                self.ack(&relayed).await;
21205                let Relayed {
21206                    target,
21207                    client,
21208                    mut client_rx,
21209                    task,
21210                    bind,
21211                } = relayed;
21212                assert!(
21213                    task.await.unwrap().is_empty(),
21214                    "the open is answered by commit"
21215                );
21216                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
21217                Bound {
21218                    target,
21219                    client,
21220                    client_rx,
21221                    channel,
21222                    epoch,
21223                    bind,
21224                }
21225            }
21226
21227            fn live(&self, route: &Bound) -> bool {
21228                matches!(
21229                    self.forwarding
21230                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21231                        .unwrap(),
21232                    DataRoute::Client(DataRouteState::Bound(_))
21233                )
21234            }
21235        }
21236
21237        struct Relayed {
21238            target: String,
21239            client: RouteCtx,
21240            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21241            task: tokio::task::JoinHandle<Vec<Frame>>,
21242            bind: Frame,
21243        }
21244
21245        struct Bound {
21246            target: String,
21247            client: RouteCtx,
21248            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21249            channel: u16,
21250            epoch: u32,
21251            bind: Frame,
21252        }
21253
21254        impl Bound {
21255            /// The reason of the `route.closed` this client was sent, after
21256            /// checking it also got a GOODBYE on exactly this route.
21257            fn closed_reason(&mut self) -> RouteCloseReason {
21258                let mut reason = None;
21259                let mut goodbye = false;
21260                while let Ok(outbound) = self.client_rx.try_recv() {
21261                    let frame = outbound.frame;
21262                    match frame.header.ty {
21263                        FrameType::Goodbye => {
21264                            assert_eq!(
21265                                (frame.header.channel, frame.header.epoch),
21266                                (self.channel, self.epoch)
21267                            );
21268                            goodbye = true;
21269                        }
21270                        FrameType::Push => {
21271                            let ClientControlPush::RouteClosed {
21272                                reason: r,
21273                                module_id,
21274                                ..
21275                            } = serde_json::from_slice(&frame.body).unwrap()
21276                            else {
21277                                panic!("unexpected push");
21278                            };
21279                            assert_eq!(module_id, self.target);
21280                            reason = Some(r);
21281                        }
21282                        other => panic!("unexpected frame {other:?}"),
21283                    }
21284                }
21285                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21286                reason.expect("the client is told why the route closed")
21287            }
21288
21289            fn untouched(&mut self) -> bool {
21290                self.client_rx.try_recv().is_err()
21291            }
21292
21293            fn stamp(&self) -> Option<ScopeStamp> {
21294                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21295                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21296                    other => panic!("expected a route.bind, got {other:?}"),
21297                }
21298            }
21299        }
21300
21301        #[tokio::test]
21302        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21303        ) {
21304            let mut rig = rig().await;
21305            let mut record = session(1);
21306            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21307            record.child_owners = vec![Principal::Reserved {
21308                module_id: MAGIC.to_string(),
21309            }];
21310            rig.sync(vec![record]).await;
21311            let scope = || Some(rig_selector("s", Some(1)));
21312
21313            // Admitted: the owner, a bare carrier to any module, a targeted
21314            // carrier to its listed module.
21315            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21316            rig.bound(Some(AFT), OTHER, scope()).await;
21317            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21318
21319            // Refused scope_not_carrier: a targeted carrier to an unlisted
21320            // module, a module that is not listed at all (a child owner is not
21321            // a carrier), and a direct key-holder.
21322            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21323                assert_eq!(
21324                    rig.refused(opener, target, scope()).await,
21325                    error_codes::SCOPE_NOT_CARRIER,
21326                    "{opener:?} -> {target}"
21327                );
21328            }
21329        }
21330
21331        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21332            ScopeSelector::new(
21333                Principal::Reserved {
21334                    module_id: OWNER.to_string(),
21335                },
21336                scope_ref.to_string(),
21337                scope_epoch,
21338            )
21339        }
21340
21341        #[tokio::test]
21342        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21343            let mut rig = rig().await;
21344            rig.sync(vec![session(1)]).await;
21345            for opener in [OWNER, AFT] {
21346                assert_eq!(
21347                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21348                        .await,
21349                    error_codes::SCOPE_EPOCH_REQUIRED,
21350                    "{opener}"
21351                );
21352            }
21353        }
21354
21355        #[tokio::test]
21356        async fn admission_separates_not_synced_not_live_and_ended() {
21357            let mut rig = rig().await;
21358            // Before the configured owner's first sync: retryable.
21359            let code = rig
21360                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21361                .await;
21362            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21363            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21364
21365            // An owner that is not configured will never sync: terminal.
21366            let ghost = ScopeSelector::new(
21367                Principal::Reserved {
21368                    module_id: "ghost".to_string(),
21369                },
21370                "s".to_string(),
21371                Some(1),
21372            );
21373            assert_eq!(
21374                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21375                error_codes::SCOPE_NOT_LIVE
21376            );
21377
21378            rig.sync(vec![session(2)]).await;
21379            assert_eq!(
21380                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21381                    .await,
21382                error_codes::SCOPE_NOT_LIVE
21383            );
21384            for epoch in [1, 3] {
21385                assert_eq!(
21386                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21387                        .await,
21388                    error_codes::SCOPE_ENDED,
21389                    "epoch {epoch}"
21390                );
21391            }
21392            // Control: the live epoch is admitted.
21393            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21394                .await;
21395        }
21396
21397        #[tokio::test]
21398        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21399            let mut rig = rig().await;
21400            rig.sync(vec![session(1)]).await;
21401            let route = rig
21402                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21403                .await;
21404            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21405            assert_eq!(stamp.scope_ref, "s");
21406            assert_eq!(stamp.scope_epoch, 1);
21407            assert_eq!(stamp.kind, ScopeKind::Head);
21408            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21409            assert!(stamp.attributes.delegates);
21410            assert!(stamp.owner_authorized);
21411            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21412            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21413
21414            // broca owns a scope of its own on its own module connection; it is
21415            // not in scope_authority_owners, so its stamp is not authorized.
21416            let (broca, mut broca_rx) = wide_ctx(50);
21417            hello_via_sink(
21418                &rig.handler,
21419                &broca,
21420                &mut broca_rx,
21421                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21422            )
21423            .await;
21424            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21425                .await
21426                .unwrap();
21427            let own = ScopeSelector::new(
21428                Principal::Reserved {
21429                    module_id: BROCA.to_string(),
21430                },
21431                "b".to_string(),
21432                Some(1),
21433            );
21434            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21435            assert!(!route.stamp().unwrap().owner_authorized);
21436        }
21437
21438        #[tokio::test]
21439        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21440            let mut rig = rig().await;
21441            let mut record = head("s", 1);
21442            record.carriers = vec![carrier(AFT, None)];
21443            let flow_id = "Flow:run-7/step_2!~";
21444            record.attributes.flow_id = Some(flow_id.to_string());
21445            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21446                .await
21447                .unwrap();
21448            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21449                panic!("not a sync reply");
21450            };
21451            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21452            let route = rig
21453                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21454                .await;
21455            assert!(rig.live(&route), "the stamped bind committed");
21456            let stamp = route.stamp().expect("a flow scope carries a stamp");
21457            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21458            assert_eq!(stamp.attributes.agent_id, None);
21459            assert!(!stamp.attributes.delegates);
21460            assert!(stamp.owner_authorized);
21461            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21462            assert_eq!(unscoped.stamp(), None);
21463        }
21464
21465        #[tokio::test]
21466        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21467            let mut rig = rig_with_flow_support(false).await;
21468            let mut record = session(1);
21469            record.attributes.flow_id = Some("flow:7".to_string());
21470            rig.sync(vec![record]).await;
21471            for opener in [OWNER, AFT] {
21472                let body = rig
21473                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21474                    .await;
21475                assert_eq!(body["code"], "target_flow_unsupported");
21476                let message = body["message"].as_str().unwrap();
21477                for required in [PLEXUS, "flow-scopes/v1"] {
21478                    assert!(message.contains(required), "{message}");
21479                }
21480            }
21481        }
21482
21483        #[tokio::test]
21484        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21485            let mut rig = rig_with_flow_support(true).await;
21486            let mut record = session(1);
21487            record.attributes.flow_id = Some("flow:7".to_string());
21488            rig.sync(vec![record]).await;
21489            for opener in [OWNER, AFT] {
21490                let route = rig
21491                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21492                    .await;
21493                assert!(rig.live(&route));
21494                assert_eq!(
21495                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21496                    Some("flow:7")
21497                );
21498            }
21499        }
21500
21501        #[tokio::test]
21502        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21503            use std::future::Future;
21504
21505            let mut rig = rig_with_flow_support(true).await;
21506            let mut record = session(1);
21507            record.attributes.flow_id = Some("flow:7".to_string());
21508            rig.sync(vec![record]).await;
21509            let (client, mut client_rx, frame) =
21510                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21511            // Hold the route-open response permit so admission sees the first
21512            // target but relay reservation cannot capture an endpoint yet.
21513            for _ in 0..64 {
21514                client.egress.try_send(route_bind_ack(1)).unwrap();
21515            }
21516            let handler = rig.handler.clone();
21517            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21518            std::future::poll_fn(|cx| {
21519                assert!(open.as_mut().poll(cx).is_pending());
21520                std::task::Poll::Ready(())
21521            })
21522            .await;
21523            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21524
21525            let old_connection = rig.modules[PLEXUS].0.connection_id;
21526            rig.handler.cleanup_connection(old_connection).unwrap();
21527            let (replacement, mut replacement_rx) = wide_ctx(200);
21528            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21529            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21530            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21531            let hello = Frame::build(
21532                FrameType::Hello,
21533                control_flags(),
21534                0,
21535                0,
21536                200,
21537                serde_json::to_vec(&body).unwrap(),
21538            )
21539            .unwrap();
21540            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21541
21542            client_rx.try_recv().unwrap();
21543            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21544                .await
21545                .expect("the replacement is refused without waiting for a bind ack")
21546                .unwrap();
21547            assert_eq!(replies.len(), 1);
21548            let body = parse_error(&replies[0]);
21549            assert_eq!(body["code"], "target_flow_unsupported");
21550            for required in [PLEXUS, "flow-scopes/v1"] {
21551                assert!(body["message"].as_str().unwrap().contains(required));
21552            }
21553            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21554            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21555            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21556            assert!(rig
21557                .handler
21558                .registry
21559                .get_module_by_connection(replacement.connection_id)
21560                .unwrap()
21561                .is_some());
21562        }
21563
21564        #[tokio::test]
21565        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21566            use std::future::Future;
21567            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21568            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21569            const NEXT_HASH: &str =
21570                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21571            let mut rig = rig().await;
21572            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21573            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21574            rig.sync(vec![record.clone()]).await;
21575            let (client, mut rx, frame) = rig.open_frame(
21576                None,
21577                PLEXUS,
21578                Some(
21579                    rig.selector("s", Some(1))
21580                        .with_bind_proof(Some(PROOF.into())),
21581                ),
21582            );
21583            // Hold egress reservation while the scope owner changes its bind-proof
21584            // hash, so a proof valid at admission must be checked again at relay.
21585            for _ in 0..64 {
21586                client.egress.try_send(route_bind_ack(1)).unwrap();
21587            }
21588            let handler = rig.handler.clone();
21589            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21590            std::future::poll_fn(|cx| {
21591                assert!(open.as_mut().poll(cx).is_pending());
21592                std::task::Poll::Ready(())
21593            })
21594            .await;
21595            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21596            rig.sync(vec![record]).await;
21597            rx.try_recv().unwrap();
21598            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21599                .await
21600                .unwrap()
21601                .unwrap();
21602            assert_eq!(
21603                parse_error(&replies[0])["code"],
21604                error_codes::SCOPE_BIND_PROOF_MISMATCH
21605            );
21606            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21607            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21608            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21609        }
21610
21611        #[tokio::test]
21612        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21613            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21614            let mut rig = rig().await;
21615            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21616                .await;
21617            for opener in [OWNER, AFT] {
21618                for proof in [None, Some("malformed+proof=")] {
21619                    let route = rig
21620                        .bound(
21621                            Some(opener),
21622                            PLEXUS,
21623                            Some(
21624                                rig.selector("s", Some(1))
21625                                    .with_bind_proof(proof.map(str::to_string)),
21626                            ),
21627                        )
21628                        .await;
21629                    assert!(rig.live(&route));
21630                }
21631            }
21632        }
21633
21634        #[tokio::test]
21635        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21636            use std::future::Future;
21637            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21638            const NEXT_HASH: &str =
21639                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21640            let mut rig = rig().await;
21641            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21642                .await;
21643            let (client, mut rx, frame) =
21644                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21645            for _ in 0..64 {
21646                client.egress.try_send(route_bind_ack(1)).unwrap();
21647            }
21648            let handler = rig.handler.clone();
21649            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21650            std::future::poll_fn(|cx| {
21651                assert!(open.as_mut().poll(cx).is_pending());
21652                std::task::Poll::Ready(())
21653            })
21654            .await;
21655            rig.sync(vec![
21656                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21657            ])
21658            .await;
21659            rx.try_recv().unwrap();
21660            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21661            let bind = std::future::poll_fn(|cx| {
21662                assert!(open.as_mut().poll(cx).is_pending());
21663                module_rx.poll_recv(cx)
21664            })
21665            .await
21666            .unwrap()
21667            .frame;
21668            handler
21669                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21670                .await
21671                .unwrap();
21672            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21673                .await
21674                .unwrap()
21675                .unwrap();
21676            assert_eq!(replies.len(), 1);
21677            // Proof rechecking allowed the relay. Independent tag settlement
21678            // still asks the opener to retry after any same-epoch content change.
21679            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21680            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21681            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21682            let route = rig
21683                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21684                .await;
21685            assert!(rig.live(&route));
21686        }
21687
21688        #[tokio::test]
21689        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21690        {
21691            let mut rig = rig_with_flow_support(false).await;
21692            rig.sync(vec![session(1)]).await;
21693            let route = rig
21694                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21695                .await;
21696            assert!(rig.live(&route));
21697            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21698            let mut record = session(1);
21699            record.attributes.flow_id = Some("flow:7".to_string());
21700            rig.sync(vec![record]).await;
21701            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21702            assert!(rig.live(&unscoped));
21703            assert_eq!(unscoped.stamp(), None);
21704        }
21705
21706        #[tokio::test]
21707        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21708            let mut rig = rig().await;
21709            let mut record = session(1);
21710            record.attributes.flow_id = Some("flow:7".to_string());
21711            rig.sync(vec![record.clone()]).await;
21712            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21713            let mut owner_route = rig
21714                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21715                .await;
21716            let mut carrier_route = rig
21717                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21718                .await;
21719            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21720            rig.sync(vec![record.clone()]).await;
21721            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21722            assert!(rig.live(&owner_route) && owner_route.untouched());
21723            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21724
21725            record.attributes.flow_id = Some("flow:8".to_string());
21726            rig.sync(vec![record]).await;
21727            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21728            let before = before.unwrap();
21729            assert_eq!(after.scope_epoch, before.scope_epoch);
21730            assert!(after.version > before.version);
21731            for route in [&mut owner_route, &mut carrier_route] {
21732                assert!(!rig.live(route));
21733                assert_eq!(
21734                    route.closed_reason(),
21735                    RouteCloseReason::ScopeDelegationChanged
21736                );
21737            }
21738            assert!(rig.live(&unscoped) && unscoped.untouched());
21739            // Each provider also receives a GOODBYE for its drained route;
21740            // consume it before expecting the next route.bind on that sink.
21741            for target in [PLEXUS, OTHER] {
21742                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21743                let goodbye = module_rx
21744                    .try_recv()
21745                    .expect("the provider sees the drain")
21746                    .frame;
21747                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21748                assert!(module_rx.try_recv().is_err());
21749            }
21750            let rebound = rig
21751                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21752                .await;
21753            assert_eq!(
21754                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21755                Some("flow:8")
21756            );
21757        }
21758
21759        /// The owner's sync lands between admission and the module's ack. The
21760        /// open is refused by name, the module's other routes stay up, and the
21761        /// reserved pair is released. Changed content is retryable; an ended
21762        /// scope is not.
21763        #[tokio::test]
21764        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21765            let mut rig = rig().await;
21766            rig.sync(vec![session(1)]).await;
21767            let mut cotenant = rig
21768                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21769                .await;
21770
21771            let mut changed = session(1);
21772            changed.child_owners.push(Principal::Reserved {
21773                module_id: MAGIC.to_string(),
21774            });
21775            let mut ended = None;
21776            for (code, next) in [
21777                (error_codes::SCOPE_CHANGED, vec![changed]),
21778                (error_codes::SCOPE_ENDED, Vec::new()),
21779            ] {
21780                let relayed = rig
21781                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21782                    .await;
21783                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21784                ended = Some(next.is_empty());
21785                rig.sync(next).await;
21786                rig.ack(&relayed).await;
21787                let replies = relayed.task.await.unwrap();
21788                assert_eq!(replies.len(), 1, "{replies:?}");
21789                assert_eq!(parse_error(&replies[0])["code"], code);
21790                assert_eq!(
21791                    subc_protocol::error_codes::is_retryable_route_open(code),
21792                    code == error_codes::SCOPE_CHANGED
21793                );
21794                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21795                // The module is told to drop just the binding it created.
21796                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21797                // Collected, because ending the scope also closes the co-tenant
21798                // route, whose GOODBYE comes first.
21799                let mut goodbyes = Vec::new();
21800                while let Ok(outbound) = plexus_rx.try_recv() {
21801                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21802                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21803                }
21804                assert!(
21805                    goodbyes.contains(&(bind_channel, bind_epoch)),
21806                    "{goodbyes:?}"
21807                );
21808                assert!(rig
21809                    .handler
21810                    .registry
21811                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21812                    .unwrap()
21813                    .is_some());
21814            }
21815            assert_eq!(ended, Some(true));
21816            // The co-tenant stayed up through the change, and closed only when
21817            // the scope ended, by the drain rule rather than by the commit.
21818            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21819        }
21820
21821        /// Each row of the drain table on one set of routes: the owner's, a
21822        /// bare carrier's, and a targeted carrier's to each of its targets.
21823        #[tokio::test]
21824        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21825            struct Case {
21826                name: &'static str,
21827                change: fn(&mut ScopeRecord),
21828                /// Closed routes by index: owner->plexus, aft->plexus,
21829                /// broca->plexus, broca->other.
21830                closed: [Option<RouteCloseReason>; 4],
21831            }
21832            use RouteCloseReason::*;
21833            let cases = [
21834                Case {
21835                    name: "a carrier entry removed",
21836                    change: |r| {
21837                        r.carriers.retain(|c| {
21838                            c.principal
21839                                != Principal::Reserved {
21840                                    module_id: AFT.to_string(),
21841                                }
21842                        })
21843                    },
21844                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21845                },
21846                Case {
21847                    name: "a target removed from a carrier",
21848                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21849                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21850                },
21851                Case {
21852                    name: "a bare carrier narrowed to targets",
21853                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21854                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21855                },
21856                Case {
21857                    name: "delegates turned off",
21858                    change: |r| r.attributes.delegates = false,
21859                    closed: [Some(ScopeDelegationChanged); 4],
21860                },
21861                Case {
21862                    name: "agent_id changed",
21863                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21864                    closed: [Some(ScopeDelegationChanged); 4],
21865                },
21866                Case {
21867                    name: "a carrier added, child owners changed, the record re-sent",
21868                    change: |r| {
21869                        r.carriers.push(carrier(MAGIC, None));
21870                        r.child_owners.push(Principal::Reserved {
21871                            module_id: MAGIC.to_string(),
21872                        });
21873                    },
21874                    closed: [None; 4],
21875                },
21876                Case {
21877                    name: "a target added",
21878                    change: |r| {
21879                        r.carriers[1]
21880                            .targets
21881                            .as_mut()
21882                            .unwrap()
21883                            .push("third".to_string())
21884                    },
21885                    closed: [None; 4],
21886                },
21887                Case {
21888                    name: "delegates turned on",
21889                    change: |r| r.attributes.delegates = true,
21890                    closed: [None; 4],
21891                },
21892            ];
21893            for case in cases {
21894                let mut rig = rig().await;
21895                rig.sync(vec![session(1)]).await;
21896                let scope = || Some(rig_selector("s", Some(1)));
21897                let mut routes = [
21898                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21899                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21900                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21901                    rig.bound(Some(BROCA), OTHER, scope()).await,
21902                ];
21903                let mut record = session(1);
21904                (case.change)(&mut record);
21905                rig.sync(vec![record]).await;
21906                for (index, expected) in case.closed.iter().enumerate() {
21907                    let route = &mut routes[index];
21908                    match expected {
21909                        Some(reason) => {
21910                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21911                            assert_eq!(
21912                                route.closed_reason(),
21913                                *reason,
21914                                "{}: route {index}",
21915                                case.name
21916                            );
21917                        }
21918                        None => {
21919                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21920                            assert!(
21921                                route.untouched(),
21922                                "{}: route {index} was told something",
21923                                case.name
21924                            );
21925                        }
21926                    }
21927                }
21928            }
21929        }
21930
21931        #[tokio::test]
21932        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21933            // Removed, and replaced by a higher epoch.
21934            for next in [Vec::new(), vec![session(2)]] {
21935                let mut rig = rig().await;
21936                rig.sync(vec![session(1)]).await;
21937                let mut route = rig
21938                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21939                    .await;
21940                rig.sync(next).await;
21941                assert!(!rig.live(&route));
21942                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21943            }
21944
21945            // A child whose parent ends: its routes close as parent-ended, the
21946            // child stays live, and routes under the parent close as ended.
21947            let mut rig = rig().await;
21948            let mut child = session(1);
21949            child.scope_ref = "child".to_string();
21950            child.kind = ScopeKind::Worker;
21951            child.parent = Some(ScopeParent::new(
21952                Principal::Reserved {
21953                    module_id: OWNER.to_string(),
21954                },
21955                "s".to_string(),
21956                1,
21957            ));
21958            rig.sync(vec![session(1), child.clone()]).await;
21959            let mut child_route = rig
21960                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21961                .await;
21962            assert_eq!(
21963                child_route.stamp().unwrap().parent_state,
21964                Some(ParentState::Linked)
21965            );
21966            rig.sync(vec![child]).await;
21967            assert!(!rig.live(&child_route));
21968            assert_eq!(
21969                child_route.closed_reason(),
21970                RouteCloseReason::ScopeParentEnded
21971            );
21972        }
21973
21974        #[tokio::test]
21975        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21976        ) {
21977            let mut rig = rig().await;
21978            rig.sync(vec![session(1)]).await;
21979            let mut route = rig
21980                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21981                .await;
21982            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21983            rig.sync(vec![session(1)]).await;
21984            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21985            assert!(rig.live(&route) && route.untouched());
21986
21987            // A call in flight on the route when another carrier is added. A
21988            // forwarded REQUEST holds one credit on the route's flow until the
21989            // module answers; the router takes it exactly like this.
21990            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21991                .forwarding
21992                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21993                .unwrap()
21994            else {
21995                panic!("the route is bound");
21996            };
21997            binding.flow.acquire_tagged(9, false).await.unwrap();
21998            let mut widened = session(1);
21999            widened.carriers.push(carrier(MAGIC, None));
22000            rig.sync(vec![widened]).await;
22001            assert!(rig.live(&route) && route.untouched());
22002            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
22003            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
22004            // The call's credit is still held on an open flow, so its answer
22005            // will be delivered: closing the route would have closed the flow.
22006            assert_eq!(binding.flow.in_flight(), 1);
22007            binding
22008                .flow
22009                .acquire_tagged(10, false)
22010                .await
22011                .expect("the flow is still open");
22012        }
22013
22014        /// A swap's superseded endpoint keeps its routes until drained; ending
22015        /// the scope closes them there too.
22016        #[tokio::test]
22017        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
22018            let mut rig = rig().await;
22019            rig.sync(vec![session(1)]).await;
22020            let mut on_incumbent = rig
22021                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
22022                .await;
22023
22024            // Swap plexus: register a candidate and cut over, leaving the
22025            // incumbent superseded with the route still on it.
22026            let (candidate, _candidate_rx) = wide_ctx(9);
22027            let registration = rig
22028                .handler
22029                .registry
22030                .register_candidate_with_control_ops(
22031                    manifest(PLEXUS, PROTOCOL_VERSION),
22032                    PROTOCOL_VERSION,
22033                    candidate.connection_id,
22034                    module_baseline_control_ops(),
22035                )
22036                .unwrap();
22037            rig.forwarding
22038                .register_candidate_module_connection(
22039                    candidate.connection_id,
22040                    PLEXUS.to_string(),
22041                    PROTOCOL_VERSION,
22042                    manifest_concurrency(&registration.manifest),
22043                    candidate.egress.clone(),
22044                )
22045                .unwrap();
22046            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
22047            rig.handler
22048                .registry
22049                .promote_candidate(PLEXUS)
22050                .unwrap()
22051                .unwrap();
22052            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
22053
22054            rig.sync(Vec::new()).await;
22055            assert!(!rig.live(&on_incumbent));
22056            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
22057            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
22058            let goodbye = incumbent_rx
22059                .try_recv()
22060                .expect("the superseded endpoint is told")
22061                .frame;
22062            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
22063        }
22064    }
22065}
22066
22067#[cfg(test)]
22068mod concurrency_default_exposure_tests {
22069    use super::*;
22070
22071    fn hello_body(role_json: &str) -> Vec<u8> {
22072        format!(
22073            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":[]}}}}}}}}"#
22074        )
22075        .into_bytes()
22076    }
22077
22078    fn manifest_from(body: &[u8]) -> ModuleManifest {
22079        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
22080        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
22081            .expect("manifest parses")
22082    }
22083
22084    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
22085
22086    #[test]
22087    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
22088        let body = hello_body(&format!(
22089            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
22090        ));
22091        let manifest = manifest_from(&body);
22092        // Precondition: serde really resolved it to the default, so the typed
22093        // manifest alone cannot answer the question this probe exists for.
22094        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
22095        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
22096    }
22097
22098    #[test]
22099    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
22100        let body = hello_body(&format!(
22101            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
22102        ));
22103        let manifest = manifest_from(&body);
22104        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
22105        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
22106    }
22107
22108    #[test]
22109    fn non_management_roles_are_never_reported() {
22110        let body = hello_body(
22111            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
22112        );
22113        let manifest = manifest_from(&body);
22114        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
22115    }
22116}