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;
168#[path = "operator_apps/connection.rs"]
169mod peer_identity;
170use caller_attestation::{caller_for_target, scope_acts_for_another};
171#[cfg(all(test, unix, feature = "test-support"))]
172#[path = "control/caller_attestation_tests.rs"]
173mod caller_attestation_tests;
174mod scope_expiry;
175mod scope_watch;
176mod usage;
177
178mod agent_commands;
179pub(crate) mod catalog;
180mod rescan_checked;
181use rescan_checked::{RescanMode, RescanPlan};
182
183const MODULE_TO_SUBC_CONTROL_OPS: &[&str] = &[
184    "claim.mint",
185    "claim.present",
186    MODULE_TO_SUBC_OP_CATALOG_UPDATE,
187    MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
188    "supervisor.live_roots",
189    "supervisor.agent_commands",
190    SCOPE_SYNC_OP,
191    SCOPE_APPLY_OP,
192    SCOPE_DESCRIBE_OP,
193    ops::SCOPE_WATCH,
194    subc_protocol::scope::ROUTE_AUTHORIZE_OP,
195    "operator.confirm",
196];
197
198/// Module-originated ops the daemon answers but does not advertise in
199/// `HELLO_ACK`. Empty today; an op is served from here while the feature it
200/// belongs to is incomplete, so no module is told it works before it does.
201const MODULE_TO_SUBC_UNADVERTISED_OPS: &[&str] = &[];
202
203const MODULE_BASELINE_CONTROL_OPS: &[&str] = &["route.bind", "route.status"];
204
205/// How long subc waits for a module to ack a relayed route.bind before returning
206/// `module_timeout`. The ack waits on the module's own configure, which for AFT
207/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
208/// and DB-open work — on a cold page cache or a large repo that legitimately
209/// exceeds a couple of seconds. The default is generous because rejecting a VALID
210/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
211/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
212pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
213
214/// How many CONSECUTIVE full-budget relay timeouts against one target module
215/// open that module's bind-relay breaker.
216///
217/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
218/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
219/// so three consecutive full-budget timeouts take ~36s to observe: every client
220/// whose open contributed to opening the breaker had already given up on its
221/// own. That is what makes opening the breaker unable to turn a call that would
222/// have succeeded into a refusal — it can only make an already-failing module
223/// fail faster.
224///
225/// Two would be reachable inside one default deadline. One would convict a
226/// module on a single cold-cache bind, which is exactly the valid-but-slow case
227/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
228pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
229
230/// How long a module's bind-relay breaker stays open before exactly one
231/// `route.open` is let through as a probe.
232///
233/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
234/// re-pays a full-budget stall almost continuously, and the breaker stops being
235/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
236/// deadline: a client that starts retrying after the module recovers has to get
237/// a probe opportunity inside its own deadline, or the breaker converts a
238/// recovered module into a failed call — the failure it exists to prevent,
239/// pointed the other way.
240///
241/// 20s sits between those with room on both sides, and it caps what a wedged
242/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
243/// rather than one per `route.open` per connection. The stall that motivated
244/// this, with its measurements, is written up in
245/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
246/// waited the whole budget out.
247pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
248
249const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
250const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
251
252fn reload_verdict(
253    configured: &Path,
254    spawned_from: Option<&Path>,
255    image: subc_control::RunningImageAgreement,
256) -> PendingReloadVerdict {
257    let path = match spawned_from {
258        Some(spawned_from) if reload_paths_match(configured, spawned_from) => {
259            ReloadPathAgreement::Match
260        }
261        Some(spawned_from) => ReloadPathAgreement::Mismatch {
262            configured: configured.to_path_buf(),
263            spawned_from: spawned_from.to_path_buf(),
264        },
265        None => ReloadPathAgreement::Unavailable {
266            reason: if matches!(
267                image,
268                subc_control::RunningImageAgreement::Unavailable {
269                    reason: subc_control::RunningImageUnavailableReason::NotRunning
270                }
271            ) {
272                ReloadPathUnavailableReason::NotRunning
273            } else {
274                ReloadPathUnavailableReason::SpawnedPathUnavailable
275            },
276        },
277    };
278    PendingReloadVerdict::new(path, image)
279}
280
281fn launch_spec_agreement(
282    configured: &crate::supervise::ModuleSpec,
283    running: bool,
284    spawned: Option<&crate::supervise::LaunchSpecDigest>,
285) -> subc_control::LaunchSpecAgreement {
286    use subc_control::{LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason};
287    if !running {
288        return Agreement::Unavailable {
289            reason: Reason::NotRunning,
290        };
291    }
292    match spawned {
293        None => Agreement::Unavailable {
294            reason: Reason::SpawnedSpecUnavailable,
295        },
296        Some(digest) if *digest == crate::supervise::LaunchSpecDigest::from_spec(configured) => {
297            Agreement::Match
298        }
299        Some(_) => Agreement::Mismatch,
300    }
301}
302
303fn reload_paths_match(configured: &Path, spawned_from: &Path) -> bool {
304    if configured == spawned_from {
305        return true;
306    }
307    #[cfg(windows)]
308    {
309        // Windows spawn records the resolved verbatim path (\\?\...), while
310        // configuration keeps its original spelling. Resolve both with the OS
311        // instead of stripping prefixes or folding case, which could conflate
312        // distinct names in case-sensitive directories. Different resolved
313        // paths still differ even if their files have identical content.
314        match (
315            std::fs::canonicalize(configured),
316            std::fs::canonicalize(spawned_from),
317        ) {
318            (Ok(configured), Ok(spawned_from)) => configured == spawned_from,
319            _ => false,
320        }
321    }
322    #[cfg(not(windows))]
323    {
324        false
325    }
326}
327
328#[derive(Clone)]
329struct DaemonProvenanceFacts {
330    build: DaemonBuildProvenance,
331    pid: Option<u32>,
332    started_at_ms: Option<u64>,
333    start_clock: Option<crate::clock::StartClock>,
334    executable_path: Option<PathBuf>,
335    executable_identity: Option<SpawnedFileIdentity>,
336    process_start_time: Option<u64>,
337    probe: ExecutableIdentityProbe,
338}
339
340impl Default for DaemonProvenanceFacts {
341    fn default() -> Self {
342        Self {
343            build: DaemonBuildProvenance {
344                build_git_sha: None,
345                build_lock_digest: None,
346            },
347            pid: None,
348            started_at_ms: None,
349            start_clock: None,
350            executable_path: None,
351            executable_identity: None,
352            process_start_time: None,
353            probe: ExecutableIdentityProbe::default(),
354        }
355    }
356}
357
358#[derive(Debug, Clone)]
359struct SupervisorRescanContext {
360    supervisor: Supervisor,
361    config_path: PathBuf,
362    configured_port: Option<u16>,
363    storage_config: Option<crate::daemon_config::StorageConfig>,
364    admission_facts_carrier_module_id: Option<String>,
365    admission_facts_targets: Option<Vec<String>>,
366    scope_authority_owners: Vec<String>,
367    federated_scope_owner: String,
368    privileged_operator_prompt: PrivilegedOperatorPrompt,
369    /// Counts executed rescans that set out to change the supervised modules'
370    /// staged or applied configuration, counted before the first change so a
371    /// rescan that fails partway still counts. With the daemon incarnation it
372    /// names the state a `supervisor.rescan_checked` preview was computed
373    /// against.
374    generation: Arc<std::sync::atomic::AtomicU64>,
375    rescan_lock: Arc<tokio::sync::Mutex<()>>,
376    module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
377}
378
379/// Refusal labels passed to `observe_route_open_refusal` that mean the target
380/// module is not serving right now, and so open or extend an outage in the
381/// route outage tracker. Every one of them is only reachable after the target
382/// was found in the registry, which is what keeps an arbitrary client-chosen
383/// id from ever creating tracker state.
384///
385/// Deliberately absent: `not_registered` and `removed` (the id may be
386/// anything a client sent, and a removed module is gone on purpose),
387/// `protocol_none` (such a module never serves routes, so nothing is out),
388/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
389/// capability and admission-facts refusals (they refuse the caller, not a
390/// module outage), and `relay_reservation_failed` (its code ranges over
391/// capacity limits as well as a vanished connection). Capacity, breaker,
392/// relay-timeout and module-rejection refusals do not pass through that
393/// function at all; the breaker logs its own transitions.
394///
395/// The two not-serving refusals that bypass that function record themselves
396/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
397/// `required_capability_unprovided` is not tracked: the module itself is up,
398/// and the outage belongs to the missing provider.
399const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
400    "reloading",
401    "supervisor_not_live",
402    "registration_not_active",
403    "no_forwarding_connection",
404    "relay_send_failed",
405];
406
407/// Observe test request cancellation relative to the connection's cleanup.
408#[cfg(test)]
409struct ActivityRequestPause {
410    connection: ConnectionId,
411    started: tokio::sync::Notify,
412    cancelled: tokio::sync::Notify,
413    cleanup_started: std::sync::atomic::AtomicBool,
414    cancelled_after_cleanup: std::sync::atomic::AtomicBool,
415}
416
417#[cfg(test)]
418struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
419
420#[cfg(test)]
421impl Drop for ActivityRequestCancellation {
422    fn drop(&mut self) {
423        self.0.cancelled_after_cleanup.store(
424            self.0
425                .cleanup_started
426                .load(std::sync::atomic::Ordering::Acquire),
427            std::sync::atomic::Ordering::Release,
428        );
429        self.0.cancelled.notify_one();
430    }
431}
432
433/// A test hold: signal arrival, then wait for release on the holding thread.
434#[cfg(test)]
435type TestPause = (
436    tokio::sync::oneshot::Sender<()>,
437    std::sync::mpsc::Receiver<()>,
438);
439
440/// A test hook run once at a fixed point in a handler.
441#[cfg(test)]
442type TestHook = Box<dyn FnOnce() + Send>;
443
444/// A test hold for async code: signal arrival, then await release.
445#[cfg(test)]
446type AsyncTestPause = (
447    tokio::sync::oneshot::Sender<()>,
448    tokio::sync::oneshot::Receiver<()>,
449);
450
451/// Real channel-0 control handler for subc itself.
452#[derive(Clone)]
453pub struct ControlHandler {
454    #[cfg(test)]
455    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
456    /// Holds connection cleanup at a numbered point: 0 is just after the agent
457    /// declaration queue closes, 1 just after the registration channel is
458    /// forgotten.
459    #[cfg(test)]
460    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
461    /// Runs once in `route.open`'s launch-nonce attestation, right after the
462    /// nonce is resolved, to interleave a nonce withdrawal there.
463    #[cfg(test)]
464    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
465    /// Holds a registration channel's HELLO after its reader resolved the
466    /// channel and before the blocking HELLO handler starts.
467    #[cfg(test)]
468    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
469    /// Holds an agent command declaration at a numbered point in its handler.
470    #[cfg(test)]
471    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
472    claims: Arc<claims::Claims>,
473    registry: Arc<Registry>,
474    control_usage: Arc<Mutex<usage::ControlUsage>>,
475    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
476    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
477    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
478    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
479    config_review_admission_is_default: bool,
480    activity: Option<crate::activity::ActivityLedger>,
481    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
482    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
483    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
484    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
485    forwarding: Arc<ForwardingTable>,
486    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
487    supervisor: SupervisorHandle,
488    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
489    agent_declarations: agent_commands::Queues,
490    list_admission: Arc<tokio::sync::Semaphore>,
491    subc_capabilities: Arc<[String]>,
492    /// Daemon-wide route.bind relay budget. Used as the fallback when the
493    /// target module has no per-module override in
494    /// `route_bind_relay_timeouts`.
495    route_bind_relay_timeout: Duration,
496    /// Per-module route.bind relay budget overrides, keyed by module id. When
497    /// `handle_route_open` resolves the deadline for a target module, a
498    /// per-module entry wins over the daemon-wide value above.
499    route_bind_relay_timeouts: BTreeMap<String, Duration>,
500    /// Per-target-module bind-relay breaker state. Shared with the forwarding
501    /// table, which is where a new module connection resets it.
502    route_bind_breakers: RouteBindBreakers,
503    /// Live relay admissions keyed by target module. Shared through the
504    /// forwarding table so cloned or separately built handlers enforce one cap.
505    route_bind_concurrency: RouteBindConcurrency,
506    /// Start and end of each module's not-serving period as seen by
507    /// `route.open`, so an outage gets one line at each edge instead of only
508    /// the per-refusal INFO lines. Taken from the forwarding table, so every
509    /// handler built over one table shares it.
510    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
511    /// Consecutive relay timeouts that open a module's breaker.
512    route_bind_breaker_threshold: u32,
513    /// How long a breaker stays open before one probe is admitted.
514    route_bind_breaker_cooldown: Duration,
515    health_probe_timeout: Duration,
516    /// Central storage policy. When set, each registering module receives its
517    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
518    storage_config: Option<crate::daemon_config::StorageConfig>,
519    /// The machine id established at boot, served on every HELLO_ACK and on
520    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
521    /// changes the file, never this value. `None` serves no id.
522    machine_id: Option<crate::machine_id::MachineId>,
523    admission_facts_carrier_module_id: Option<String>,
524    admission_facts_targets: Option<Vec<String>>,
525    /// Scope records with their sync authorities and tombstones; see
526    /// `crate::scopes`. Shared by clones of this handler, so every connection
527    /// reads and writes one table.
528    scopes: Arc<RwLock<ScopeTable>>,
529    /// Wakes the expiry loop when an accepted scope change may have added a
530    /// deadline, so the loop can wait without ticking while no live scope has
531    /// one. A permit is stored when nothing waits, so no wake is lost.
532    scope_deadline_added: Arc<tokio::sync::Notify>,
533    /// The configured `scope_authority_owners`, kept so a rescan can report a
534    /// changed value as needing a daemon restart; rescan never applies it.
535    scope_authority_owners: Vec<String>,
536    federated_scope_owner: String,
537    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
538    privileged_operator_prompt: PrivilegedOperatorPrompt,
539    /// The local and peer address of each accepted TCP client connection, read
540    /// from the daemon's own socket, so a privileged request can name its caller.
541    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
542    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
543    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
544    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
545    config_desktop_stamps:
546        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
547    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
548    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
549    pub(crate) operator_apps:
550        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
551    /// One launch entry per app, behind a leaf lock: no other lock is taken
552    /// while it is held. Entries are memory-only, so a daemon or
553    /// installed-service restart drops them and a relaunched daemon never
554    /// mistakes an older process for its own launch.
555    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
556    /// Serializes `app.open` launches: the liveness check in the decision and
557    /// the later publish must not interleave across concurrent calls, or two
558    /// calls could both launch and the second publish would orphan the first
559    /// process. Refusals and `already_running` answers share the same lock;
560    /// `app.open` is rare, so the cost is negligible.
561    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
562    // Portable wire samples exercise dispatch without starting an OS process.
563    #[cfg(test)]
564    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
565    #[cfg(test)]
566    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
567    #[cfg(test)]
568    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
569    #[cfg(test)]
570    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
571    #[cfg(test)]
572    recovery_exit_test_completed: Option<fn(u64)>,
573    #[cfg(test)]
574    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
575    #[cfg(test)]
576    recovery_exit_test_quiet_retry: bool,
577    #[cfg(test)]
578    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
579    #[cfg(test)]
580    config_delivery_test_wakes:
581        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
582    #[cfg(all(test, unix))]
583    config_delivery_test_idle:
584        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
585    /// Test-only Windows signature and flash hooks. Production builds carry
586    /// neither: with the publisher unset, the production table never reaches
587    /// verification, and the default attention hook only logs.
588    #[allow(dead_code)]
589    #[cfg(windows)]
590    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
591    #[allow(dead_code)]
592    #[cfg(windows)]
593    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
594    /// Test-only tracking fault hook: makes opening the tracking handle on
595    /// the launched pid fail, so a test can prove an untrackable launch is
596    /// stopped rather than left running.
597    #[allow(dead_code)]
598    #[cfg(windows)]
599    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
600    /// Test-only count of Windows spawn attempts, so a test can prove a
601    /// refused launch started no process. Unit tests only.
602    #[cfg(all(test, windows))]
603    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
604    #[cfg(test)]
605    caller_lookup: Option<TestCallerLookup>,
606    /// The launch nonce each module connection presented at HELLO, which is how
607    /// a `scope.sync` is matched to the owner's current launch.
608    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
609    rescan: Option<SupervisorRescanContext>,
610    connected_clients: ConnectedClients,
611    counters: DaemonCounters,
612    /// Why this daemon serves no local endpoint, when binding one failed. `None`
613    /// when the endpoint is served, and also on a handler that was never told.
614    local_endpoint_unavailable: Option<String>,
615    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
616    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
617    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
618    /// their usual severity (see [`log_requirement_events`]). A handler built
619    /// without one has a flag that is never set.
620    daemon_shutdown: DaemonShutdownFlag,
621    daemon_provenance: DaemonProvenanceFacts,
622    #[cfg(test)]
623    control_dispatch_delay: Option<Duration>,
624    #[cfg(test)]
625    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
626    /// Holds `route.open` after the route.bind is queued to the module and
627    /// before it is marked enqueued, so a test can make the module's reply (or
628    /// a client teardown) land exactly inside that window.
629    #[cfg(test)]
630    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
631    /// Holds a HELLO after its registry entry is reserved and before its
632    /// forwarding endpoint is installed, so a test can read the catalog and
633    /// open routes while the module is registered but not yet routable. A
634    /// blocking barrier because the HELLO handler is synchronous; the test
635    /// runs the HELLO on its own thread.
636    #[cfg(test)]
637    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
638    #[cfg(test)]
639    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
640    #[cfg(test)]
641    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
642    #[cfg(test)]
643    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
644    #[cfg(test)]
645    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
646}
647
648impl fmt::Debug for ControlHandler {
649    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650        f.debug_struct("ControlHandler")
651            .field("registry", &self.registry)
652            .field("forwarding", &self.forwarding)
653            .field("process_liveness", &self.process_liveness.is_some())
654            .field("supervisor", &self.supervisor)
655            .field("subc_capabilities", &self.subc_capabilities)
656            .finish()
657    }
658}
659
660struct RouteOpenRequest {
661    target: RouteTarget,
662    identity: BindIdentity,
663    consumer_identity: Option<ConsumerIdentity>,
664    consumer_capabilities: Option<Vec<String>>,
665    role_versions: Option<BTreeMap<String, String>>,
666    busy_refusals: Option<bool>,
667    admission_facts: Option<serde_json::Value>,
668    scope: Option<ScopeSelector>,
669    accepts_close_reasons: Option<Vec<String>>,
670}
671
672#[derive(Clone, Copy)]
673enum RouteOpenPhase {
674    Admission,
675    ProjectRoot,
676    EgressReservation,
677    BindSend,
678    BindAckWait,
679}
680
681/// Store elapsed time for each route-open phase, including attempts that end
682/// in an early refusal or backend error. Admission also includes rechecks and
683/// commit bookkeeping performed between the other timed phases.
684struct RouteOpenTimings {
685    module_id: String,
686    principal: String,
687    admission: Duration,
688    project_root: Duration,
689    egress_reservation: Duration,
690    bind_send: Duration,
691    bind_ack_wait: Duration,
692    phase: Option<RouteOpenPhase>,
693    phase_started_at: Instant,
694}
695
696impl RouteOpenTimings {
697    fn new() -> Self {
698        Self {
699            module_id: String::new(),
700            // Refusals before attestation must not claim a verified principal.
701            principal: "unresolved".to_string(),
702            admission: Duration::ZERO,
703            project_root: Duration::ZERO,
704            egress_reservation: Duration::ZERO,
705            bind_send: Duration::ZERO,
706            bind_ack_wait: Duration::ZERO,
707            phase: Some(RouteOpenPhase::Admission),
708            phase_started_at: Instant::now(),
709        }
710    }
711
712    fn finish(&mut self) {
713        let elapsed = self.phase_started_at.elapsed();
714        match self.phase.take() {
715            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
716            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
717            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
718            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
719            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
720            None => {}
721        }
722    }
723
724    fn enter(&mut self, phase: RouteOpenPhase) {
725        self.finish();
726        self.phase = Some(phase);
727        self.phase_started_at = Instant::now();
728    }
729}
730
731struct RouteBindReservationGuard {
732    forwarding: Arc<ForwardingTable>,
733    endpoint: ModuleEndpointId,
734    relay_corr: u64,
735    armed: bool,
736}
737
738struct ModuleControlRpcGuard {
739    forwarding: Arc<ForwardingTable>,
740    endpoint: ModuleEndpointId,
741    corr: u64,
742    armed: bool,
743}
744
745impl ModuleControlRpcGuard {
746    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
747        Self {
748            forwarding,
749            endpoint,
750            corr,
751            armed: true,
752        }
753    }
754
755    fn disarm(&mut self) {
756        self.armed = false;
757    }
758}
759
760impl Drop for ModuleControlRpcGuard {
761    fn drop(&mut self) {
762        if self.armed {
763            let _ = self
764                .forwarding
765                .cancel_module_control_rpc(self.endpoint, self.corr);
766        }
767    }
768}
769
770impl RouteBindReservationGuard {
771    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
772        Self {
773            forwarding,
774            endpoint,
775            relay_corr,
776            armed: true,
777        }
778    }
779
780    fn release_and_disarm(&mut self) {
781        if !self.armed {
782            return;
783        }
784        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
785            self.endpoint,
786            self.relay_corr,
787            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
788        ) {
789            send_goodbye_target_best_effort(
790                &self.forwarding.counters(),
791                &target,
792                "canceled route.bind",
793            );
794        }
795        self.armed = false;
796    }
797
798    fn disarm(&mut self) {
799        self.armed = false;
800    }
801}
802
803impl Drop for RouteBindReservationGuard {
804    fn drop(&mut self) {
805        self.release_and_disarm();
806    }
807}
808
809/// Per-target-module circuit breaker around the `route.bind` relay.
810///
811/// The connection reader is serial per connection, so a module whose `on_bind`
812/// sits on the ack blocks every LATER frame on the connections that call it,
813/// including calls to unrelated modules. This does not make any module's bind
814/// fast; it stops the daemon paying the full budget again and again for a
815/// condition it has already observed.
816///
817/// State is keyed by TARGET MODULE and shared by every connection: a wedged
818/// module wedges everyone, so what one connection learned should protect the
819/// rest.
820///
821/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
822/// relay to that module has actually timed out, and is removed again when a
823/// relay is accepted or the module reconnects, so it cannot grow with traffic
824/// or with modules that behave.
825///
826/// # Why a `std` mutex here is not the head-of-line defect again
827///
828/// Acquisition never awaits. The critical section is a hash lookup plus a few
829/// integer updates, with no I/O and no `.await` inside it, so a reader task
830/// cannot be descheduled behind it the way it can behind
831/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
832/// primitive, held for the same kind of work, as the refusal counter this very
833/// path already increments.
834///
835/// It is also NOT on the data-plane splice path: only `route.open` and module
836/// registration touch it, so bound-route frames gain no state check and no
837/// contention.
838#[derive(Debug, Clone, Default)]
839pub(crate) struct RouteBindBreakers {
840    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
841}
842
843#[derive(Debug, Clone, Default)]
844pub(crate) struct RouteBindConcurrency {
845    modules: Arc<Mutex<HashMap<String, usize>>>,
846}
847
848struct RouteBindConcurrencyGuard {
849    concurrency: RouteBindConcurrency,
850    module_id: String,
851}
852
853impl RouteBindConcurrency {
854    /// Admit without waiting. Waiting here would move the bind stall from the
855    /// module reply to a semaphore and restore reader head-of-line blocking.
856    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
857        let mut modules = self
858            .modules
859            .lock()
860            .expect("route.bind concurrency mutex poisoned");
861        let in_flight = modules.entry(module_id.to_string()).or_default();
862        if *in_flight >= limit {
863            return Err(*in_flight);
864        }
865        *in_flight += 1;
866        Ok(RouteBindConcurrencyGuard {
867            concurrency: self.clone(),
868            module_id: module_id.to_string(),
869        })
870    }
871}
872
873impl Drop for RouteBindConcurrencyGuard {
874    fn drop(&mut self) {
875        let mut modules = self
876            .concurrency
877            .modules
878            .lock()
879            .expect("route.bind concurrency mutex poisoned");
880        let remove = {
881            let in_flight = modules
882                .get_mut(&self.module_id)
883                .expect("admitted route.bind has a concurrency entry");
884            *in_flight -= 1;
885            *in_flight == 0
886        };
887        if remove {
888            modules.remove(&self.module_id);
889        }
890    }
891}
892
893#[derive(Debug, Default)]
894struct ModuleBreakerState {
895    /// Relay timeouts observed with no accepted relay in between.
896    consecutive_timeouts: u32,
897    /// `Some` while the breaker is open: the instant the cooldown expires and
898    /// the next arrival may probe. `None` means closed.
899    cooldown_until: Option<Instant>,
900    /// A half-open probe has been admitted and has not settled yet. This is
901    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
902    /// that read the cooldown, so concurrent opens arriving at the moment the
903    /// cooldown expires cannot all decide that they are the probe.
904    probe_in_flight: Option<Arc<()>>,
905}
906
907/// What the breaker decided for one `route.open`, before any relay work.
908enum RouteBindAdmission<'a> {
909    Admitted {
910        guard: RouteBindBreakerGuard<'a>,
911        /// This open is the single half-open probe, so the transition is worth
912        /// one log line.
913        probe: bool,
914    },
915    Refused {
916        consecutive_timeouts: u32,
917        /// What is left of the cooldown. Zero when the refusal is because the
918        /// one probe is already in flight rather than because the cooldown has
919        /// not elapsed.
920        retry_in: Duration,
921        probe_in_flight: bool,
922    },
923}
924
925/// An outstanding admission, which must be told how its relay settled.
926///
927/// `Drop` settles it as inconclusive, so an early return between admission and
928/// the relay -- or the whole handler being cancelled when the client
929/// disconnects -- releases a half-open probe slot instead of leaving the
930/// breaker wedged half-open with no further probes.
931struct RouteBindBreakerGuard<'a> {
932    breakers: RouteBindBreakers,
933    module_id: &'a str,
934    probe_token: Option<Arc<()>>,
935    settled: bool,
936}
937
938impl RouteBindBreakerGuard<'_> {
939    /// The module answered within the budget and took the bind. THE ONLY
940    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
941    /// breaker, which is a transition worth logging.
942    fn record_accepted(&mut self) -> bool {
943        self.settled = true;
944        self.breakers.record_accepted(self.module_id)
945    }
946
947    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
948    /// COUNTS TOWARD OPENING.
949    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
950        self.settled = true;
951        self.breakers.record_timeout(
952            self.module_id,
953            self.probe_token.as_ref(),
954            threshold,
955            cooldown,
956        )
957    }
958
959    /// Everything else: the module REJECTED the bind, its connection went away
960    /// mid-relay, or the waiter was cancelled.
961    ///
962    /// None of these is evidence that a module is slow, and each already has
963    /// its own refusal with its own code. A module that rejects a bind in
964    /// microseconds is healthy and must never be convicted for it; a module
965    /// that died has said nothing about the module that replaces it. So these
966    /// neither increment nor reset the count -- they only release a probe slot.
967    fn record_inconclusive(&mut self) {
968        self.settled = true;
969        self.breakers
970            .record_inconclusive(self.module_id, self.probe_token.as_ref());
971    }
972}
973
974impl Drop for RouteBindBreakerGuard<'_> {
975    fn drop(&mut self) {
976        if !self.settled {
977            self.breakers
978                .record_inconclusive(self.module_id, self.probe_token.as_ref());
979        }
980    }
981}
982
983/// The breaker moved to open, reported so the caller can log it outside the
984/// lock. Opening is rare and load-bearing; the refusals that follow are
985/// frequent and are counted rather than logged.
986struct BreakerOpened {
987    consecutive_timeouts: u32,
988    /// True when a failed probe re-opened an already-open breaker, which reads
989    /// very differently in a log from a first opening.
990    reopened_after_probe: bool,
991}
992
993impl RouteBindBreakers {
994    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
995        self.modules
996            .lock()
997            .expect("route.bind breaker mutex poisoned")
998    }
999
1000    /// Decide whether this `route.open` may attempt its relay. Takes the map
1001    /// lock and nothing else, and never awaits.
1002    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
1003        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
1004            probe: probe_token.is_some(),
1005            guard: RouteBindBreakerGuard {
1006                breakers: self.clone(),
1007                module_id,
1008                probe_token,
1009                settled: false,
1010            },
1011        };
1012
1013        let mut modules = self.lock();
1014        let Some(state) = modules.get_mut(module_id) else {
1015            return admitted(None);
1016        };
1017        let Some(cooldown_until) = state.cooldown_until else {
1018            return admitted(None);
1019        };
1020        if state.probe_in_flight.is_some() {
1021            return RouteBindAdmission::Refused {
1022                consecutive_timeouts: state.consecutive_timeouts,
1023                retry_in: Duration::ZERO,
1024                probe_in_flight: true,
1025            };
1026        }
1027        let now = Instant::now();
1028        if now < cooldown_until {
1029            return RouteBindAdmission::Refused {
1030                consecutive_timeouts: state.consecutive_timeouts,
1031                retry_in: cooldown_until - now,
1032                probe_in_flight: false,
1033            };
1034        }
1035        let token = Arc::new(());
1036        state.probe_in_flight = Some(Arc::clone(&token));
1037        admitted(Some(token))
1038    }
1039
1040    fn record_accepted(&self, module_id: &str) -> bool {
1041        self.lock()
1042            .remove(module_id)
1043            .is_some_and(|state| state.cooldown_until.is_some())
1044    }
1045
1046    fn record_timeout(
1047        &self,
1048        module_id: &str,
1049        probe_token: Option<&Arc<()>>,
1050        threshold: u32,
1051        cooldown: Duration,
1052    ) -> Option<BreakerOpened> {
1053        let mut modules = self.lock();
1054        let state = modules.entry(module_id.to_string()).or_default();
1055        let was_open = state.cooldown_until.is_some();
1056        let was_probe = Self::owns_probe(state, probe_token);
1057        if was_probe {
1058            state.probe_in_flight = None;
1059        }
1060        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
1061        if state.consecutive_timeouts < threshold {
1062            return None;
1063        }
1064        state.cooldown_until = Some(Instant::now() + cooldown);
1065        Some(BreakerOpened {
1066            consecutive_timeouts: state.consecutive_timeouts,
1067            reopened_after_probe: was_open && was_probe,
1068        })
1069    }
1070
1071    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
1072        // A relay can finish after the breaker was reset or after it opened
1073        // again and started a new probe. Only the guard whose token matches the
1074        // active probe may release it, so a late relay never frees a newer probe.
1075        state
1076            .probe_in_flight
1077            .as_ref()
1078            .zip(token)
1079            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
1080    }
1081
1082    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
1083        if let Some(state) = self.lock().get_mut(module_id) {
1084            if Self::owns_probe(state, probe_token) {
1085                state.probe_in_flight = None;
1086            }
1087        }
1088    }
1089
1090    /// Discard what was learned about a module, because the process it was
1091    /// learned about is gone. Returns the discarded count when it was non-zero.
1092    ///
1093    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
1094    /// `module_id` is a configuration identity that outlives any particular
1095    /// child; what the breaker observed was the process behind the module
1096    /// connection of the moment. When a new connection registers under that id
1097    /// the verdict's subject no longer exists, so the verdict is stale by
1098    /// construction rather than merely likely to be wrong. Keeping it would
1099    /// apply a dead process's record to a live one, which is the same defect
1100    /// class this breaker exists to stop the daemon committing.
1101    ///
1102    /// A half-open probe in flight is discarded with the rest: it was a
1103    /// question about the old process.
1104    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
1105        self.lock()
1106            .remove(module_id)
1107            .map(|state| state.consecutive_timeouts)
1108            .filter(|discarded| *discarded > 0)
1109    }
1110
1111    /// Open breakers, for the `server.describe` counters object. `None` when
1112    /// none is open, so the key stays absent rather than present-and-empty.
1113    ///
1114    /// This is the operator's answer to "is this module refusing instantly or
1115    /// is it fine?", which look identical from a client that retries and then
1116    /// succeeds.
1117    fn open_snapshot(&self) -> Option<serde_json::Value> {
1118        let now = Instant::now();
1119        let modules = self.lock();
1120        let open = modules
1121            .iter()
1122            .filter_map(|(module_id, state)| {
1123                let cooldown_until = state.cooldown_until?;
1124                Some((
1125                    module_id.clone(),
1126                    serde_json::json!({
1127                        "consecutive_timeouts": state.consecutive_timeouts,
1128                        "cooldown_remaining_ms":
1129                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
1130                        "probe_in_flight": state.probe_in_flight.is_some(),
1131                    }),
1132                ))
1133            })
1134            .collect::<serde_json::Map<String, serde_json::Value>>();
1135        (!open.is_empty()).then_some(serde_json::Value::Object(open))
1136    }
1137}
1138
1139impl ControlHandler {
1140    pub(crate) fn install_registration_service(
1141        &self,
1142        router: std::sync::Weak<crate::Router>,
1143        auth: crate::server::ServerAuth,
1144    ) {
1145        self.supervisor.install_registration_service(router, auth);
1146    }
1147    pub fn new(registry: Arc<Registry>) -> Self {
1148        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
1149    }
1150
1151    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
1152        let counters = forwarding.counters();
1153        // Taken from the forwarding table rather than created here, so that the
1154        // breaker a `route.open` consults is the same one a module's
1155        // registration resets, however many handlers are built over one table.
1156        let route_bind_breakers = forwarding.route_bind_breakers();
1157        let route_bind_concurrency = forwarding.route_bind_concurrency();
1158        let route_outages = forwarding.route_outages();
1159        Self {
1160            registry,
1161            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
1162            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
1163            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1164            #[cfg(test)]
1165            activity_request_pause: Arc::new(Mutex::new(None)),
1166            #[cfg(test)]
1167            cleanup_pause: Arc::new(Mutex::new(None)),
1168            #[cfg(test)]
1169            after_nonce_attestation: Arc::new(Mutex::new(None)),
1170            #[cfg(test)]
1171            hello_ingress_pause: Arc::new(Mutex::new(None)),
1172            #[cfg(test)]
1173            agent_commands_pause: Arc::new(Mutex::new(None)),
1174            claims: Arc::new(claims::Claims::default()),
1175            config_runtime: None,
1176            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
1177            config_review_admission_is_default: true,
1178            activity: None,
1179            activity_streams: Arc::new(Mutex::new(HashMap::new())),
1180            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
1181            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
1182            scope_streams: Arc::new(Mutex::new(HashMap::new())),
1183            forwarding,
1184            process_liveness: None,
1185            supervisor: SupervisorHandle::new(),
1186            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
1187                env!("CARGO_PKG_VERSION").to_owned(),
1188            )),
1189            agent_declarations: agent_commands::Queues::default(),
1190            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
1191            subc_capabilities: Arc::from([
1192                CAP_MANIFEST_REGISTRATION.to_string(),
1193                CAP_CHANNEL_LIFECYCLE.to_string(),
1194                CAP_PING_PONG.to_string(),
1195                CAP_SESSION_ATTACH.to_string(),
1196                CAP_ADMISSION_FACTS_RELAY.to_string(),
1197                CAP_SCOPES_V1.to_string(),
1198                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
1199                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
1200                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1201                PEER_BUILD_CAPABILITY.to_string(),
1202                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1203                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1204                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1205                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1206                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1207                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1208                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1209                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1210                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1211                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1212                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1213                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1214            ]),
1215            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1216            route_bind_relay_timeouts: BTreeMap::new(),
1217            route_bind_breakers,
1218            route_bind_concurrency,
1219            route_outages,
1220            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1221            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1222            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1223            storage_config: None,
1224            machine_id: None,
1225            admission_facts_carrier_module_id: None,
1226            admission_facts_targets: None,
1227            scopes: Arc::new(RwLock::new(ScopeTable::new(
1228                crate::daemon_config::default_scope_authority_owners(),
1229            ))),
1230            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1231            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1232            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1233            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1234            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1235            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1236            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1237            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1238            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1239            local_connections: Arc::new(Mutex::new(HashSet::new())),
1240            operator_app_policy: Default::default(),
1241            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1242            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1243            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1244            #[cfg(test)]
1245            app_open_test_platform: None,
1246            #[cfg(test)]
1247            app_open_test_launch: None,
1248            #[cfg(test)]
1249            config_review_test_reply: None,
1250            #[cfg(test)]
1251            recovery_exit_test_after_step: None,
1252            #[cfg(test)]
1253            recovery_exit_test_completed: None,
1254            #[cfg(test)]
1255            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1256            #[cfg(test)]
1257            recovery_exit_test_quiet_retry: false,
1258            #[cfg(test)]
1259            recovery_exit_test_retry_pause: None,
1260            #[cfg(test)]
1261            config_delivery_test_wakes: None,
1262            #[cfg(all(test, unix))]
1263            config_delivery_test_idle: None,
1264            #[cfg(windows)]
1265            windows_verify: None,
1266            #[cfg(windows)]
1267            windows_flash: None,
1268            #[cfg(windows)]
1269            windows_track: None,
1270            #[cfg(all(test, windows))]
1271            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1272            #[cfg(test)]
1273            caller_lookup: None,
1274            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1275            rescan: None,
1276            connected_clients: ConnectedClients::new(),
1277            local_endpoint_unavailable: None,
1278            counters,
1279            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1280            daemon_shutdown: DaemonShutdownFlag::default(),
1281            daemon_provenance: DaemonProvenanceFacts::default(),
1282            #[cfg(test)]
1283            control_dispatch_delay: None,
1284            #[cfg(test)]
1285            provenance_probe_override: None,
1286            #[cfg(test)]
1287            route_bind_relay_sent_hold: None,
1288            #[cfg(test)]
1289            hello_registry_to_forwarding_hold: None,
1290            #[cfg(test)]
1291            hello_ack_to_publication_hold: None,
1292            #[cfg(test)]
1293            hello_before_publication_hold: None,
1294            #[cfg(test)]
1295            hello_after_launch_check_hold: None,
1296            #[cfg(test)]
1297            hello_inside_publication_hold: None,
1298        }
1299    }
1300
1301    /// Set the central storage policy: registering modules then receive their
1302    /// resolved storage descriptor in HELLO_ACK.
1303    pub fn with_storage_config(
1304        mut self,
1305        storage_config: Option<crate::daemon_config::StorageConfig>,
1306    ) -> Self {
1307        self.storage_config = storage_config;
1308        self
1309    }
1310
1311    /// Open the ledger on its own writer thread; an unavailable sink does not
1312    /// prevent the daemon from serving routing or supervisor requests.
1313    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1314        self.activity = Some(crate::activity::ActivityLedger::open(
1315            run_dir.join("activity.jsonl"),
1316            incarnation,
1317        ));
1318        self.supervisor.set_activity(self.activity.clone());
1319        self
1320    }
1321
1322    /// Set the machine id served to every registering module (HELLO_ACK) and on
1323    /// `server.describe`.
1324    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1325        self.machine_id = machine_id;
1326        self
1327    }
1328
1329    /// Configure the exact reserved module and target ids permitted to relay
1330    /// opaque admission facts. Config-file loading validates this authority;
1331    /// this builder keeps the same policy available to embedded test daemons.
1332    pub fn with_admission_facts_config(
1333        mut self,
1334        carrier_module_id: Option<String>,
1335        targets: Option<Vec<String>>,
1336    ) -> Self {
1337        self.admission_facts_carrier_module_id = carrier_module_id;
1338        self.admission_facts_targets = targets;
1339        self
1340    }
1341
1342    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1343    /// Replaces the scope table with an empty one under the new list, so call it
1344    /// while building the handler, before any module can sync.
1345    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1346        self.scopes = Arc::new(RwLock::new(
1347            ScopeTable::new(owners.iter().cloned())
1348                .with_federated_owner(self.federated_scope_owner.clone()),
1349        ));
1350        self.scope_authority_owners = owners;
1351        self
1352    }
1353
1354    /// Set the exclusive federated owner while building the handler, before syncs.
1355    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1356        self.scopes = Arc::new(RwLock::new(
1357            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1358                .with_federated_owner(owner.clone()),
1359        ));
1360        self.federated_scope_owner = owner;
1361        self
1362    }
1363
1364    /// Set the startup policy before installing the rescan context or serving requests.
1365    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1366        self.privileged_operator_prompt = mode;
1367        self
1368    }
1369
1370    /// Override the route.bind relay timeout. Used by tests that assert the
1371    /// timeout path so they don't block on the production-safe default.
1372    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1373        self.route_bind_relay_timeout = timeout;
1374        self
1375    }
1376
1377    /// Install per-module route.bind relay budget overrides. A module id
1378    /// listed here wins over the daemon-wide default set via
1379    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1380    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1381    /// the same `Duration` the bind path will use.
1382    pub fn with_route_bind_relay_timeouts(
1383        mut self,
1384        timeouts: impl IntoIterator<Item = (String, Duration)>,
1385    ) -> Self {
1386        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1387        self
1388    }
1389
1390    /// Resolve the route.bind relay budget for a specific target module id.
1391    /// Per-module overrides win; the daemon-wide value (set via
1392    /// `with_route_bind_relay_timeout` or the built-in default) is the
1393    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1394    /// the same resolution `handle_route_open` will use.
1395    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1396        self.route_bind_relay_timeouts
1397            .get(module_id)
1398            .copied()
1399            .unwrap_or(self.route_bind_relay_timeout)
1400    }
1401
1402    /// Override the per-module bind-relay breaker policy.
1403    ///
1404    /// Used by tests, which cannot spend three production budgets opening a
1405    /// breaker or twenty seconds waiting for its cooldown. The production
1406    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1407    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1408    /// reasoning for the numbers.
1409    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1410        self.route_bind_breaker_threshold = threshold.max(1);
1411        self.route_bind_breaker_cooldown = cooldown;
1412        self
1413    }
1414
1415    #[cfg(test)]
1416    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1417        self.health_probe_timeout = timeout;
1418        self
1419    }
1420
1421    #[cfg(test)]
1422    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1423        self.control_dispatch_delay = Some(delay);
1424        self
1425    }
1426
1427    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1428    /// announce it is parked, once to be released. Build the barrier for two
1429    /// parties, the test being the other one.
1430    #[cfg(test)]
1431    pub(crate) fn with_route_bind_relay_sent_hold(
1432        mut self,
1433        hold: Arc<tokio::sync::Barrier>,
1434    ) -> Self {
1435        self.route_bind_relay_sent_hold = Some(hold);
1436        self
1437    }
1438
1439    /// A HELLO waits on `hold` twice between reserving its registry entry and
1440    /// installing its forwarding endpoint: once to announce it is parked, once
1441    /// to be released. Build the barrier for two parties, the test being the
1442    /// other one, and run the HELLO on a thread of its own.
1443    #[cfg(test)]
1444    pub(crate) fn with_hello_registry_to_forwarding_hold(
1445        mut self,
1446        hold: Arc<std::sync::Barrier>,
1447    ) -> Self {
1448        self.hello_registry_to_forwarding_hold = Some(hold);
1449        self
1450    }
1451
1452    #[cfg(test)]
1453    fn hold_between_registry_and_forwarding(&self) {
1454        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1455            hold.wait();
1456            hold.wait();
1457        }
1458    }
1459
1460    /// Park after the ACK is queued and forwarding is installed, until a test
1461    /// has read the ACK and issued a registry lookup from another connection.
1462    #[cfg(test)]
1463    fn hold_between_ack_and_publication(&self) {
1464        if let Some(hold) = &self.hello_ack_to_publication_hold {
1465            hold.wait();
1466            hold.wait();
1467        }
1468    }
1469
1470    #[cfg(all(test, unix))]
1471    pub(crate) fn with_hello_before_publication_hold(
1472        mut self,
1473        hold: Arc<std::sync::Barrier>,
1474    ) -> Self {
1475        self.hello_before_publication_hold = Some(hold);
1476        self
1477    }
1478
1479    #[cfg(all(test, unix))]
1480    pub(crate) fn with_hello_after_launch_check_hold(
1481        mut self,
1482        hold: Arc<std::sync::Barrier>,
1483    ) -> Self {
1484        self.hello_after_launch_check_hold = Some(hold);
1485        self
1486    }
1487
1488    #[cfg(all(test, unix))]
1489    pub(crate) fn with_hello_inside_publication_hold(
1490        mut self,
1491        hold: Arc<std::sync::Barrier>,
1492    ) -> Self {
1493        self.hello_inside_publication_hold = Some(hold);
1494        self
1495    }
1496
1497    pub fn with_process_liveness(
1498        mut self,
1499        process_liveness: Arc<dyn ModuleProcessLiveness>,
1500    ) -> Self {
1501        self.process_liveness = Some(process_liveness);
1502        self
1503    }
1504
1505    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1506        self.supervisor = supervisor;
1507        if let Some(owner) = &self.config_runtime {
1508            self.supervisor.install_binding_retirement(owner);
1509        }
1510        self.supervisor.set_activity(self.activity.clone());
1511        self
1512    }
1513
1514    pub fn with_daemon_provenance(
1515        mut self,
1516        pid: u32,
1517        started_at_ms: u64,
1518        executable_path: Option<PathBuf>,
1519        build_git_sha: Option<String>,
1520        build_lock_digest: Option<String>,
1521    ) -> Self {
1522        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1523        let process_start_time = process_start_time(pid);
1524        self.daemon_provenance = DaemonProvenanceFacts {
1525            build: DaemonBuildProvenance {
1526                build_git_sha,
1527                build_lock_digest,
1528            },
1529            pid: Some(pid),
1530            started_at_ms: Some(started_at_ms),
1531            start_clock: None,
1532            executable_path,
1533            executable_identity,
1534            process_start_time,
1535            probe: ExecutableIdentityProbe::default(),
1536        };
1537        self
1538    }
1539
1540    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1541        self.daemon_provenance.start_clock = Some(clock);
1542        self
1543    }
1544
1545    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1546    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1547        self.scopes
1548            .write()
1549            .unwrap_or_else(|poisoned| poisoned.into_inner())
1550            .set_wall_clock(Arc::new(clock));
1551        self
1552    }
1553
1554    #[cfg(test)]
1555    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1556        self.provenance_probe_override = Some(result);
1557        self
1558    }
1559
1560    /// Install the configured module set and its reserved capability bindings.
1561    /// Bindings are configuration-scoped and may point at a provider that has not
1562    /// been installed yet, so this does not require the bound module to exist.
1563    pub fn with_capability_config(
1564        self,
1565        modules: impl IntoIterator<Item = (String, bool)>,
1566        reserved_capabilities: BTreeMap<String, String>,
1567    ) -> Self {
1568        self.capability_evaluator
1569            .configure(modules, reserved_capabilities);
1570        self
1571    }
1572
1573    /// Share the supervisor's daemon-shutdown flag with this handler, so
1574    /// requirement changes after the daemon has begun its announced shutdown
1575    /// are not reported as faults.
1576    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1577        self.daemon_shutdown = flag;
1578        self
1579    }
1580
1581    pub fn with_supervisor_rescan(
1582        mut self,
1583        supervisor: Supervisor,
1584        config_path: impl Into<PathBuf>,
1585        configured_port: Option<u16>,
1586    ) -> Self {
1587        self.rescan = Some(SupervisorRescanContext {
1588            supervisor,
1589            config_path: config_path.into(),
1590            configured_port,
1591            storage_config: self.storage_config.clone(),
1592            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1593            admission_facts_targets: self.admission_facts_targets.clone(),
1594            scope_authority_owners: self.scope_authority_owners.clone(),
1595            federated_scope_owner: self.federated_scope_owner.clone(),
1596            privileged_operator_prompt: self.privileged_operator_prompt,
1597            generation: Arc::default(),
1598            rescan_lock: Arc::default(),
1599            module_entries: Arc::default(),
1600        });
1601        self
1602    }
1603
1604    pub(crate) fn with_supervisor_rescan_entries(
1605        self,
1606        modules: &[crate::daemon_config::ConfiguredModule],
1607    ) -> Self {
1608        if let Some(context) = &self.rescan {
1609            let mut entries = context
1610                .module_entries
1611                .lock()
1612                .unwrap_or_else(|e| e.into_inner());
1613            entries.seed(modules);
1614        }
1615        self
1616    }
1617
1618    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1619        self.connected_clients = connected_clients;
1620        self
1621    }
1622
1623    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1624    /// an operator can see a bind failure without reading the daemon log.
1625    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1626        self.local_endpoint_unavailable = reason;
1627        self
1628    }
1629
1630    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1631        Arc::clone(&self.forwarding)
1632    }
1633
1634    pub(crate) fn counters(&self) -> DaemonCounters {
1635        self.counters.clone()
1636    }
1637
1638    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1639    /// requirement event without depending on an operator polling a status command.
1640    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1641        let handler = Arc::downgrade(&self);
1642        let evaluator = self.capability_evaluator.clone();
1643        tokio::spawn(async move {
1644            loop {
1645                evaluator.wait_for_change_or_deadline().await;
1646                let Some(handler) = handler.upgrade() else {
1647                    break;
1648                };
1649                handler.refresh_capability_requirements();
1650            }
1651        });
1652    }
1653
1654    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1655    /// deadline passed during sleep is enforced on the first tick after wake.
1656    /// While no live scope carries a deadline the loop waits for an accepted
1657    /// scope change instead of ticking, so a daemon without deadlines never
1658    /// wakes for expiry.
1659    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1660        let context = scope_expiry::ScopeExpiryContext::new(&self);
1661        let deadline_added = self.scope_deadline_added.clone();
1662        tokio::spawn(async move {
1663            loop {
1664                if !context.has_deadlines() {
1665                    deadline_added.notified().await;
1666                    continue;
1667                }
1668                tokio::time::sleep(Duration::from_secs(1)).await;
1669                if let Err(error) = context.sweep() {
1670                    warn!(%error, "scope expiry sweep failed");
1671                }
1672            }
1673        });
1674    }
1675
1676    #[cfg(test)]
1677    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1678        scope_expiry::ScopeExpiryContext::new(self).sweep()
1679    }
1680
1681    fn publish_scope_changes(
1682        &self,
1683        changes: &[crate::scopes::ScopeTagChange],
1684        expired: &[crate::scopes::ScopeExpired],
1685    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1686        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1687    }
1688
1689    fn runtime_capability_snapshot(
1690        &self,
1691    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1692        let runtime = self
1693            .supervisor
1694            .list()
1695            .into_iter()
1696            .map(|module| {
1697                let status = module.status().map_err(|err| {
1698                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1699                })?;
1700                Ok(RuntimeModule {
1701                    module_id: status.module_id,
1702                    state: status.state,
1703                    enabled: status.enabled,
1704                })
1705            })
1706            .collect::<Result<Vec<_>, RouterError>>()?;
1707        // Include every registration, published or not. The capability
1708        // evaluator counts a module as providing its capabilities as soon as it
1709        // has registered, even before `catalog.list` shows it, so a HELLO in
1710        // progress does not change other modules' required-capability
1711        // verdicts. See `Registry::list_registered_modules`.
1712        let registrations = self.registry.list_registered_modules().map_err(|err| {
1713            RouterError::backend(
1714                0,
1715                0,
1716                format!("failed to list capability registrations: {err}"),
1717            )
1718        })?;
1719        let registrations = registrations
1720            .into_iter()
1721            .map(|registration| RegisteredModule {
1722                module_id: registration.manifest.module_id,
1723                module_version: registration.manifest.module_version,
1724                capabilities: registration.manifest.capabilities,
1725            })
1726            .collect();
1727        Ok((runtime, registrations))
1728    }
1729
1730    /// The capability side effects of a module becoming the active registration
1731    /// for its id: cache its manifest (logging how it differs from the cached
1732    /// one), run the deny census when its declarations call for one, and recompute the
1733    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1734    /// candidate's does not, and the supervisor does it at promotion instead,
1735    /// through [`crate::supervise::SwapPromotionObserver`].
1736    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1737        let cached_registration = RegisteredModule {
1738            module_id: registration.manifest.module_id.clone(),
1739            module_version: registration.manifest.module_version.clone(),
1740            capabilities: registration.manifest.capabilities.clone(),
1741        };
1742        let change = self.capability_evaluator.record_hello(&cached_registration);
1743        log_manifest_change(&cached_registration.module_id, &change);
1744        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1745            self.enforce_capability_denies();
1746        }
1747        self.refresh_capability_requirements();
1748    }
1749
1750    /// Point the shared supervisor handle at this handler for swap promotions.
1751    /// Called wherever a handler is put behind the `Arc` the router serves, so
1752    /// it can be held weakly.
1753    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1754        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1755            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1756        self.supervisor.set_swap_promotion_observer(observer);
1757    }
1758
1759    pub fn refresh_capability_requirements(&self) {
1760        match self.runtime_capability_snapshot() {
1761            Ok((runtime, registrations)) => {
1762                let events = self
1763                    .capability_evaluator
1764                    .evaluate_now(&runtime, &registrations);
1765                if !events.is_empty() {
1766                    self.catalog_readiness_revision
1767                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1768                }
1769                log_requirement_events(events, &self.daemon_shutdown);
1770            }
1771            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1772        }
1773    }
1774
1775    /// Reconcile only live, attested route bindings after a capability deny edge
1776    /// or target claim was added. This is deliberately a control-plane census:
1777    /// the opaque forwarding hot path must not grow a per-frame capability check.
1778    fn enforce_capability_denies(&self) {
1779        let registrations = match self.registry.list_registered_modules() {
1780            Ok(snapshot) => snapshot,
1781            Err(err) => {
1782                warn!(error = %err, "failed to read registrations for capability deny census");
1783                return;
1784            }
1785        };
1786        let manifests = registrations
1787            .into_iter()
1788            .map(|registration| {
1789                (
1790                    registration.manifest.module_id.clone(),
1791                    registration.manifest,
1792                )
1793            })
1794            .collect::<BTreeMap<_, _>>();
1795        let census = match self.forwarding.route_census(None) {
1796            Ok(census) => census,
1797            Err(err) => {
1798                warn!(error = %err, "failed to read route census for capability deny enforcement");
1799                return;
1800            }
1801        };
1802
1803        for (target_module_id, routes) in census {
1804            let Some(target_manifest) = manifests.get(&target_module_id) else {
1805                continue;
1806            };
1807            let mut closed_routes = Vec::new();
1808            let mut goodbyes = Vec::new();
1809            for route in routes {
1810                let Principal::Reserved {
1811                    module_id: opening_module_id,
1812                } = &route.principal
1813                else {
1814                    continue;
1815                };
1816                let Some(opening_manifest) = manifests.get(opening_module_id) else {
1817                    continue;
1818                };
1819                let Some(capability) = denied_capability(
1820                    opening_manifest.capabilities.as_ref(),
1821                    target_manifest.capabilities.as_ref(),
1822                ) else {
1823                    continue;
1824                };
1825
1826                match self.forwarding.release_client_route(
1827                    route.goodbye_target.connection_id,
1828                    route.goodbye_target.channel,
1829                    route.goodbye_target.epoch,
1830                ) {
1831                    Ok(RouteRelease::Removed(module_goodbye)) => {
1832                        warn!(
1833                            opening_module_id,
1834                            target_module_id,
1835                            capability,
1836                            "force-closing route because an attested capability deny edge now matches"
1837                        );
1838                        goodbyes.push(module_goodbye);
1839                        goodbyes.push(route.goodbye_target.clone());
1840                        closed_routes.push(route);
1841                    }
1842                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
1843                    Err(err) => warn!(
1844                        opening_module_id,
1845                        target_module_id,
1846                        capability,
1847                        error = %err,
1848                        "failed to force-close capability-denied route"
1849                    ),
1850                }
1851            }
1852
1853            if closed_routes.is_empty() {
1854                continue;
1855            }
1856            send_route_control_pushes(
1857                &self.forwarding,
1858                closed_routes,
1859                ClientControlPush::RouteClosed {
1860                    module_id: target_module_id,
1861                    channels: Vec::new(),
1862                    reason: RouteCloseReason::CapabilityDenied,
1863                    drained: false,
1864                    abandoned: 0,
1865                    excluded_subscriptions: 0,
1866                    terminal: Some(false),
1867                },
1868            );
1869            // route.closed records the reason; the route GOODBYE ends the
1870            // client's handle and settles any calls still pending on it.
1871            self.emit_route_goodbyes(goodbyes);
1872        }
1873    }
1874
1875    /// Why a registered module is not accepting new route binds, or `None` when
1876    /// it is. This is the module's effective readiness: its declared readiness
1877    /// first, then every `need: required` capability it declares evaluating to
1878    /// `provided`. `route.open` and `catalog.list` both read it here so the
1879    /// catalog never reports a module routable that `route.open` would refuse.
1880    fn not_ready_reason(
1881        &self,
1882        registration: &crate::registry::ModuleRegistration,
1883    ) -> Option<NotReadyReason> {
1884        if !registration.ready {
1885            return Some(NotReadyReason {
1886                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1887                capability: None,
1888            });
1889        }
1890        self.first_unprovided_required_capability(registration)
1891            .map(|capability| NotReadyReason {
1892                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1893                capability: Some(capability),
1894            })
1895    }
1896
1897    /// The lexicographically first capability this registration declares
1898    /// `need: required` whose evaluator verdict is not `provided`.
1899    ///
1900    /// The verdicts are the capability evaluator's own; nothing here decides
1901    /// what "provided" means. The evaluator counts a capability provided as
1902    /// soon as a module claiming it has REGISTERED, not once that module is
1903    /// ready. That distinction is what keeps two modules that require each
1904    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1905    /// is ready", each would wait for the other to become ready first and
1906    /// neither ever would. Do not tighten it to readiness.
1907    ///
1908    /// A required capability with no verdict at all means this registration's
1909    /// HELLO or catalog.update landed after the last recompute; recompute once
1910    /// rather than let a missing verdict read as either answer. If it is still
1911    /// missing (the recompute itself failed) the capability counts as
1912    /// unprovided: the refusal is retryable, and routing a module whose
1913    /// required provider is unknown is the outcome this check exists to stop.
1914    fn first_unprovided_required_capability(
1915        &self,
1916        registration: &crate::registry::ModuleRegistration,
1917    ) -> Option<String> {
1918        self.first_unprovided_required_capability_for(
1919            &registration.manifest.module_id,
1920            registration.manifest.capabilities.as_ref(),
1921        )
1922    }
1923
1924    fn first_unprovided_required_capability_for(
1925        &self,
1926        module_id: &str,
1927        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1928    ) -> Option<String> {
1929        let required = capabilities
1930            .into_iter()
1931            .flat_map(|declarations| declarations.requires.iter())
1932            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1933            .map(|requirement| requirement.capability.as_str())
1934            .collect::<BTreeSet<_>>();
1935        if required.is_empty() {
1936            return None;
1937        }
1938        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1939        if required
1940            .iter()
1941            .any(|capability| verdict(capability).is_none())
1942        {
1943            self.refresh_capability_requirements();
1944        }
1945        required
1946            .into_iter()
1947            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1948            .map(str::to_string)
1949    }
1950
1951    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1952        self.capability_evaluator
1953            .statuses()
1954            .into_iter()
1955            .map(capability_requirement_status)
1956            .collect()
1957    }
1958
1959    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1960    /// registration-release watch. The signal is what the supervisor waits on
1961    /// before spawning a replacement, so it must only fire once forwarding
1962    /// teardown is also done (see [`Self::cleanup_connection`] /
1963    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1964    /// registry-only path below because publication already owns the spawn lock.
1965    fn deregister_connection(
1966        &self,
1967        connection_id: ConnectionId,
1968        reason: RegistrationEndReason,
1969    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1970        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1971            spawn.end_primary_registration();
1972        }
1973        self.registry
1974            .deregister_connection_with_reason(connection_id, reason)
1975    }
1976
1977    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1978    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1979    // or claim-bound consumers to revoke. Remove only its unpublished registry
1980    // entry without re-entering primary-registration teardown.
1981    fn rollback_unpublished_hello(
1982        &self,
1983        connection: ConnectionId,
1984    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1985        self.registry.deregister_connection_with_reason(
1986            connection,
1987            RegistrationEndReason::RegistrationFailed,
1988        )
1989    }
1990
1991    fn request_refusal_close(
1992        &self,
1993        connection: ConnectionId,
1994        sink: Option<&crate::FrameSink>,
1995        reason: CloseReason,
1996    ) {
1997        if let Some(sink) = sink {
1998            sink.terminate_ingress();
1999        }
2000        if self.claims.close_notifications_enabled() {
2001            self.forwarding.request_connection_close(connection, reason);
2002        }
2003    }
2004
2005    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
2006        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
2007            return None;
2008        }
2009        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
2010            parse_client_control_request(&frame.body)
2011        else {
2012            return None;
2013        };
2014        Some(target_module_id(&target).to_string())
2015    }
2016
2017    pub(crate) fn route_open_capacity_refusal(
2018        &self,
2019        ctx: &RouteCtx,
2020        frame: &Frame,
2021        target_module_id: &str,
2022        in_flight: usize,
2023        limit: usize,
2024    ) -> Result<Frame, RouterError> {
2025        // Sent before the request reaches `handle_route_open`, so the caller
2026        // fields come from the raw frame here.
2027        let caller = self.route_open_caller_from_frame(ctx, frame);
2028        self.route_open_admission_refusal_frame(
2029            ctx,
2030            &caller,
2031            frame,
2032            target_module_id,
2033            "open_admission_full",
2034            (in_flight, limit),
2035            format!(
2036                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
2037            ),
2038        )
2039    }
2040
2041    fn route_open_target_capacity_refusal(
2042        &self,
2043        ctx: &RouteCtx,
2044        caller: &RouteOpenCaller,
2045        frame: &Frame,
2046        target_module_id: &str,
2047        in_flight: usize,
2048    ) -> Result<Frame, RouterError> {
2049        self.route_open_admission_refusal_frame(
2050            ctx,
2051            caller,
2052            frame,
2053            target_module_id,
2054            "target_binds_full",
2055            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
2056            format!(
2057                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
2058            ),
2059        )
2060    }
2061
2062    /// Admission pressure clears as existing binds settle, so its refusal must
2063    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
2064    /// `module_reloading`, `module_warming`, `target_unavailable`, or
2065    /// `module_timeout`. `target_unavailable` is honest for an attempt that
2066    /// cannot currently reach its target; `module_timeout` would falsely claim
2067    /// that a wait expired. A new, cleaner code would be terminal to deployed
2068    /// clients, so it requires a client-tolerance rollout before daemon emission.
2069    #[allow(clippy::too_many_arguments)]
2070    fn route_open_admission_refusal_frame(
2071        &self,
2072        ctx: &RouteCtx,
2073        caller: &RouteOpenCaller,
2074        frame: &Frame,
2075        target_module_id: &str,
2076        reason: &'static str,
2077        (in_flight, limit): (usize, usize),
2078        message: impl Into<String>,
2079    ) -> Result<Frame, RouterError> {
2080        let code = error_codes::TARGET_UNAVAILABLE;
2081        self.counters.increment_route_open_refused(code);
2082        info!(
2083            target: "control",
2084            code,
2085            reason,
2086            module_id = ?target_module_id,
2087            connection_id = ctx.connection_id.get(),
2088            principal = %caller.principal,
2089            scope = %caller.scope,
2090            harness = %caller.harness,
2091            in_flight,
2092            limit,
2093            "route.open refused"
2094        );
2095        control_error_frame(frame, code, message.into())
2096    }
2097
2098    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
2099    ///
2100    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
2101    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
2102    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
2103    #[cfg(test)]
2104    pub fn handle_control(
2105        &self,
2106        connection_id: ConnectionId,
2107        frame: Frame,
2108    ) -> Result<Vec<Frame>, RouterError> {
2109        match frame.header.ty {
2110            FrameType::Ping => Ok(vec![pong(&frame)?]),
2111            FrameType::Hello => self.handle_hello(connection_id, None, frame),
2112            FrameType::Goodbye => self.handle_goodbye(connection_id),
2113            ty => Ok(vec![control_error_frame(
2114                &frame,
2115                "unsupported_control_frame",
2116                format!("unsupported channel-0 frame {ty:?}"),
2117            )?]),
2118        }
2119    }
2120
2121    pub async fn handle_control_frame(
2122        &self,
2123        ctx: &RouteCtx,
2124        frame: Frame,
2125    ) -> Result<Vec<Frame>, RouterError> {
2126        self.handle_control_frame_timed(ctx, frame, None).await
2127    }
2128
2129    #[cfg(any(test, feature = "test-support"))]
2130    pub fn with_test_operator_app_policy(
2131        mut self,
2132        policy: crate::operator_apps::TestOperatorAppPolicy,
2133    ) -> Self {
2134        self.operator_app_policy = policy.into();
2135        self
2136    }
2137
2138    /// Inject the Windows signature check for tests. The injected check
2139    /// answers the verified version string or the rejection reason; the
2140    /// daemon enforces the floor itself on the returned version.
2141    #[cfg(all(windows, any(test, feature = "test-support")))]
2142    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
2143        self.windows_verify = Some(verify);
2144        self
2145    }
2146
2147    /// Record which pids the daemon would flash for `already_running`.
2148    #[cfg(all(windows, any(test, feature = "test-support")))]
2149    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
2150        self.windows_flash = Some(flash);
2151        self
2152    }
2153
2154    /// Inject a tracking failure for tests: makes `track_launched_process`
2155    /// fail so a test can prove a launch that cannot be tracked is stopped,
2156    /// never left running.
2157    #[cfg(all(windows, any(test, feature = "test-support")))]
2158    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2159        self.windows_track = Some(track);
2160        self
2161    }
2162
2163    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2164        self.local_connections
2165            .lock()
2166            .unwrap_or_else(|p| p.into_inner())
2167            .insert(connection);
2168    }
2169
2170    // Keep the connection-level delivery decision shared with route.bind. The
2171    // target's capability opt-in is separate from recognition of the caller.
2172    fn connection_operator_app(
2173        &self,
2174        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2175    ) -> Option<subc_protocol::peer::OperatorApp> {
2176        stamp
2177            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2178            .map(|stamp| stamp.app.clone())
2179    }
2180
2181    pub(crate) fn record_observed_peer(
2182        &self,
2183        connection: ConnectionId,
2184        peer: subc_os::local_peer::ObservedPeer,
2185    ) {
2186        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2187        let peer = match peer {
2188            OsPeer::Unobserved => ObservedPeer::unobserved(),
2189            OsPeer::Observed(peer) => {
2190                let observed = match peer.user {
2191                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2192                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2193                };
2194                observed
2195                    .with_exe(
2196                        peer.exe
2197                            .and_then(|path| path.into_os_string().into_string().ok()),
2198                    )
2199                    .with_signing_id(peer.signing_id)
2200            }
2201        };
2202        self.observed_peers
2203            .lock()
2204            .unwrap_or_else(|p| p.into_inner())
2205            .insert(connection, peer);
2206    }
2207
2208    pub(crate) fn record_caller_endpoints(
2209        &self,
2210        connection: ConnectionId,
2211        endpoints: Option<(SocketAddr, SocketAddr)>,
2212    ) {
2213        let mut callers = self
2214            .caller_endpoints
2215            .lock()
2216            .unwrap_or_else(|p| p.into_inner());
2217        callers.remove(&connection);
2218        if let Some(endpoints) = endpoints {
2219            callers.insert(connection, endpoints);
2220        }
2221    }
2222
2223    #[cfg(test)]
2224    pub(crate) fn with_caller_lookup_for_test(
2225        mut self,
2226        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2227    ) -> Self {
2228        self.caller_lookup = Some(Arc::new(lookup));
2229        self
2230    }
2231
2232    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2233        let endpoints = self
2234            .caller_endpoints
2235            .lock()
2236            .unwrap_or_else(|p| p.into_inner())
2237            .get(&connection)
2238            .copied();
2239        #[cfg(test)]
2240        let lookup = self.caller_lookup.clone();
2241        tokio::task::spawn_blocking(move || {
2242            #[cfg(test)]
2243            if let Some(lookup) = lookup {
2244                return lookup(endpoints);
2245            }
2246            endpoints
2247                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2248                .unwrap_or_default()
2249        })
2250        .await
2251        .unwrap_or_default()
2252    }
2253
2254    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2255        frame.header.channel == 0
2256            && frame.header.ty == FrameType::Request
2257            && self
2258                .forwarding
2259                .module_endpoint_for_connection(ctx.connection_id)
2260                .is_ok_and(|endpoint| endpoint.is_none())
2261            && parse_client_control_request(&frame.body)
2262                .ok()
2263                .is_some_and(|request| privileged_operation(&request).is_some())
2264    }
2265
2266    pub(crate) async fn handle_control_frame_timed(
2267        &self,
2268        ctx: &RouteCtx,
2269        frame: Frame,
2270        dispatch_started_at: Option<StdInstant>,
2271    ) -> Result<Vec<Frame>, RouterError> {
2272        let first = ctx.egress.first_ingress_frame();
2273        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2274            .await
2275    }
2276
2277    pub(crate) async fn handle_control_frame_ingress(
2278        &self,
2279        ctx: &RouteCtx,
2280        frame: Frame,
2281        dispatch_started_at: Option<StdInstant>,
2282        first: bool,
2283    ) -> Result<Vec<Frame>, RouterError> {
2284        if ctx.egress.ingress_terminal() {
2285            return Ok(Vec::new());
2286        }
2287        #[cfg(test)]
2288        self.claims.record_dispatch(frame.header.corr);
2289        let claim_binding = self.claims.binding(ctx.connection_id);
2290        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2291            && claim_binding
2292                .as_ref()
2293                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2294        .then(|| self.prefix_hello_attempt(ctx));
2295        if claim_binding
2296            .as_ref()
2297            .is_some_and(|binding| binding.prefix_module_id().is_some())
2298        {
2299            let registered = self
2300                .forwarding
2301                .module_endpoint_for_connection(ctx.connection_id)
2302                .map_err(RouterError::Forwarding)?
2303                .is_some();
2304            if !registered && frame.header.ty != FrameType::Hello {
2305                return self
2306                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2307                    .await;
2308            }
2309            if registered && frame.header.ty == FrameType::Goodbye {
2310                ctx.egress.terminate_ingress();
2311                let result = self.handle_goodbye(ctx.connection_id);
2312                self.claims.connection_closed(ctx.connection_id);
2313                self.request_refusal_close(
2314                    ctx.connection_id,
2315                    Some(&ctx.egress),
2316                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2317                );
2318                return result;
2319            }
2320            if registered && frame.header.ty == FrameType::Request {
2321                let allowed =
2322                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2323                        matches!(
2324                            probe.op.as_str(),
2325                            "catalog.update"
2326                                | "catalog.update_role_declarations"
2327                                | "scope.describe"
2328                                | "scope.watch"
2329                                | "supervisor.live_roots"
2330                                | "activity.record"
2331                        )
2332                    });
2333                if !allowed {
2334                    return Ok(vec![control_error_frame(
2335                        &frame,
2336                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2337                        "prefix registrations have only brokered module operations",
2338                    )?]);
2339                }
2340            }
2341            if registered
2342                && frame.header.ty == FrameType::Push
2343                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2344                    .is_ok_and(|probe| probe.op == "route.status")
2345            {
2346                return Ok(vec![control_error_frame(
2347                    &frame,
2348                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2349                    "prefix registrations may push only route.status for routes they serve",
2350                )?]);
2351            }
2352        }
2353        match frame.header.ty {
2354            FrameType::Ping => Ok(vec![pong(&frame)?]),
2355            FrameType::Hello => {
2356                if claim_binding
2357                    .as_ref()
2358                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2359                {
2360                    return self
2361                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2362                        .await;
2363                }
2364                // Resolved once, here: the blocking HELLO below may outlive this
2365                // reader and run after cleanup has forgotten the channel, and it
2366                // must still be judged as this channel's HELLO.
2367                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2368                if let Some(spawn) = &channel_spawn {
2369                    spawn.wait_launch().await;
2370                    // Refused launches close the channel. Leave their pending
2371                    // HELLO unanswered instead of racing a reply against shutdown.
2372                    if !spawn.launch_ready() {
2373                        ctx.egress.terminate_ingress();
2374                        return Ok(Vec::new());
2375                    }
2376                    #[cfg(test)]
2377                    self.pause_hello_ingress_for_test().await;
2378                } else if claim_binding.is_none() {
2379                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2380                        if let (Some(module), Some(nonce)) = (
2381                            hello
2382                                .get("manifest")
2383                                .and_then(|value| value.get("module_id"))
2384                                .and_then(|value| value.as_str()),
2385                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2386                        ) {
2387                            if !self
2388                                .config_runtime
2389                                .as_ref()
2390                                .is_some_and(|owner| owner.module_is_gated(module))
2391                                && !self.supervisor.wait_program_binding(module, nonce).await
2392                            {
2393                                self.request_refusal_close(
2394                                    ctx.connection_id,
2395                                    Some(&ctx.egress),
2396                                    CloseReason::new(
2397                                        "program_refused",
2398                                        "the spawned program binding failed",
2399                                    ),
2400                                );
2401                                return Ok(vec![control_error_frame(
2402                                    &frame,
2403                                    if self
2404                                        .config_runtime
2405                                        .as_ref()
2406                                        .is_some_and(|owner| owner.is_recovering())
2407                                    {
2408                                        "config_gated"
2409                                    } else {
2410                                        "program_refused"
2411                                    },
2412                                    "the spawned program binding failed",
2413                                )?]);
2414                            }
2415                        }
2416                    }
2417                }
2418                let handler = self.clone();
2419                let connection = ctx.connection_id;
2420                let egress = ctx.egress.clone();
2421                let correlation = frame.header.corr;
2422                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2423                let span = tracing::Span::current();
2424                let hello_binding = claim_binding.clone();
2425                let replies = tokio::task::spawn_blocking(move || {
2426                    tracing::dispatcher::with_default(&dispatcher, || {
2427                        span.in_scope(|| {
2428                            handler.handle_hello_checked(
2429                                connection,
2430                                Some(egress),
2431                                frame,
2432                                true,
2433                                hello_binding,
2434                                channel_spawn,
2435                            )
2436                        })
2437                    })
2438                })
2439                .await
2440                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2441                #[cfg(test)]
2442                if prefix_attempt.is_some() {
2443                    self.claims.pause_prefix_commit_for_test(false).await;
2444                }
2445                if let Some(attempt) = &mut prefix_attempt {
2446                    let accepted = !replies
2447                        .iter()
2448                        .any(|reply| reply.header.ty == FrameType::Error)
2449                        && self
2450                            .registry
2451                            .get_module_by_connection(ctx.connection_id)
2452                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2453                            .is_some();
2454                    if accepted {
2455                        attempt.accepted = true;
2456                    } else {
2457                        ctx.egress.terminate_ingress();
2458                        for reply in replies {
2459                            ctx.egress.send_flushed(reply).await?;
2460                        }
2461                        return Ok(Vec::new());
2462                    }
2463                }
2464                Ok(replies)
2465            }
2466            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2467            FrameType::Cancel => {
2468                // Channel-0 cancellation withdraws approvals and subscriptions
2469                // and fences pending agent declarations;
2470                // successful cancellation has no ordinary reply.
2471                // A config Apply may also own an OS prompt. Cancel that prompt
2472                // before config cancellation can report the request handled.
2473                if self
2474                    .agent_declarations
2475                    .cancel(ctx.connection_id, frame.header.corr)
2476                    || self
2477                        .forwarding
2478                        .operator_confirms()
2479                        .cancel(ctx.connection_id, frame.header.corr)
2480                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2481                    || self
2482                        .supervisor
2483                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2484                    || self.cancel_activity_subscription(ctx, &frame)?
2485                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2486                    || self
2487                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2488                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2489                {
2490                    Ok(Vec::new())
2491                } else {
2492                    Ok(vec![control_error_frame(
2493                        &frame,
2494                        "unknown_subscription",
2495                        "no subscription has this correlation id",
2496                    )?])
2497                }
2498            }
2499            FrameType::Request => {
2500                // This additive operation is not part of the existing exhaustive
2501                // module-control enum. Probe the op before decoding that enum.
2502                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2503                if let Some(probe) = &op {
2504                    self.record_control_usage(ctx.connection_id, &probe.op);
2505                }
2506                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2507                if let Some(refusal) = self
2508                    .recovery_request_refusal(
2509                        ctx,
2510                        &frame,
2511                        op.as_ref().map(|probe| probe.op.as_str()),
2512                    )
2513                    .await?
2514                {
2515                    if claim_present {
2516                        self.reclaim_presented_expiry(&frame);
2517                        return self
2518                            .refuse_claim_connection(ctx, &frame, "config_gated")
2519                            .await;
2520                    }
2521                    return Ok(vec![refusal]);
2522                }
2523                if claim_present {
2524                    return self.handle_claim_present(ctx, &frame, first).await;
2525                }
2526                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2527                    return self.handle_claim_mint(ctx, &frame).await;
2528                }
2529                if let Some(refusal) = self.registration_operation_refusal(
2530                    ctx,
2531                    &frame,
2532                    op.as_ref().map(|probe| probe.op.as_str()),
2533                )? {
2534                    return Ok(vec![refusal]);
2535                }
2536                if op
2537                    .as_ref()
2538                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2539                {
2540                    return self.handle_catalog_watch(ctx, frame);
2541                }
2542                if op
2543                    .as_ref()
2544                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2545                {
2546                    return self.handle_scope_watch(ctx, frame);
2547                }
2548                if op
2549                    .as_ref()
2550                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2551                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2552                        .unwrap_or(false)
2553                {
2554                    return Ok(vec![control_error_frame(
2555                        &frame,
2556                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2557                        "provider_declarations are fixed at HELLO; restart the module to change them",
2558                    )?]);
2559                }
2560                if let Some(probe) = op
2561                    .as_ref()
2562                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2563                {
2564                    return self
2565                        .handle_module_config_request(ctx, frame, &probe.op)
2566                        .await;
2567                }
2568                if op
2569                    .as_ref()
2570                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2571                {
2572                    return self.handle_config_gate_request(ctx, frame).await;
2573                }
2574                if op
2575                    .as_ref()
2576                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2577                {
2578                    return self.handle_activity_record(ctx, frame).await;
2579                }
2580                if op.as_ref().is_some_and(|probe| {
2581                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2582                }) {
2583                    return self.handle_activity_read(ctx, frame).await;
2584                }
2585                if op
2586                    .as_ref()
2587                    .is_some_and(|probe| probe.op == "operator.confirm")
2588                {
2589                    return self.handle_operator_confirm(ctx, frame).await;
2590                }
2591                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2592                    return self
2593                        .observe_control_wait(
2594                            ctx,
2595                            None,
2596                            ops::APP_OPEN,
2597                            self.handle_app_open(ctx, frame),
2598                        )
2599                        .await;
2600                }
2601                if op
2602                    .as_ref()
2603                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2604                {
2605                    return self.handle_connection_describe(ctx, frame).await;
2606                }
2607                if op
2608                    .as_ref()
2609                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2610                {
2611                    return self.handle_scope_served_by(ctx.connection_id, frame);
2612                }
2613                if self
2614                    .forwarding
2615                    .module_endpoint_for_connection(ctx.connection_id)
2616                    .map_err(RouterError::Forwarding)?
2617                    .is_some()
2618                {
2619                    if !is_known_module_request_op(&frame.body) {
2620                        return Ok(vec![control_error_frame(
2621                            &frame,
2622                            "unsupported_control_frame",
2623                            "module-originated channel-0 REQUEST is not supported",
2624                        )?]);
2625                    }
2626                    let request = match parse_module_control_request_from_module(&frame.body) {
2627                        Ok(request) => request,
2628                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2629                            return Ok(vec![control_error_frame(
2630                                &frame,
2631                                "unsupported_control_frame",
2632                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2633                            )?])
2634                        }
2635                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2636                            return Ok(vec![control_error_frame(
2637                                &frame,
2638                                "invalid_control_body",
2639                                format!("malformed module control body: {err}"),
2640                            )?])
2641                        }
2642                    };
2643                    let op = module_control_request_op(&request);
2644                    let corr = frame.header.corr;
2645                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2646                    if let ModuleControlRequestFromModule::AgentCommands {
2647                        started,
2648                        finished,
2649                        known,
2650                    } = request
2651                    {
2652                        return self
2653                            .agent_declarations
2654                            .enqueue(
2655                                self,
2656                                ctx,
2657                                frame,
2658                                crate::resource_totals::Declaration {
2659                                    started,
2660                                    finished,
2661                                    known,
2662                                },
2663                            )
2664                            .await;
2665                    }
2666                    let result =
2667                        self.handle_module_control_request(ctx.connection_id, frame, request);
2668                    log_slow_control_dispatch(
2669                        dispatch_started_at,
2670                        op,
2671                        ctx.connection_id,
2672                        corr,
2673                        None,
2674                    );
2675                    return result;
2676                }
2677
2678                if is_known_module_request_op(&frame.body) {
2679                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2680                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2681                    let code = if is_agents {
2682                        "not_supervised"
2683                    } else if op
2684                        .as_ref()
2685                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2686                    {
2687                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2688                    } else {
2689                        "not_registered"
2690                    };
2691                    return Ok(vec![control_error_frame(
2692                        &frame,
2693                        code,
2694                        "module-originated control requests require the module's own registered connection",
2695                    )?]);
2696                }
2697
2698                let request = match parse_client_control_request(&frame.body) {
2699                    Ok(request) => request,
2700                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2701                        return Ok(vec![control_error_frame(
2702                            &frame,
2703                            "unknown_control_op",
2704                            format!("unknown client control op: {err}"),
2705                        )?])
2706                    }
2707                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2708                        return Ok(vec![control_error_frame(
2709                            &frame,
2710                            "invalid_control_body",
2711                            format!("malformed client control body: {err}"),
2712                        )?])
2713                    }
2714                };
2715                let op = client_control_request_op(&request);
2716                let corr = frame.header.corr;
2717                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2718                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2719                #[cfg(test)]
2720                if let Some(delay) = self.control_dispatch_delay {
2721                    tokio::time::sleep(delay).await;
2722                }
2723                let result = self
2724                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2725                    .await;
2726                if let Some(timings) = route_open_timings.as_mut() {
2727                    timings.finish();
2728                }
2729                log_slow_control_dispatch(
2730                    dispatch_started_at,
2731                    op,
2732                    ctx.connection_id,
2733                    corr,
2734                    route_open_timings.as_ref(),
2735                );
2736                result
2737            }
2738            FrameType::Push => {
2739                let Some(endpoint) = self
2740                    .forwarding
2741                    .module_endpoint_for_connection(ctx.connection_id)
2742                    .map_err(RouterError::Forwarding)?
2743                else {
2744                    return Ok(vec![control_error_frame(
2745                        &frame,
2746                        "unsupported_control_frame",
2747                        "client-originated channel-0 PUSH is not supported",
2748                    )?]);
2749                };
2750                self.handle_status_update(endpoint, frame)
2751            }
2752            FrameType::Response | FrameType::Error
2753                if self
2754                    .forwarding
2755                    .module_endpoint_for_connection(ctx.connection_id)
2756                    .map_err(RouterError::Forwarding)?
2757                    .is_some() =>
2758            {
2759                self.handle_module_relay_response(ctx.connection_id, frame)
2760            }
2761            ty => Ok(vec![control_error_frame(
2762                &frame,
2763                "unsupported_control_frame",
2764                format!("unsupported channel-0 frame {ty:?}"),
2765            )?]),
2766        }
2767    }
2768
2769    #[cfg(test)]
2770    fn pause_cleanup_for_test(&self, stage: u8) {
2771        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2772        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2773            let (_, (reached, release)) = slot.take().unwrap();
2774            drop(slot);
2775            let _ = reached.send(());
2776            let _ = release.recv_timeout(Duration::from_secs(5));
2777        }
2778    }
2779
2780    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2781    /// right after the nonce is resolved.
2782    #[cfg(all(test, unix, feature = "test-support"))]
2783    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2784        *self
2785            .after_nonce_attestation
2786            .lock()
2787            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2788    }
2789
2790    #[cfg(test)]
2791    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2792        let hook = self
2793            .after_nonce_attestation
2794            .lock()
2795            .unwrap_or_else(|p| p.into_inner())
2796            .take();
2797        if let Some(hook) = hook {
2798            hook();
2799        }
2800    }
2801
2802    #[cfg(test)]
2803    async fn pause_hello_ingress_for_test(&self) {
2804        let pause = self
2805            .hello_ingress_pause
2806            .lock()
2807            .unwrap_or_else(|p| p.into_inner())
2808            .take();
2809        if let Some((reached, release)) = pause {
2810            let _ = reached.send(());
2811            let _ = release.await;
2812        }
2813    }
2814
2815    pub fn cleanup_connection(
2816        &self,
2817        connection_id: ConnectionId,
2818    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2819        // The server loop joins its offloaded request tasks (route opens,
2820        // privileged requests and activity reads) before this cleanup runs, and
2821        // inline dispatch has ended. Two kinds of work are not joined. Agent
2822        // command declarations run on their queue's detached worker, so the
2823        // queue is closed first: every declaration still queued or validating
2824        // has its commit fence cancelled before anything below can change how
2825        // the connection resolves. A HELLO whose reader was dropped keeps
2826        // running on its blocking thread. It carries the channel spawn its
2827        // reader resolved at ingress instead of re-reading the index forgotten
2828        // below, so it is still judged as that channel's HELLO: the retired
2829        // spawn refuses it before it records anything, and a channel HELLO
2830        // never records a launch nonce, so it cannot leave this connection any
2831        // nonce authority.
2832        self.agent_declarations.close(connection_id);
2833        self.close_catalog_subscriptions(connection_id);
2834        self.close_config_settings_subscriptions(connection_id);
2835        self.close_scope_subscriptions(connection_id);
2836        #[cfg(test)]
2837        self.pause_cleanup_for_test(0);
2838        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2839            spawn.retire_registration_channel();
2840        }
2841        self.supervisor
2842            .forget_registration_connection(connection_id);
2843        #[cfg(test)]
2844        self.pause_cleanup_for_test(1);
2845        self.local_connections
2846            .lock()
2847            .unwrap_or_else(|p| p.into_inner())
2848            .remove(&connection_id);
2849        self.caller_endpoints
2850            .lock()
2851            .unwrap_or_else(|p| p.into_inner())
2852            .remove(&connection_id);
2853        self.build_class_warned
2854            .lock()
2855            .unwrap_or_else(|p| p.into_inner())
2856            .remove(&connection_id);
2857        // Retire the capture before its published facts so an in-flight
2858        // verification cannot recreate them after cleanup.
2859        self.captured_peers
2860            .lock()
2861            .unwrap_or_else(|p| p.into_inner())
2862            .remove(&connection_id);
2863        self.observed_peers
2864            .lock()
2865            .unwrap_or_else(|p| p.into_inner())
2866            .remove(&connection_id);
2867        self.config_desktop_stamps
2868            .lock()
2869            .unwrap_or_else(|p| p.into_inner())
2870            .remove(&connection_id);
2871        self.operator_apps
2872            .lock()
2873            .unwrap_or_else(|p| p.into_inner())
2874            .remove(&connection_id);
2875        self.forwarding
2876            .operator_confirms()
2877            .connection_closed(connection_id);
2878        let cleanup = self.cleanup_connection_with_end_reason(
2879            connection_id,
2880            RegistrationEndReason::ConnectionClosed,
2881        );
2882        // A draining writer can still be reached by a route until forwarding
2883        // cleanup finishes. Keep its claim sink visible to launch retirement.
2884        self.claims.connection_closed(connection_id);
2885        cleanup
2886    }
2887
2888    fn cleanup_connection_with_end_reason(
2889        &self,
2890        connection_id: ConnectionId,
2891        requested_reason: RegistrationEndReason,
2892    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2893        #[cfg(test)]
2894        if let Some(pause) = self
2895            .activity_request_pause
2896            .lock()
2897            .unwrap()
2898            .as_ref()
2899            .filter(|pause| pause.connection == connection_id)
2900        {
2901            pause
2902                .cleanup_started
2903                .store(true, std::sync::atomic::Ordering::Release);
2904        }
2905        if let Some(runtime) = &self.config_runtime {
2906            runtime.disconnected(connection_id);
2907        }
2908        self.agent_declarations.close(connection_id);
2909        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2910            self.registry
2911                .get_module_by_connection(connection_id)?
2912                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2913                .and_then(|module| module.registration_end_reason().ok().flatten())
2914                .unwrap_or(requested_reason)
2915        } else {
2916            requested_reason
2917        };
2918        let crash_closed = self
2919            .registry
2920            .get_module_by_connection(connection_id)?
2921            .and_then(|registration| {
2922                self.forwarding
2923                    .module_endpoint_for_connection(connection_id)
2924                    .ok()
2925                    .flatten()
2926                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2927                    .map(|routes| (registration.manifest.module_id, routes))
2928            });
2929        let crash_closed = crash_closed.map(|(module_id, routes)| {
2930            let terminal = match self.supervisor.get(&module_id) {
2931                None => false,
2932                Some(module) => match module.will_recover_after_connection_loss() {
2933                    Ok(will_recover) => !will_recover,
2934                    Err(err) => {
2935                        warn!(
2936                            %module_id,
2937                            error = %err,
2938                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2939                        );
2940                        false
2941                    }
2942                },
2943            };
2944            // The forwarding table gates all providers at the start of daemon
2945            // shutdown, before their connections are closed. An ordinary
2946            // module disconnect still reports crash if that gate is not set.
2947            let (reason, drained) = match self
2948                .forwarding
2949                .daemon_drain_result_for_connection(connection_id)
2950            {
2951                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
2952                Ok(None) => (RouteCloseReason::Crash, false),
2953                Err(err) => {
2954                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
2955                    (RouteCloseReason::Crash, false)
2956                }
2957            };
2958            (module_id, routes, reason, drained, terminal)
2959        });
2960        let registrations = self.deregister_connection(connection_id, end_reason);
2961        // Read before teardown: the spawn whose registration this connection
2962        // was. Its registration ending is an authority change for it.
2963        let ended_authority = self
2964            .forwarding
2965            .target_authority_for_connection(connection_id)
2966            .ok()
2967            .flatten();
2968        let cleanup = if crash_closed.is_some() {
2969            self.forwarding.cleanup_connection_counted(connection_id)
2970        } else {
2971            // A module connection's teardown needs the count of abandoned
2972            // route.bind relays for its route.closed notice below. Any other
2973            // connection, such as a client's, sends no such notice and needs
2974            // only its routes released, so it uses the route-only wrapper and
2975            // reports zero.
2976            self.forwarding
2977                .cleanup_connection(connection_id)
2978                .map(|released| crate::forwarding::ConnectionCleanup {
2979                    released,
2980                    abandoned_relays: 0,
2981                })
2982        };
2983        // The route.closed push waits for forwarding teardown because only
2984        // teardown knows how many pending route.bind relays it aborted. It still
2985        // goes out before the GOODBYEs for the released routes, and its targets
2986        // were captured above, before teardown removed those routes.
2987        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
2988            let abandoned = cleanup
2989                .as_ref()
2990                .map_or(0, |cleanup| cleanup.abandoned_relays);
2991            send_route_control_pushes(
2992                &self.forwarding,
2993                routes,
2994                ClientControlPush::RouteClosed {
2995                    module_id,
2996                    channels: Vec::new(),
2997                    reason,
2998                    drained,
2999                    abandoned,
3000                    excluded_subscriptions: 0,
3001                    terminal: Some(terminal),
3002                },
3003            );
3004        }
3005        if let Ok(cleanup) = cleanup {
3006            self.emit_route_goodbyes(cleanup.released);
3007        }
3008        if let Some(record) = ended_authority {
3009            self.change_spawn_authority(&record);
3010        }
3011        // Signal the registration-release watch only now that BOTH registry and
3012        // forwarding teardown are done, so a supervisor waiting to spawn a
3013        // replacement never observes release while old routes still exist.
3014        if matches!(&registrations, Ok(r) if !r.is_empty()) {
3015            crate::supervise::notify_registration_release();
3016            self.capability_evaluator.wake_deadline_loop();
3017            self.refresh_capability_requirements();
3018        }
3019        self.supervisor.remove_spawn_subscribers(connection_id);
3020        self.activity_streams
3021            .lock()
3022            .unwrap_or_else(|p| p.into_inner())
3023            .retain(|(id, _), task| {
3024                if *id == connection_id {
3025                    task.abort();
3026                    false
3027                } else {
3028                    true
3029                }
3030            });
3031        // Sync authority dies with its connection, so the owner's next
3032        // connection can take it; the owner's scopes stay as they are.
3033        self.hello_launch_nonces
3034            .lock()
3035            .unwrap_or_else(|poisoned| poisoned.into_inner())
3036            .forget(connection_id);
3037        self.scopes
3038            .write()
3039            .unwrap_or_else(|poisoned| poisoned.into_inner())
3040            .release_connection(connection_id);
3041        registrations
3042    }
3043
3044    pub(crate) fn handle_route_goodbye(
3045        &self,
3046        connection_id: ConnectionId,
3047        route_channel: u16,
3048        route_epoch: u32,
3049    ) -> Result<bool, RouterError> {
3050        debug!(
3051            connection_id = connection_id.get(),
3052            route_channel, route_epoch, "handling route GOODBYE"
3053        );
3054        let RouteRelease::Removed(released_route) = self
3055            .forwarding
3056            .release_client_route(connection_id, route_channel, route_epoch)
3057            .map_err(RouterError::Forwarding)?
3058        else {
3059            return Ok(false);
3060        };
3061        self.emit_route_goodbyes(vec![released_route]);
3062        Ok(true)
3063    }
3064
3065    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
3066        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
3067    }
3068
3069    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
3070    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
3071    /// own commit failed after the module had already accepted). Without this, a
3072    /// module that accepts late keeps a binding subc has torn down, so a later
3073    /// frame on that module channel could misdeliver if the channel is reused.
3074    ///
3075    /// Never closes the shared module connection on failure: a dropped notification
3076    /// only wastes a bounded amount of warm module-side state, which the module's
3077    /// own idle reaper reclaims. Only call this once the route.bind relay was
3078    /// actually enqueued to the module — if the relay send itself failed, the
3079    /// module never created a binding and there is nothing to tear down.
3080    fn send_abandoned_route_bind_goodbye(
3081        &self,
3082        module_sink: &crate::FrameSink,
3083        negotiated_ver: u8,
3084        module_channel: u16,
3085        module_epoch: u32,
3086    ) {
3087        let frame = match Frame::build_with_version(
3088            negotiated_ver,
3089            FrameType::Goodbye,
3090            control_flags(),
3091            module_channel,
3092            module_epoch,
3093            0,
3094            Vec::new(),
3095        ) {
3096            Ok(frame) => frame,
3097            Err(err) => {
3098                warn!(
3099                    route_channel = module_channel,
3100                    error = %err,
3101                    "failed to build GOODBYE for abandoned route.bind"
3102                );
3103                return;
3104            }
3105        };
3106        crate::forwarding::send_module_route_goodbye(
3107            &self.counters,
3108            module_sink,
3109            frame,
3110            None,
3111            "abandoned route.bind",
3112        );
3113    }
3114
3115    #[cfg(test)]
3116    fn handle_hello(
3117        &self,
3118        connection_id: ConnectionId,
3119        egress: Option<crate::router::FrameSink>,
3120        frame: Frame,
3121    ) -> Result<Vec<Frame>, RouterError> {
3122        let binding = self.claims.binding(connection_id);
3123        let channel_spawn = self.supervisor.registration_spawn(connection_id);
3124        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
3125    }
3126
3127    fn handle_hello_checked(
3128        &self,
3129        connection_id: ConnectionId,
3130        sink: Option<crate::FrameSink>,
3131        frame: Frame,
3132        wait_for_gate: bool,
3133        prefix_binding: Option<claims::ClaimBinding>,
3134        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3135    ) -> Result<Vec<Frame>, RouterError> {
3136        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
3137        #[cfg(test)]
3138        if prefix_binding.is_some() {
3139            self.claims.pause_prefix_hello_for_test(5);
3140            match self.claims.take_prefix_hello_failure_for_test() {
3141                Some("error") => {
3142                    return Err(RouterError::backend(
3143                        0,
3144                        frame.header.corr,
3145                        "injected HELLO failure",
3146                    ))
3147                }
3148                Some("panic") => panic!("injected HELLO task panic"),
3149                _ => {}
3150            }
3151        }
3152        if let Some(binding) = &prefix_binding {
3153            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3154            let module = value
3155                .as_ref()
3156                .and_then(|value| value["manifest"]["module_id"].as_str());
3157            if !binding.admit_prefix_hello(module)
3158                || !self.prefix_binding_live(binding, connection_id)
3159                || !module.is_some_and(|module| {
3160                    self.supervisor
3161                        .prefix_claim_authorized(&binding.registration.module_id, module)
3162                })
3163                || binding.registration.check().is_err()
3164            {
3165                return Ok(vec![control_error_frame(
3166                    &frame,
3167                    "claim_prefix_refused",
3168                    "HELLO must name the prefix claim's exact module id once",
3169                )?]);
3170            }
3171        }
3172        struct RefuseUnregisteredChannel {
3173            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3174            sink: Option<crate::FrameSink>,
3175        }
3176        impl Drop for RefuseUnregisteredChannel {
3177            fn drop(&mut self) {
3178                if let Some(spawn) = &self.spawn {
3179                    if !spawn.registered() {
3180                        if let Some(sink) = &self.sink {
3181                            sink.terminate_ingress();
3182                        }
3183                        spawn.retire_registration_channel();
3184                    }
3185                }
3186            }
3187        }
3188        let _channel_attempt = RefuseUnregisteredChannel {
3189            spawn: channel_spawn.clone(),
3190            sink: sink.clone(),
3191        };
3192        if let Some(spawn) = &channel_spawn {
3193            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3194            if let Err(code) = spawn.admit_hello(
3195                value
3196                    .as_ref()
3197                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3198            ) {
3199                return Ok(vec![control_error_frame(
3200                    &frame,
3201                    code,
3202                    "registration channel HELLO refused",
3203                )?]);
3204            }
3205        }
3206        debug!(
3207            connection_id = connection_id.get(),
3208            corr = frame.header.corr,
3209            "handling HELLO"
3210        );
3211        // A module connection has one identity for its entire lifetime. A second
3212        // registration would leave the old registry owner behind while replacing
3213        // its forwarding endpoint and launch nonce.
3214        if self
3215            .registry
3216            .get_module_by_connection(connection_id)
3217            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3218            .is_some()
3219        {
3220            return Ok(vec![control_error_frame(
3221                &frame,
3222                "invalid_hello",
3223                "connection is already registered as a module",
3224            )?]);
3225        }
3226        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3227            Ok(value) => value,
3228            Err(err) => {
3229                return Ok(vec![control_error_frame(
3230                    &frame,
3231                    "invalid_hello",
3232                    format!("malformed HELLO body: {err}"),
3233                )?])
3234            }
3235        };
3236        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3237            return Ok(vec![control_error_frame(
3238                &frame,
3239                error_codes::INVALID_PROVIDER_DECLARATIONS,
3240                detail,
3241            )?]);
3242        }
3243        if let Some(module) = hello_value
3244            .get("manifest")
3245            .and_then(|value| value.get("module_id"))
3246            .and_then(|value| value.as_str())
3247        {
3248            let recovering = self
3249                .config_runtime
3250                .as_ref()
3251                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3252            // Defence in depth: RuntimeOwner::module_is_gated in
3253            // config_gate/admission.rs already gates every id during recovery.
3254            // A registration channel still never uses the nonce fallback.
3255            if recovering
3256                && channel_spawn.as_ref().is_none_or(|spawn| {
3257                    !self.supervisor.has_live_verified_channel_binding(spawn)
3258                        || spawn.check().is_err()
3259                })
3260                && !(channel_spawn.is_none()
3261                    && hello_value
3262                        .get("launch_nonce")
3263                        .and_then(|value| value.as_str())
3264                        .is_some_and(|nonce| {
3265                            self.supervisor.spawned_consumer_authorized(module, nonce)
3266                                && self
3267                                    .supervisor
3268                                    .has_live_verified_program_binding(module, nonce)
3269                        }))
3270            {
3271                return Ok(vec![control_error_frame(
3272                    &frame,
3273                    "config_gated",
3274                    "recovery admits only previously bound supervised launches",
3275                )?]);
3276            }
3277            if self
3278                .config_runtime
3279                .as_ref()
3280                .is_some_and(|owner| owner.module_is_gated(module))
3281                && (channel_spawn
3282                    .as_ref()
3283                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3284                    || self.config_runtime.as_ref().is_some_and(|owner| {
3285                        !recovering && owner.check_module_hold(module).is_err()
3286                    }))
3287            {
3288                return Ok(vec![control_error_frame(
3289                    &frame,
3290                    "reserved_module",
3291                    "a gated identity belongs only to its supervised child",
3292                )?]);
3293            }
3294        }
3295        if channel_spawn.is_none() {
3296            if let (Some(module), Some(nonce)) = (
3297                hello_value
3298                    .get("manifest")
3299                    .and_then(|value| value.get("module_id"))
3300                    .and_then(|value| value.as_str()),
3301                hello_value
3302                    .get("launch_nonce")
3303                    .and_then(|value| value.as_str()),
3304            ) {
3305                let binding = self.supervisor.has_program_binding_record(module, nonce);
3306                let required = self
3307                    .config_runtime
3308                    .as_ref()
3309                    .is_some_and(|owner| owner.module_is_gated(module));
3310                if let Some(error) = (binding || required)
3311                    .then(|| {
3312                        self.supervisor
3313                            .check_current_program_binding(module, nonce)
3314                            .err()
3315                    })
3316                    .flatten()
3317                {
3318                    let code = if error.code == "program_refused" {
3319                        "program_refused"
3320                    } else {
3321                        "config_delivery_deferred"
3322                    };
3323                    self.request_refusal_close(
3324                        connection_id,
3325                        sink.as_ref(),
3326                        CloseReason::new(code, error.detail.clone()),
3327                    );
3328                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3329                }
3330            }
3331        }
3332        if let Err(err) = validate_hello_display_name(&hello_value) {
3333            return Ok(vec![control_error_frame(
3334                &frame,
3335                "invalid_manifest",
3336                err.to_string(),
3337            )?]);
3338        }
3339        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3340            return Ok(vec![control_error_frame(
3341                &frame,
3342                "invalid_capability_grammar",
3343                err.to_string(),
3344            )?]);
3345        }
3346        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3347            return Ok(vec![control_error_frame(
3348                &frame,
3349                "invalid_manifest",
3350                err.to_string(),
3351            )?]);
3352        }
3353        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3354            return Ok(vec![control_error_frame(
3355                &frame,
3356                "invalid_event_declaration",
3357                err.to_string(),
3358            )?]);
3359        }
3360        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3361            return Ok(vec![control_error_frame(
3362                &frame,
3363                "invalid_manifest",
3364                err.to_string(),
3365            )?]);
3366        }
3367        if let Some(provenance) = hello_value
3368            .get("manifest")
3369            .and_then(|manifest| manifest.get("provenance"))
3370        {
3371            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3372                return Ok(vec![control_error_frame(
3373                    &frame,
3374                    "invalid_manifest",
3375                    format!("malformed manifest provenance: {err}"),
3376                )?]);
3377            }
3378        }
3379        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3380            let module_id = hello_value["manifest"]["module_id"]
3381                .as_str()
3382                .unwrap_or("<unknown>");
3383            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3384        }
3385        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3386            let module_id = hello_value
3387                .get("manifest")
3388                .and_then(|m| m.get("module_id"))
3389                .and_then(serde_json::Value::as_str)
3390                .unwrap_or("unknown");
3391            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3392        }
3393        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3394            let module_id = hello_value["manifest"]["module_id"]
3395                .as_str()
3396                .unwrap_or("<unknown>");
3397            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3398        }
3399        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3400            let module_id = hello_value["manifest"]["module_id"]
3401                .as_str()
3402                .unwrap_or("<unknown>");
3403            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3404        }
3405        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3406            Ok(hello) => hello,
3407            Err(err) => {
3408                return Ok(vec![control_error_frame(
3409                    &frame,
3410                    "invalid_hello",
3411                    format!("malformed HELLO body: {err}"),
3412                )?])
3413            }
3414        };
3415
3416        if hello.protocol_ver != hello.manifest.protocol_ver {
3417            return Ok(vec![control_error_frame(
3418                &frame,
3419                "invalid_manifest",
3420                format!(
3421                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3422                    hello.protocol_ver, hello.manifest.protocol_ver
3423                ),
3424            )?]);
3425        }
3426
3427        if hello.manifest.module_id.trim().is_empty() {
3428            return Ok(vec![control_error_frame(
3429                &frame,
3430                "invalid_manifest",
3431                "manifest module_id must not be empty",
3432            )?]);
3433        }
3434
3435        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3436            Ok(negotiated_ver) => negotiated_ver,
3437            Err(message) => {
3438                return Ok(vec![control_error_frame(
3439                    &frame,
3440                    "version_unsupported",
3441                    message,
3442                )?])
3443            }
3444        };
3445
3446        // Registration and forwarding publication use the same module gate as
3447        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3448        // precede those transitions. A program-refusal hold blocks future
3449        // spawns, but does not take this gate or revoke a HELLO whose supervised
3450        // child's image has already passed the check.
3451        let _publication_gate = if let Some(owner) = &self.config_runtime {
3452            let gate = owner
3453                .module_gate(&hello.manifest.module_id)
3454                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3455            Some(if wait_for_gate {
3456                gate.blocking_lock_owned()
3457            } else {
3458                match gate.try_lock_owned() {
3459                    Ok(guard) => guard,
3460                    Err(_) => {
3461                        return Ok(vec![control_error_frame(
3462                            &frame,
3463                            "config_delivery_deferred",
3464                            "module admission is busy",
3465                        )?])
3466                    }
3467                }
3468            })
3469        } else {
3470            None
3471        };
3472        #[cfg(test)]
3473        if let Some(hold) = &self.hello_before_publication_hold {
3474            hold.wait();
3475            hold.wait();
3476        }
3477        let module = &hello.manifest.module_id;
3478        let required = self
3479            .config_runtime
3480            .as_ref()
3481            .is_some_and(|owner| owner.module_is_gated(module));
3482        let recovering = self
3483            .config_runtime
3484            .as_ref()
3485            .is_some_and(|owner| owner.is_recovering());
3486        // Both entry paths (handle_control -> handle_hello and
3487        // handle_control_frame_timed -> spawn_blocking) enter this same
3488        // handle_hello_checked function. Its fresh, fail-closed store check
3489        // precedes parsing and this publication-gate check; this cached read
3490        // also observes any recovery transition published during that work.
3491        // The nonce-connection-only fallback is defence in depth alongside
3492        // RuntimeOwner::module_is_gated's all-id recovery gate.
3493        if recovering
3494            && channel_spawn.as_ref().is_none_or(|spawn| {
3495                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3496            })
3497            && !(channel_spawn.is_none()
3498                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3499                    self.supervisor.spawned_consumer_authorized(module, nonce)
3500                        && self
3501                            .supervisor
3502                            .has_live_verified_program_binding(module, nonce)
3503                }))
3504        {
3505            return Ok(vec![control_error_frame(
3506                &frame,
3507                "config_gated",
3508                "recovery admits only previously bound supervised launches",
3509            )?]);
3510        }
3511        if required
3512            && (channel_spawn
3513                .as_ref()
3514                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3515                || self
3516                    .config_runtime
3517                    .as_ref()
3518                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3519        {
3520            return Ok(vec![control_error_frame(
3521                &frame,
3522                "reserved_module",
3523                "gated admission requires the current supervised child's registration channel and verified image binding",
3524            )?]);
3525        }
3526        if let Some(spawn) = &channel_spawn {
3527            if let Err(code) = spawn.check() {
3528                return Ok(vec![control_error_frame(
3529                    &frame,
3530                    code,
3531                    "registration launch is no longer live",
3532                )?]);
3533            }
3534        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3535            if required || self.supervisor.has_program_binding_record(module, nonce) {
3536                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3537                    let code = if error.code == "program_refused" {
3538                        "program_refused"
3539                    } else {
3540                        "config_delivery_deferred"
3541                    };
3542                    self.request_refusal_close(
3543                        connection_id,
3544                        sink.as_ref(),
3545                        CloseReason::new(code, error.detail.clone()),
3546                    );
3547                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3548                }
3549            }
3550        }
3551
3552        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3553        // swap is open for this id, the only HELLO admitted as a second process
3554        // is the one carrying the candidate's launch nonce (the swap token), and
3555        // it registers into the candidate slot rather than being refused as a
3556        // duplicate. Run after the reserved gate, a reserved module's candidate
3557        // would be refused `reserved_module` for presenting a nonce that gate
3558        // does not know. See `SupervisorHandle::swap_hello_admission`.
3559        let swap_admission = match &channel_spawn {
3560            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3561            Some(_) => SwapHelloAdmission::NotSwapping,
3562            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3563            None => self
3564                .supervisor
3565                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3566        };
3567        if swap_admission == SwapHelloAdmission::ProtocolNone {
3568            warn!(
3569                module_id = %hello.manifest.module_id,
3570                connection_id = connection_id.get(),
3571                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3572            );
3573            // The code stays `swap_token_invalid` for existing callers; only the
3574            // explanation names the actual reason.
3575            return Ok(vec![control_error_frame(
3576                &frame,
3577                "swap_token_invalid",
3578                format!(
3579                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3580                    hello.manifest.module_id
3581                ),
3582            )?]);
3583        }
3584        if swap_admission == SwapHelloAdmission::ChannelRequired {
3585            warn!(
3586                module_id = %hello.manifest.module_id,
3587                connection_id = connection_id.get(),
3588                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3589            );
3590            // The code stays `swap_token_invalid` for existing callers; only the
3591            // explanation names the actual reason.
3592            return Ok(vec![control_error_frame(
3593                &frame,
3594                "swap_token_invalid",
3595                format!(
3596                    "module_id '{}' is gated; it must register over its supervised registration channel",
3597                    hello.manifest.module_id
3598                ),
3599            )?]);
3600        }
3601        if swap_admission == SwapHelloAdmission::Refused {
3602            warn!(
3603                module_id = %hello.manifest.module_id,
3604                connection_id = connection_id.get(),
3605                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3606            );
3607            return Ok(vec![control_error_frame(
3608                &frame,
3609                "swap_token_invalid",
3610                format!(
3611                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3612                    hello.manifest.module_id
3613                ),
3614            )?]);
3615        }
3616        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3617
3618        // A swap candidate proves its identity with the candidate nonce above.
3619        // Other registrations receive this catalog fact only when reserved-module
3620        // policy required and accepted a nonce; unreserved registrations require
3621        // no nonce check.
3622        let verification = if swap_candidate && channel_spawn.is_none() {
3623            ReservedHelloVerification {
3624                nonce_verified: true,
3625                prefix_owner: None,
3626            }
3627        } else {
3628            let verification = if let Some(binding) = &prefix_binding {
3629                if !self.supervisor.prefix_claim_authorized(
3630                    &binding.registration.module_id,
3631                    &hello.manifest.module_id,
3632                ) {
3633                    return Ok(vec![control_error_frame(
3634                        &frame,
3635                        "claim_prefix_refused",
3636                        "prefix ownership changed",
3637                    )?]);
3638                }
3639                Ok(ReservedHelloVerification {
3640                    nonce_verified: true,
3641                    prefix_owner: Some(binding.registration.module_id.clone()),
3642                })
3643            } else if channel_spawn.is_some() {
3644                self.supervisor
3645                    .channel_hello_verification(&hello.manifest.module_id)
3646            } else {
3647                self.supervisor.reserved_hello_verification(
3648                    &hello.manifest.module_id,
3649                    hello.launch_nonce.as_deref(),
3650                )
3651            };
3652            match verification {
3653                Ok(verified) => verified,
3654                Err(rejection) => {
3655                    let message = match rejection {
3656                        ReservedHelloRejection::Exact { module_id } => format!(
3657                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3658                        ),
3659                        ReservedHelloRejection::Prefix {
3660                            prefix,
3661                            owner_module_id,
3662                        } => format!(
3663                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3664                            hello.manifest.module_id
3665                        ),
3666                    };
3667                    return Ok(vec![control_error_frame(
3668                        &frame,
3669                        "reserved_module",
3670                        message,
3671                    )?]);
3672                }
3673            }
3674        };
3675
3676        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3677            &hello.manifest.module_id,
3678            hello.manifest.capabilities.as_ref(),
3679        );
3680        if let Some(refusal) = reserved_capability_refusals.first() {
3681            let capability = refusal.capability.clone();
3682            let bound_module = refusal.claimants[0].clone();
3683            log_duplicate_claim_events(reserved_capability_refusals);
3684            return Ok(vec![control_error_frame(
3685                &frame,
3686                "reserved_capability",
3687                format!(
3688                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3689                    capability, bound_module, hello.manifest.module_id
3690                ),
3691            )?]);
3692        }
3693
3694        // A connection that already opened client routes must not also register as
3695        // a module: cleanup would then release only one side and leak the other.
3696        if self
3697            .forwarding
3698            .connection_has_client_routes(connection_id)
3699            .map_err(RouterError::Forwarding)?
3700        {
3701            return Ok(vec![control_error_frame(
3702                &frame,
3703                "invalid_hello",
3704                "connection has open client routes and cannot also register as a module",
3705            )?]);
3706        }
3707
3708        // Kept for scope sync authority, which goes only to the connection that
3709        // presented the module's current launch nonce. Recorded before the
3710        // registration is attempted: a connection whose registration then fails
3711        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3712        // A registration channel's authority is the channel itself, never a
3713        // nonce it also presented, and a prefix registration's is its claim:
3714        // neither records one, so neither can fall back to nonce authority.
3715        self.hello_launch_nonces
3716            .lock()
3717            .unwrap_or_else(|poisoned| poisoned.into_inner())
3718            .record(
3719                connection_id,
3720                if prefix_binding.is_some() || channel_spawn.is_some() {
3721                    None
3722                } else {
3723                    hello.launch_nonce.as_deref()
3724                },
3725            );
3726        let control_ops = effective_module_control_ops(hello.control_ops);
3727        let prefix_submodule = verification.prefix_owner.is_some();
3728        // Built before anything is registered so an encoding failure leaves no
3729        // registry or forwarding state behind.
3730        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3731        #[cfg(test)]
3732        struct PublicationFinished(Arc<std::sync::Barrier>);
3733        #[cfg(test)]
3734        impl Drop for PublicationFinished {
3735            fn drop(&mut self) {
3736                self.0.wait();
3737            }
3738        }
3739        #[cfg(test)]
3740        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3741            hold.wait();
3742            hold.wait();
3743            PublicationFinished(hold.clone())
3744        });
3745        let publication_spawn = channel_spawn
3746            .as_ref()
3747            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3748        #[cfg(test)]
3749        if prefix_binding.is_some() {
3750            self.claims.pause_prefix_hello_for_test(7);
3751        }
3752        let _registration_publication = match publication_spawn {
3753            Some(spawn) => Some(match spawn.begin_publication() {
3754                Ok(guard) => guard,
3755                Err(code) => {
3756                    return Ok(vec![control_error_frame(
3757                        &frame,
3758                        code,
3759                        "registration ended before HELLO publication",
3760                    )?])
3761                }
3762            }),
3763            None => None,
3764        };
3765        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3766            let live = self.claims.lock_prefix_binding(binding, connection_id);
3767            let ownership = self.supervisor.prefix_claim_publication(
3768                &binding.registration.module_id,
3769                &hello.manifest.module_id,
3770            );
3771            if live.is_none()
3772                || ownership.is_none()
3773                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3774                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3775            {
3776                return Ok(vec![control_error_frame(
3777                    &frame,
3778                    "claim_prefix_refused",
3779                    "prefix authority ended before publication",
3780                )?]);
3781            }
3782            (live, ownership)
3783        } else {
3784            (None, None)
3785        };
3786        if let Some(spawn) = publication_spawn {
3787            self.forwarding
3788                .bind_spawn(connection_id, spawn)
3789                .map_err(RouterError::Forwarding)?;
3790        }
3791        // The spawn whose own registration this HELLO is, for `target` on
3792        // the route.open reply: its channel, or the launch its nonce was
3793        // minted for. A prefix child's HELLO names no spawn of its own. It is
3794        // only looked up here. The connection is bound to it and its
3795        // requested declarations are frozen once the registry has accepted
3796        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3797        // duplicate, or for any other reason, leaves the spawn untouched: its
3798        // closing connection is then no registration of the spawn and ends
3799        // none of the spawn's routes.
3800        let hello_authority = match (&channel_spawn, &prefix_binding) {
3801            (Some(spawn), _) => Some(spawn.authority.clone()),
3802            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3803                self.supervisor
3804                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3805            }),
3806            (None, Some(_)) => None,
3807        }
3808        .map(|record| HelloAuthority {
3809            record,
3810            requested: hello
3811                .manifest
3812                .provider_declarations
3813                .clone()
3814                .unwrap_or_default(),
3815            froze: Default::default(),
3816        });
3817        #[cfg(test)]
3818        if prefix_binding.is_some() {
3819            self.claims.pause_prefix_hello_for_test(8);
3820        }
3821        if swap_candidate {
3822            let module_id = hello.manifest.module_id.clone();
3823            let mut differing_declarations = Default::default();
3824            let reply = self.register_swap_candidate(
3825                connection_id,
3826                sink,
3827                &frame,
3828                hello.manifest,
3829                negotiated_ver,
3830                control_ops,
3831                hello_ack,
3832                hello_authority.as_ref(),
3833                &mut differing_declarations,
3834                #[cfg(windows)]
3835                hello.launch_nonce.as_deref(),
3836            )?;
3837            if let Some(spawn) = &channel_spawn {
3838                if self
3839                    .registry
3840                    .get_module_by_connection(connection_id)
3841                    .ok()
3842                    .flatten()
3843                    .is_some()
3844                {
3845                    if let Some(sink) = primary_sink {
3846                        spawn.bind_primary_sink(sink);
3847                    }
3848                    spawn.hello_accepted();
3849                }
3850            } else if self
3851                .registry
3852                .get_module_by_connection(connection_id)
3853                .ok()
3854                .flatten()
3855                .is_some()
3856            {
3857                self.supervisor
3858                    .retire_unused_registration_channel(&module_id, true);
3859            }
3860            if self
3861                .registry
3862                .get_module_by_connection(connection_id)
3863                .ok()
3864                .flatten()
3865                .is_some()
3866            {
3867                self.file_development_widening(
3868                    hello_authority.map(|authority| authority.record),
3869                    differing_declarations,
3870                );
3871            }
3872            return Ok(reply);
3873        }
3874        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3875        // is refused, but `catalog.list` does not show the module and the
3876        // catalog generation does not move until it is published below, once
3877        // its forwarding endpoint exists. Listing it now would advertise a
3878        // module that `route.open` still refuses for having no forwarding
3879        // connection.
3880        let registration = match self
3881            .registry
3882            .register_unpublished_verified_with_control_ops(
3883                hello.manifest,
3884                negotiated_ver,
3885                connection_id,
3886                control_ops,
3887                verification.nonce_verified,
3888            ) {
3889            Ok(registration) => registration,
3890            Err(RegistryError::DuplicateModuleId { module_id }) => {
3891                return Ok(vec![control_error_frame(
3892                    &frame,
3893                    "duplicate_module_id",
3894                    format!(
3895                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3896                    ),
3897                )?])
3898            }
3899            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3900                return Ok(vec![control_error_frame(
3901                    &frame,
3902                    "invalid_module_id",
3903                    err.to_string(),
3904                )?])
3905            }
3906            Err(err) => {
3907                return Ok(vec![control_error_frame(
3908                    &frame,
3909                    "registry_error",
3910                    err.to_string(),
3911                )?])
3912            }
3913        };
3914        let differing_declarations =
3915            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3916                Ok(differing) => differing,
3917                Err(err) => {
3918                    if matches!(
3919                        self.rollback_unpublished_hello(connection_id),
3920                        Ok(r) if !r.is_empty()
3921                    ) {
3922                        crate::supervise::notify_registration_release();
3923                    }
3924                    return Err(RouterError::Forwarding(err));
3925                }
3926            };
3927        #[cfg(test)]
3928        self.hold_between_registry_and_forwarding();
3929
3930        let mut reply = Vec::new();
3931        // Registry readers must wait from before the ACK can be read until
3932        // publication. Nest forwarding inside the registry lock, never reverse.
3933        let publication = self
3934            .registry
3935            .publish_registration_after(connection_id, || {
3936                if let Some(sink) = sink {
3937                    // The forwarding table's module store is also the daemon-to-module
3938                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3939                    // manifest has no routable provider role. Non-routable modules still
3940                    // cannot receive route.bind in production: `handle_route_open` checks
3941                    // the registry manifest with `target_has_required_role` before the
3942                    // only production call to `begin_route_bind_relay_for` below that
3943                    // route.open path. The remaining direct relay callers are unit tests
3944                    // and benchmark harnesses that construct forwarding state explicitly.
3945                    //
3946                    // The HELLO_ACK is queued by the forwarding table itself, before the
3947                    // endpoint becomes visible, and is NOT returned as a reply. A module
3948                    // reads HELLO_ACK first and exits on anything else; a reply is only
3949                    // written after this handler returns, by which time a route.open on
3950                    // another connection could already have queued a route.bind request
3951                    // for this module ahead of it.
3952                    let concurrency = manifest_concurrency(&registration.manifest);
3953                    self.forwarding.register_module_connection_acked(
3954                        connection_id,
3955                        registration.manifest.module_id.clone(),
3956                        negotiated_ver,
3957                        concurrency,
3958                        sink,
3959                        crate::forwarding::ModuleHelloAck {
3960                            frame: hello_ack,
3961                            verified_prefix_owner: verification.prefix_owner,
3962                        },
3963                    )?;
3964                } else {
3965                    // No sink means no forwarding endpoint, so nothing can be routed
3966                    // ahead of the ack; it goes out as the reply.
3967                    reply.push(hello_ack);
3968                }
3969                #[cfg(test)]
3970                self.hold_between_ack_and_publication();
3971                Ok(())
3972            })
3973            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3974        let published = match publication {
3975            Ok(published) => published,
3976            Err(err) => {
3977                // The registry lock has been released, so rollback can take it
3978                // again. No forwarding endpoint or route was published. Keep
3979                // forwarding's weak connection-to-spawn association until the
3980                // connection's read loop ends and removes its remaining routes.
3981                // Removing this unpublished entry does not advance the catalog
3982                // generation.
3983                if matches!(
3984                    self.rollback_unpublished_hello(connection_id),
3985                    Ok(r) if !r.is_empty()
3986                ) {
3987                    crate::supervise::notify_registration_release();
3988                }
3989                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3990                return Ok(vec![control_error_frame(
3991                    &frame,
3992                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
3993                        "invalid_hello"
3994                    } else {
3995                        forwarding_error_code(&err)
3996                    },
3997                    err.to_string(),
3998                )?]);
3999            }
4000        };
4001        if !published {
4002            debug!(
4003                module_id = %registration.manifest.module_id,
4004                connection_id = connection_id.get(),
4005                "registration was removed before it could be published"
4006            );
4007            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
4008            return Ok(reply);
4009        }
4010
4011        drop(_prefix_ownership);
4012        drop(_prefix_live);
4013
4014        // Exposure over assumption: Concurrency's serde default is pinned to the
4015        // pre-field behavior (ModuleManaged), so a management surface that is
4016        // genuinely Serial and just never declared it inherits concurrent
4017        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
4018        // turns "no module has been bitten yet" into the checkable claim "no
4019        // module is exposed" -- one read of the boot log instead of a fleet
4020        // audit. Detected from the raw HELLO bytes because the serde default
4021        // deliberately erases the absent/declared distinction from the type.
4022        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
4023            info!(
4024                module_id = %registration.manifest.module_id,
4025                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
4026            );
4027        }
4028        if registration.manifest.registration_channel == Some(false)
4029            && self
4030                .supervisor
4031                .module_is_gated(&registration.manifest.module_id)
4032            && self
4033                .config_runtime
4034                .as_ref()
4035                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
4036                .as_deref()
4037                == Some("declared")
4038        {
4039            warn!(module_id = %registration.manifest.module_id,
4040                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
4041        }
4042
4043        self.apply_registration_capabilities(&registration);
4044
4045        self.supervisor
4046            .record_activity_registration(&registration.manifest.module_id);
4047
4048        info!(
4049            module_id = %registration.manifest.module_id,
4050            module_version = %registration.manifest.module_version,
4051            negotiated_ver,
4052            routable_provider = manifest_provides_routable_role(&registration.manifest),
4053            connection_id = connection_id.get(),
4054            "module registered"
4055        );
4056
4057        if let Some(spawn) = &channel_spawn {
4058            if let Some(sink) = primary_sink {
4059                spawn.bind_primary_sink(sink);
4060            }
4061            spawn.hello_accepted();
4062        } else if !prefix_submodule {
4063            self.supervisor
4064                .retire_unused_registration_channel(&registration.manifest.module_id, false);
4065        }
4066        self.file_development_widening(
4067            hello_authority.map(|authority| authority.record),
4068            differing_declarations,
4069        );
4070        #[cfg(windows)]
4071        if let Some(nonce) = hello.launch_nonce.as_deref() {
4072            self.supervisor
4073                .program_hello_accepted(&registration.manifest.module_id, nonce);
4074        }
4075
4076        #[cfg(test)]
4077        if let Some(hold) = &self.hello_inside_publication_hold {
4078            hold.wait();
4079            hold.wait();
4080        }
4081
4082        Ok(reply)
4083    }
4084
4085    /// Register a HELLO the swap gate admitted into the candidate slot of the
4086    /// registry and of forwarding, where it is reachable over its own
4087    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
4088    /// nothing routes to it until the supervisor cuts over.
4089    ///
4090    /// Registry first (unpublished), then forwarding, then publication, the
4091    /// same order as an ordinary HELLO; a forwarding failure removes the
4092    /// registry entry again. The swap supervisor treats a published, ready
4093    /// candidate as registered and promotes it, and promotion needs the
4094    /// candidate's forwarding endpoint, so the candidate is published only
4095    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
4096    /// recompute capability verdicts or run the capability deny census
4097    /// (`enforce_capability_denies`): both are about the module in the active
4098    /// slot, which `route.open` can target. A candidate sits in the candidate
4099    /// slot, so it neither provides capabilities to other modules nor can be
4100    /// routed to until promotion moves it into the active slot.
4101    #[allow(clippy::too_many_arguments)]
4102    fn register_swap_candidate(
4103        &self,
4104        connection_id: ConnectionId,
4105        sink: Option<crate::FrameSink>,
4106        frame: &Frame,
4107        manifest: ModuleManifest,
4108        negotiated_ver: u8,
4109        control_ops: Vec<String>,
4110        hello_ack: Frame,
4111        hello_authority: Option<&HelloAuthority>,
4112        differing_declarations: &mut ProviderDeclarations,
4113        #[cfg(windows)] launch_nonce: Option<&str>,
4114    ) -> Result<Vec<Frame>, RouterError> {
4115        let module_id = manifest.module_id.clone();
4116        // Closing a swap and publishing its candidate must be ordered. The
4117        // spawn role proves which slot is intended, not that the slot is open.
4118        self.supervisor
4119            .with_swap_candidate_admission(&module_id, || {
4120                let reply = self.publish_swap_candidate(
4121                    connection_id,
4122                    sink,
4123                    frame,
4124                    manifest,
4125                    negotiated_ver,
4126                    control_ops,
4127                    hello_ack,
4128                    hello_authority,
4129                    differing_declarations,
4130                    #[cfg(windows)]
4131                    launch_nonce,
4132                );
4133                let admitted = self
4134                    .registry
4135                    .get_candidate(&module_id)
4136                    .ok()
4137                    .flatten()
4138                    .is_some_and(|candidate| candidate.connection_id == connection_id);
4139                (reply, admitted)
4140            })
4141            .unwrap_or_else(|| {
4142                Ok(vec![control_error_frame(
4143                    frame,
4144                    "swap_token_invalid",
4145                    "swap ended before candidate HELLO publication",
4146                )?])
4147            })
4148    }
4149
4150    #[allow(clippy::too_many_arguments)]
4151    fn publish_swap_candidate(
4152        &self,
4153        connection_id: ConnectionId,
4154        sink: Option<crate::FrameSink>,
4155        frame: &Frame,
4156        manifest: ModuleManifest,
4157        negotiated_ver: u8,
4158        control_ops: Vec<String>,
4159        hello_ack: Frame,
4160        hello_authority: Option<&HelloAuthority>,
4161        differing_declarations: &mut ProviderDeclarations,
4162        #[cfg(windows)] launch_nonce: Option<&str>,
4163    ) -> Result<Vec<Frame>, RouterError> {
4164        let module_id = manifest.module_id.clone();
4165        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4166            manifest,
4167            negotiated_ver,
4168            connection_id,
4169            control_ops,
4170        ) {
4171            Ok(registration) => registration,
4172            Err(RegistryError::DuplicateModuleId { module_id }) => {
4173                return Ok(vec![control_error_frame(
4174                    frame,
4175                    "duplicate_module_id",
4176                    format!(
4177                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4178                    ),
4179                )?])
4180            }
4181            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4182                return Ok(vec![control_error_frame(
4183                    frame,
4184                    "invalid_module_id",
4185                    err.to_string(),
4186                )?])
4187            }
4188            Err(err) => {
4189                return Ok(vec![control_error_frame(
4190                    frame,
4191                    "registry_error",
4192                    err.to_string(),
4193                )?])
4194            }
4195        };
4196        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4197            Ok(differing) => differing,
4198            Err(err) => {
4199                if matches!(
4200                    self.rollback_unpublished_hello(connection_id),
4201                    Ok(r) if !r.is_empty()
4202                ) {
4203                    crate::supervise::notify_registration_release();
4204                }
4205                return Err(RouterError::Forwarding(err));
4206            }
4207        };
4208        #[cfg(test)]
4209        self.hold_between_registry_and_forwarding();
4210        let mut reply = Vec::new();
4211        let publication = self
4212            .registry
4213            .publish_registration_after(connection_id, || {
4214                if let Some(sink) = sink {
4215                    // Same ordering as an ordinary HELLO: queue the ACK before
4216                    // inserting the endpoint, and keep registry readers excluded
4217                    // until the candidate is published.
4218                    let concurrency = manifest_concurrency(&registration.manifest);
4219                    self.forwarding.register_candidate_module_connection_acked(
4220                        connection_id,
4221                        module_id.clone(),
4222                        negotiated_ver,
4223                        concurrency,
4224                        sink,
4225                        hello_ack,
4226                    )?;
4227                } else {
4228                    reply.push(hello_ack);
4229                }
4230                #[cfg(test)]
4231                self.hold_between_ack_and_publication();
4232                Ok(())
4233            })
4234            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4235        let published = match publication {
4236            Ok(published) => published,
4237            Err(err) => {
4238                if matches!(
4239                    self.rollback_unpublished_hello(connection_id),
4240                    Ok(r) if !r.is_empty()
4241                ) {
4242                    crate::supervise::notify_registration_release();
4243                }
4244                self.refuse_hello_authority(connection_id, hello_authority);
4245                return Ok(vec![control_error_frame(
4246                    frame,
4247                    forwarding_error_code(&err),
4248                    err.to_string(),
4249                )?]);
4250            }
4251        };
4252        if !published {
4253            debug!(
4254                module_id = %module_id,
4255                connection_id = connection_id.get(),
4256                "swap candidate registration was removed before it could be published"
4257            );
4258            self.refuse_hello_authority(connection_id, hello_authority);
4259            return Ok(reply);
4260        }
4261        info!(
4262            module_id = %module_id,
4263            module_version = %registration.manifest.module_version,
4264            negotiated_ver,
4265            ready = registration.ready,
4266            connection_id = connection_id.get(),
4267            "swap candidate registered; not routable until cutover"
4268        );
4269        #[cfg(windows)]
4270        if let Some(nonce) = launch_nonce {
4271            self.supervisor.program_hello_accepted(&module_id, nonce);
4272        }
4273        Ok(reply)
4274    }
4275
4276    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4277    /// spawn's requested provider declarations. Runs only once the registry
4278    /// has accepted the HELLO, before its endpoint is published, so a route
4279    /// reserved on the endpoint always finds the spawn. Returns the requested
4280    /// entries that differ from the saved approvals, for a widening request.
4281    fn admit_hello_authority(
4282        &self,
4283        connection: ConnectionId,
4284        authority: Option<&HelloAuthority>,
4285    ) -> Result<ProviderDeclarations, ForwardingError> {
4286        let Some(authority) = authority else {
4287            return Ok(ProviderDeclarations::new());
4288        };
4289        let froze = authority
4290            .record
4291            .freeze_declarations(authority.requested.clone());
4292        authority
4293            .froze
4294            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4295        self.forwarding
4296            .bind_target_authority(connection, authority.record.clone())
4297            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4298        Ok(froze.unwrap_or_default())
4299    }
4300
4301    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4302    /// registry accepted it, so the refused connection is no registration of
4303    /// the spawn and the spawn's declarations are left for the HELLO that
4304    /// does register it to freeze.
4305    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4306        let Some(authority) = authority else {
4307            return;
4308        };
4309        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4310            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4311        }
4312        if authority
4313            .froze
4314            .swap(false, std::sync::atomic::Ordering::Relaxed)
4315        {
4316            authority.record.unfreeze_refused_declarations();
4317        }
4318    }
4319
4320    fn build_hello_ack(
4321        &self,
4322        frame: &Frame,
4323        negotiated_ver: u8,
4324        module_id: &str,
4325    ) -> Result<Frame, RouterError> {
4326        let ack = ModuleHelloAckBody {
4327            negotiated_ver,
4328            subc_ops: module_subc_ops(),
4329            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4330            storage: self
4331                .storage_config
4332                .as_ref()
4333                .map(|cfg| cfg.descriptor_for(module_id)),
4334            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4335        };
4336        let body = serde_json::to_vec(&ack).map_err(|err| {
4337            RouterError::backend(
4338                0,
4339                frame.header.corr,
4340                format!("failed to encode HELLO_ACK: {err}"),
4341            )
4342        })?;
4343
4344        Frame::build_with_version(
4345            negotiated_ver,
4346            FrameType::HelloAck,
4347            control_flags(),
4348            0,
4349            0,
4350            frame.header.corr,
4351            body,
4352        )
4353        .map_err(RouterError::FrameBuild)
4354    }
4355
4356    async fn handle_client_control_request(
4357        &self,
4358        ctx: &RouteCtx,
4359        frame: Frame,
4360        request: ClientControlRequest,
4361        route_open_timings: &mut Option<RouteOpenTimings>,
4362    ) -> Result<Vec<Frame>, RouterError> {
4363        if let Some(owner) = &self.config_runtime {
4364            let module = match &request {
4365                ClientControlRequest::SupervisorRestart { module_id, .. }
4366                | ClientControlRequest::SupervisorReload { module_id }
4367                | ClientControlRequest::SupervisorSwap { module_id, .. }
4368                | ClientControlRequest::SupervisorSetEnabled {
4369                    module_id,
4370                    enabled: true,
4371                } => Some(module_id.as_str()),
4372                _ => None,
4373            };
4374            let rescan = matches!(
4375                &request,
4376                ClientControlRequest::SupervisorRescan { preview: false }
4377                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4378            );
4379            let held = if module.is_some() || rescan {
4380                let module = module.map(str::to_owned);
4381                owner
4382                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4383                    .await
4384            } else {
4385                Ok(())
4386            };
4387            if let Err(error) = held {
4388                if error.code != "config_delivery_deferred" {
4389                    let code = if error.code == "store_tampered" {
4390                        "store_tampered"
4391                    } else {
4392                        "config_gated"
4393                    };
4394                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4395                }
4396            }
4397        }
4398        if let Some(operation) = privileged_operation(&request) {
4399            let caller = self.resolve_caller(ctx.connection_id).await;
4400            let op = client_control_request_op(&request);
4401            let text = prompt_text(operation, &caller);
4402            match self.privileged_operator_prompt {
4403                PrivilegedOperatorPrompt::Log => {
4404                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4405                        target = ?operation, caller = %caller.description(), summary = %text,
4406                        "privileged request would prompt the operator");
4407                }
4408                PrivilegedOperatorPrompt::Enforce => {
4409                    let key =
4410                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4411                    let shortcut =
4412                        self.operator_shortcut_stamp(ctx.connection_id)
4413                            .await
4414                            .map(|stamp| {
4415                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
4416                            });
4417                    let outcome = self
4418                        .forwarding
4419                        .operator_confirms()
4420                        .approve_privileged_with_shortcut(
4421                            ctx,
4422                            &frame,
4423                            op,
4424                            text,
4425                            caller.description(),
4426                            key,
4427                            shortcut,
4428                        )
4429                        .await;
4430                    if outcome.code != "confirmed" {
4431                        return Ok(vec![outcome.frame(&frame)]);
4432                    }
4433                }
4434            }
4435        }
4436        match request {
4437            ClientControlRequest::DaemonShutdownIntent { intent } => {
4438                if intent.as_str() != Some("restart") {
4439                    return Ok(vec![control_error_frame(
4440                        &frame,
4441                        "invalid_params",
4442                        "intent must be 'restart'",
4443                    )?]);
4444                }
4445                // A stamped daemon boots a newer approved generation only from a
4446                // durable restart intent, written here before the daemon exits.
4447                // Failing to write it never blocks the restart: the next start
4448                // then boots the last active generation and the newer one waits.
4449                if let Some(owner) = &self.config_runtime {
4450                    match owner
4451                        .on_blocking(|owner| owner.assign_daemon_restart())
4452                        .await
4453                    {
4454                        Ok(Some(generation)) => {
4455                            info!(
4456                                generation,
4457                                "daemon restart will warm up approved generation"
4458                            )
4459                        }
4460                        Ok(None) => {}
4461                        Err(error) => warn!(
4462                            %error,
4463                            "daemon restart intent not recorded; the next start boots the last active generation"
4464                        ),
4465                    }
4466                }
4467                let response = ClientControlResponse::DaemonShutdownIntent {
4468                    intent: "restart".to_owned(),
4469                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4470                };
4471                Ok(vec![control_response_body_frame(
4472                    &frame,
4473                    &response,
4474                    "ClientControlResponse::DaemonShutdownIntent",
4475                )?])
4476            }
4477            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4478            ClientControlRequest::CatalogList { module_id } => {
4479                self.handle_catalog_list(frame, module_id)
4480            }
4481            ClientControlRequest::RouteOpen {
4482                target,
4483                identity,
4484                consumer_identity,
4485                consumer_capabilities,
4486                role_versions,
4487                busy_refusals,
4488                admission_facts,
4489                scope,
4490                ..
4491            } => {
4492                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4493                    &frame.body,
4494                ) {
4495                    Ok(extensions) => extensions,
4496                    Err(err) => {
4497                        return Ok(vec![control_error_frame(
4498                            &frame,
4499                            "invalid_control_body",
4500                            format!("malformed route.open extensions: {err}"),
4501                        )?]);
4502                    }
4503                };
4504                self.handle_route_open(
4505                    ctx,
4506                    frame,
4507                    RouteOpenRequest {
4508                        target,
4509                        identity,
4510                        consumer_identity,
4511                        consumer_capabilities,
4512                        role_versions,
4513                        busy_refusals,
4514                        admission_facts,
4515                        scope,
4516                        accepts_close_reasons: extensions.accepts_close_reasons,
4517                    },
4518                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4519                )
4520                .await
4521            }
4522            ClientControlRequest::RoutePoll {
4523                route_channel,
4524                route_epoch,
4525                kind,
4526            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4527            ClientControlRequest::SupervisorList {} => {
4528                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4529                    self.agent_declarations.refuse(
4530                        self,
4531                        ctx,
4532                        control_error_frame(
4533                            &frame,
4534                            "busy",
4535                            "supervisor list work is at capacity; retry",
4536                        )?,
4537                    );
4538                    return Ok(Vec::new());
4539                };
4540                // Filesystem-backed diagnostics must not hold up this connection's reader.
4541                let handler = self.clone();
4542                let sink = ctx.egress.clone();
4543                tokio::spawn(
4544                    async move {
4545                        let _permit = permit;
4546                        let result = handler.handle_supervisor_list(frame.clone()).await;
4547                        let replies = match result {
4548                            Ok(replies) => replies,
4549                            Err(error) => {
4550                                control_error_frame(&frame, "backend_error", error.to_string())
4551                                    .into_iter()
4552                                    .collect()
4553                            }
4554                        };
4555                        for reply in replies {
4556                            if !matches!(
4557                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4558                                    .await,
4559                                Ok(Ok(()))
4560                            ) {
4561                                break;
4562                            }
4563                        }
4564                    }
4565                    .with_current_subscriber(),
4566                );
4567                Ok(Vec::new())
4568            }
4569            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4570                self.handle_supervisor_spawn_snapshot(frame)
4571            }
4572            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4573                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4574            }
4575            ClientControlRequest::SupervisorRestart {
4576                module_id,
4577                drain_timeout_ms,
4578            } => {
4579                self.log_supervisor_request_received(
4580                    ctx,
4581                    frame.header.corr,
4582                    ops::SUPERVISOR_RESTART,
4583                    Some(&module_id),
4584                    None,
4585                )?;
4586                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4587                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4588                    .await
4589            }
4590            ClientControlRequest::SupervisorSwap {
4591                module_id,
4592                ready_timeout_ms,
4593            } => {
4594                self.log_supervisor_request_received(
4595                    ctx,
4596                    frame.header.corr,
4597                    ops::SUPERVISOR_SWAP,
4598                    Some(&module_id),
4599                    None,
4600                )?;
4601                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4602                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4603                    .await
4604            }
4605            ClientControlRequest::SupervisorReload { module_id } => {
4606                self.log_supervisor_request_received(
4607                    ctx,
4608                    frame.header.corr,
4609                    ops::SUPERVISOR_RELOAD,
4610                    Some(&module_id),
4611                    None,
4612                )?;
4613                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4614                self.handle_supervisor_reload(frame, module_id, requester)
4615                    .await
4616            }
4617            ClientControlRequest::SupervisorRescan { preview } => {
4618                if !preview {
4619                    self.log_supervisor_request_received(
4620                        ctx,
4621                        frame.header.corr,
4622                        ops::SUPERVISOR_RESCAN,
4623                        None,
4624                        None,
4625                    )?;
4626                }
4627                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4628                let operation = self.handle_supervisor_rescan(
4629                    frame,
4630                    if preview {
4631                        RescanMode::Preview
4632                    } else {
4633                        RescanMode::Execute
4634                    },
4635                    requester,
4636                );
4637                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4638                    .await
4639            }
4640            ClientControlRequest::SupervisorRescanChecked {
4641                preview,
4642                candidate,
4643                expect,
4644            } => {
4645                self.observe_control_wait(
4646                    ctx,
4647                    None,
4648                    ops::SUPERVISOR_RESCAN,
4649                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4650                )
4651                .await
4652            }
4653            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4654                self.log_supervisor_request_received(
4655                    ctx,
4656                    frame.header.corr,
4657                    ops::SUPERVISOR_RELEASE_RESERVED,
4658                    Some(&module_id),
4659                    None,
4660                )?;
4661                self.handle_supervisor_release_reserved(frame, module_id)
4662                    .await
4663            }
4664            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4665                self.log_supervisor_request_received(
4666                    ctx,
4667                    frame.header.corr,
4668                    ops::SUPERVISOR_SET_ENABLED,
4669                    Some(&module_id),
4670                    Some(enabled),
4671                )?;
4672                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4673                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4674                    .await
4675            }
4676            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4677                self.handle_supervisor_health_probe(ctx, frame, module_id)
4678                    .await
4679            }
4680            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4681            ClientControlRequest::SupervisorRoutes { module_id } => {
4682                self.handle_supervisor_routes(frame, module_id)
4683            }
4684            ClientControlRequest::SupervisorProvenance { module_id } => {
4685                self.handle_supervisor_provenance(ctx, frame, module_id)
4686                    .await
4687            }
4688            ClientControlRequest::SupervisorStderrTail {
4689                module_id,
4690                max_lines,
4691                max_bytes,
4692            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4693            ClientControlRequest::SupervisorTerminals { module_id } => {
4694                self.handle_supervisor_terminals(ctx, frame, module_id)
4695                    .await
4696            }
4697        }
4698    }
4699
4700    fn log_supervisor_request_received(
4701        &self,
4702        ctx: &RouteCtx,
4703        corr: u64,
4704        op: &'static str,
4705        module_id: Option<&str>,
4706        enabled: Option<bool>,
4707    ) -> Result<(), RouterError> {
4708        let caller = self.supervisor_requester(ctx, corr)?;
4709        let caller = principal_label(&caller);
4710        // `Option` fields are recorded only when present, so a request with no
4711        // module id (rescan) or no enabled flag simply omits that field.
4712        info!(
4713            target: "control",
4714            op,
4715            module_id,
4716            enabled,
4717            connection_id = ctx.connection_id.get(),
4718            caller = %caller,
4719            "supervisor request received"
4720        );
4721        Ok(())
4722    }
4723
4724    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4725        Ok(self
4726            .registry
4727            .get_module_by_connection(ctx.connection_id)
4728            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4729            .map(|registration| Principal::Reserved {
4730                module_id: registration.manifest.module_id,
4731            })
4732            .unwrap_or(Principal::Direct))
4733    }
4734
4735    fn handle_module_control_request(
4736        &self,
4737        connection_id: ConnectionId,
4738        frame: Frame,
4739        request: ModuleControlRequestFromModule,
4740    ) -> Result<Vec<Frame>, RouterError> {
4741        match request {
4742            ModuleControlRequestFromModule::RouteAuthorize {
4743                principal,
4744                scope,
4745                target,
4746                expected,
4747            } => self.handle_route_authorize(
4748                connection_id,
4749                frame,
4750                principal,
4751                scope,
4752                target,
4753                expected,
4754            ),
4755            ModuleControlRequestFromModule::CatalogUpdate {
4756                provides,
4757                capabilities,
4758                ready,
4759            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4760            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4761                self.handle_catalog_update_role_declarations(
4762                    connection_id,
4763                    frame,
4764                    role_declarations,
4765                )
4766            }
4767            ModuleControlRequestFromModule::LiveRoots {} => {
4768                let registered = self
4769                    .registry
4770                    .get_module_by_connection(connection_id)
4771                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4772                let Some(registration) = registered else {
4773                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4774                };
4775                let response = self
4776                    .forwarding
4777                    .live_roots(&registration.manifest.module_id)
4778                    .map_err(RouterError::Forwarding)?;
4779                Ok(vec![control_response_body_frame(
4780                    &frame,
4781                    &response,
4782                    "ModuleControlResponseToModule::LiveRoots",
4783                )?])
4784            }
4785            ModuleControlRequestFromModule::AgentCommands {
4786                started,
4787                finished,
4788                known,
4789            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4790            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4791                self.handle_scope_sync(connection_id, frame, generation, scopes)
4792            }
4793            ModuleControlRequestFromModule::ScopeApply {
4794                generation,
4795                upsert,
4796                end,
4797            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4798            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4799                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4800            }
4801            _ => Ok(vec![control_error_frame(
4802                &frame,
4803                "unsupported_control_frame",
4804                "unsupported module control operation",
4805            )?]),
4806        }
4807    }
4808
4809    fn handle_scope_served_by(
4810        &self,
4811        connection_id: ConnectionId,
4812        frame: Frame,
4813    ) -> Result<Vec<Frame>, RouterError> {
4814        let registered = self
4815            .registry
4816            .get_module_by_connection(connection_id)
4817            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4818        let Some(registered) = registered else {
4819            return Ok(vec![control_error_frame(
4820                &frame,
4821                "not_registered",
4822                "scope.served_by requires an active module registration owned by this connection",
4823            )?]);
4824        };
4825        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4826        {
4827            Ok(request) => request,
4828            Err(err) => {
4829                return Ok(vec![control_error_frame(
4830                    &frame,
4831                    "invalid_control_body",
4832                    format!("malformed scope.served_by body: {err}"),
4833                )?])
4834            }
4835        };
4836        let answer = self
4837            .scopes
4838            .read()
4839            .unwrap_or_else(|poisoned| poisoned.into_inner())
4840            .served_by(
4841                &registered.manifest.module_id,
4842                &request.scope_ref,
4843                request.scope_epoch,
4844                &request.module_id,
4845            );
4846        let reply = subc_control::ScopeServedByReply::new(
4847            answer,
4848            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4849        );
4850        Ok(vec![control_response_body_frame(
4851            &frame,
4852            &reply,
4853            "ScopeServedByReply",
4854        )?])
4855    }
4856
4857    /// Explicit test-only phone policy; daemon configuration cannot select it.
4858    #[cfg(any(test, feature = "test-support"))]
4859    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
4860        self.operator_app_policy.phone_enabled = enabled;
4861        self
4862    }
4863
4864    /// Resolve folders before taking the scope-table lock: a slow filesystem
4865    /// must not hold up admissions for unrelated scoped routes.
4866    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
4867        let mut scopes = ScopeRecords::from(scopes);
4868        for (index, record) in scopes.records.iter_mut().enumerate() {
4869            if let Some(refusal) = Self::canonicalize_workdir(record) {
4870                scopes.refusals.insert(index, refusal);
4871            }
4872        }
4873        scopes
4874    }
4875
4876    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
4877        let workdir = record.workdir.as_mut()?;
4878        let path = std::path::Path::new(workdir);
4879        if !path.is_absolute() {
4880            return Some((
4881                error_codes::INVALID_WORKDIR,
4882                "workdir must be absolute".to_string(),
4883            ));
4884        }
4885        match ProjectRootId::from_path_allowing_missing(path) {
4886            Ok(root) => match root.as_path().to_str() {
4887                Some(canonical) => {
4888                    *workdir = canonical.to_string();
4889                    None
4890                }
4891                None => Some((
4892                    error_codes::INVALID_WORKDIR,
4893                    "canonical workdir is not UTF-8".to_string(),
4894                )),
4895            },
4896            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
4897        }
4898    }
4899
4900    /// `scope.sync`: the owner is the module registered on this connection.
4901    /// A connection with no registration (every client connection, `direct`
4902    /// included) is refused `not_registered` before the table is consulted.
4903    fn handle_scope_sync(
4904        &self,
4905        connection_id: ConnectionId,
4906        frame: Frame,
4907        generation: u64,
4908        scopes: Vec<ScopeRecord>,
4909    ) -> Result<Vec<Frame>, RouterError> {
4910        self.handle_scope_change(connection_id, frame, generation, scopes, None)
4911    }
4912
4913    fn handle_scope_change(
4914        &self,
4915        connection_id: ConnectionId,
4916        frame: Frame,
4917        generation: u64,
4918        scopes: Vec<ScopeRecord>,
4919        end: Option<Vec<ScopeEnd>>,
4920    ) -> Result<Vec<Frame>, RouterError> {
4921        let is_apply = end.is_some();
4922        let Some(registration) = self
4923            .registry
4924            .get_module_by_connection(connection_id)
4925            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4926        else {
4927            return Ok(vec![control_error_frame(
4928                &frame,
4929                "not_registered",
4930                "scope.sync and scope.apply require an active module registration owned by this connection",
4931            )?]);
4932        };
4933        let owner = registration.manifest.module_id;
4934        let scopes = Self::prepare_scope_records(scopes);
4935        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
4936        let is_current_launch = |connection: ConnectionId| {
4937            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
4938        };
4939        // Lock order is the scope table, then the forwarding table: the new
4940        // tags are published, and the routes the change closes are selected,
4941        // while the scope table is still write-locked, so no admission can read
4942        // a record whose tag is not yet published.
4943        let mut table = self
4944            .scopes
4945            .write()
4946            .unwrap_or_else(|poisoned| poisoned.into_inner());
4947        let outcome = match end {
4948            Some(end) => table.apply(
4949                &owner,
4950                connection_id,
4951                is_current_launch,
4952                generation,
4953                scopes,
4954                end,
4955            ),
4956            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
4957        };
4958        let drained = match &outcome {
4959            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
4960            Err(_) => Vec::new(),
4961        };
4962        let has_deadlines = outcome.is_ok() && table.has_deadlines();
4963        drop(table);
4964        if has_deadlines {
4965            self.scope_deadline_added.notify_one();
4966        }
4967        match outcome {
4968            Ok(applied) => {
4969                let counts = ScopeOutcomeCounts::of(&applied.results);
4970                info!(
4971                    owner = %owner,
4972                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4973                    generation,
4974                    records = applied.results.len(),
4975                    created = counts.created,
4976                    replaced = counts.replaced,
4977                    updated = counts.updated,
4978                    unchanged = counts.unchanged,
4979                    refused = counts.refused,
4980                    ended = applied.ended.len(),
4981                    tag_changes = applied.tag_changes.len(),
4982                    routes_closed = drained.len(),
4983                    "scope change accepted"
4984                );
4985                // An accepted scope change can still refuse individual records, and the
4986                // owner is the only party that sees the reply. Name them here so
4987                // an operator can tell a refused session from a missing one
4988                // without the owner's logs. Capped so a call that refuses
4989                // thousands cannot flood the log; the count above is complete.
4990                for refused in applied
4991                    .results
4992                    .iter()
4993                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
4994                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
4995                {
4996                    warn!(
4997                        owner = %owner,
4998                        generation,
4999                        scope_ref = %refused.scope_ref,
5000                        scope_epoch = refused.scope_epoch,
5001                        code = refused.code.as_deref().unwrap_or(""),
5002                        "scope record refused"
5003                    );
5004                }
5005                self.close_scope_drained_routes(drained);
5006                let response = if is_apply {
5007                    ModuleControlResponseToModule::ScopeApply {
5008                        generation,
5009                        results: applied.results,
5010                        end_results: applied.end_results,
5011                        ended: applied.ended,
5012                    }
5013                } else {
5014                    ModuleControlResponseToModule::ScopeSync {
5015                        generation,
5016                        results: applied.results,
5017                        ended: applied.ended,
5018                    }
5019                };
5020                Ok(vec![control_response_body_frame(
5021                    &frame,
5022                    &response,
5023                    "scope change response",
5024                )?])
5025            }
5026            Err(refusal) => {
5027                info!(
5028                    owner = %owner,
5029                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
5030                    generation,
5031                    code = refusal.code,
5032                    "scope change refused"
5033                );
5034                Ok(vec![control_error_frame(
5035                    &frame,
5036                    refusal.code,
5037                    refusal.message,
5038                )?])
5039            }
5040        }
5041    }
5042
5043    /// Notify both endpoints of routes drained by a scope change.
5044    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
5045        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
5046    }
5047
5048    /// Re-authorize a stored source on a principal the module supplies.
5049    ///
5050    /// That principal carries no spawn or authority epoch, so this reply never
5051    /// conveys a caller attestation or a first-party mark, and a provider must
5052    /// not apply automatic grants on anything it authorizes.
5053    fn handle_route_authorize(
5054        &self,
5055        connection_id: ConnectionId,
5056        frame: Frame,
5057        principal: Principal,
5058        scope: subc_protocol::scope::RouteAuthorizeScope,
5059        target: String,
5060        expected: subc_protocol::scope::RouteAuthorizeExpected,
5061    ) -> Result<Vec<Frame>, RouterError> {
5062        use crate::scopes::admission::{admit_route, AdmissionMode};
5063        use subc_protocol::scope::{
5064            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
5065        };
5066        let registry = self
5067            .registry
5068            .route_admission_snapshot()
5069            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5070        let owner_configured = match &scope.owner {
5071            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5072            _ => false,
5073        };
5074        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
5075        let answer = {
5076            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
5077            let permitted = registry
5078                .iter()
5079                .find(|r| r.connection_id == connection_id)
5080                .is_some_and(|r| {
5081                    scopes.is_federated_owner(&Principal::Reserved {
5082                        module_id: r.module_id.clone(),
5083                    }) && r.capabilities.as_ref().is_some_and(|caps| {
5084                        caps.provides
5085                            .iter()
5086                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
5087                    })
5088                });
5089            if !permitted {
5090                drop(scopes);
5091                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
5092                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
5093            }
5094            admit_route(
5095                &scopes,
5096                &registry,
5097                &principal,
5098                &target,
5099                Some(&selector),
5100                owner_configured,
5101                AdmissionMode::Authorize(&expected),
5102            )
5103        };
5104        let response = match answer {
5105            Ok(admission) => {
5106                let mut response = RouteAuthorizeResponse::new(
5107                    RouteAuthorizeOutcome::Authorized,
5108                    "route admission authorized",
5109                );
5110                response.content_version = admission.content_version;
5111                response
5112            }
5113            Err(refusal) => refusal.response(),
5114        };
5115        Ok(vec![control_response_body_frame(
5116            &frame,
5117            &response,
5118            "RouteAuthorizeResponse",
5119        )?])
5120    }
5121
5122    /// `scope.describe`: any registered module may read any scope, because a
5123    /// provider must read the scope a route it serves is stamped with.
5124    fn handle_scope_describe(
5125        &self,
5126        connection_id: ConnectionId,
5127        frame: Frame,
5128        owner: Principal,
5129        scope_ref: String,
5130    ) -> Result<Vec<Frame>, RouterError> {
5131        let registered = self
5132            .registry
5133            .get_module_by_connection(connection_id)
5134            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5135        let Some(registered) = registered else {
5136            return Ok(vec![control_error_frame(
5137                &frame,
5138                "not_registered",
5139                "scope.describe requires an active module registration owned by this connection",
5140            )?]);
5141        };
5142        let scopes = self
5143            .scopes
5144            .read()
5145            .unwrap_or_else(|poisoned| poisoned.into_inner());
5146        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5147            return Ok(vec![control_error_frame(
5148                &frame,
5149                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5150                "scope.describe of the federated owner requires scope-federated/v1",
5151            )?]);
5152        }
5153        let mut description = scopes.describe(&owner, &scope_ref);
5154        drop(scopes);
5155        if owner
5156            != (Principal::Reserved {
5157                module_id: registered.manifest.module_id.clone(),
5158            })
5159        {
5160            if let Some(facts) = description
5161                .stamp
5162                .as_mut()
5163                .and_then(|stamp| stamp.attributes.federated.as_mut())
5164            {
5165                facts.stamp_required = false;
5166            }
5167        }
5168        // Describe readers also decode strict ScopeAttributes. Attribution is
5169        // safe to omit unless the requesting module declares it understands it.
5170        if !registered
5171            .manifest
5172            .capabilities
5173            .as_ref()
5174            .is_some_and(|caps| {
5175                caps.provides
5176                    .iter()
5177                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5178            })
5179        {
5180            if let Some(stamp) = description.stamp.as_mut() {
5181                stamp.attributes.on_behalf_of_agent = None;
5182            }
5183        }
5184        if !registered
5185            .manifest
5186            .capabilities
5187            .as_ref()
5188            .is_some_and(|caps| {
5189                caps.provides
5190                    .iter()
5191                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5192            })
5193        {
5194            if let Some(stamp) = description.stamp.as_mut() {
5195                stamp.attributes.flow_version = None;
5196                stamp.attributes.flow_code_hash = None;
5197                stamp.attributes.flow_install_id = None;
5198            }
5199        }
5200        let owner_configured = match &owner {
5201            // Ask whether the owner is configured (`is_configured`), not
5202            // whether it is on the roster (`get(..).is_some()`): a supervised
5203            // module's process can register and describe a scope before the
5204            // supervisor has put it on the roster.
5205            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5206            _ => false,
5207        };
5208        let response = ModuleControlResponseToModule::ScopeDescribe {
5209            status: description.status,
5210            scope_epoch: description.scope_epoch,
5211            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5212            owner_synced: description.owner_synced,
5213            owner_configured,
5214            scope: description.stamp,
5215        };
5216        Ok(vec![control_response_body_frame(
5217            &frame,
5218            &response,
5219            "ModuleControlResponseToModule::ScopeDescribe",
5220        )?])
5221    }
5222
5223    fn handle_catalog_update_role_declarations(
5224        &self,
5225        connection_id: ConnectionId,
5226        frame: Frame,
5227        role_declarations: serde_json::Value,
5228    ) -> Result<Vec<Frame>, RouterError> {
5229        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5230            return Ok(vec![control_error_frame(
5231                &frame,
5232                "invalid_role_declarations",
5233                err.to_string(),
5234            )?]);
5235        }
5236        let declarations = serde_json::from_value(role_declarations)
5237            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5238        if self
5239            .registry
5240            .replace_role_declarations_for_connection(connection_id, declarations)
5241            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5242            .is_none()
5243        {
5244            return Ok(vec![control_error_frame(
5245                &frame,
5246                "not_registered",
5247                "catalog.update_role_declarations requires an active module registration owned by this connection",
5248            )?]);
5249        }
5250        control_response_body_frame(
5251            &frame,
5252            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5253            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5254        )
5255        .map(|frame| vec![frame])
5256    }
5257
5258    fn handle_catalog_update(
5259        &self,
5260        connection_id: ConnectionId,
5261        frame: Frame,
5262        provides: Vec<ProviderRole>,
5263        capabilities: Option<CapabilityDeclarations>,
5264        ready: Option<bool>,
5265    ) -> Result<Vec<Frame>, RouterError> {
5266        self.refresh_capability_requirements();
5267        let Some(registration) = self
5268            .registry
5269            .get_module_by_connection(connection_id)
5270            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5271        else {
5272            return Ok(vec![control_error_frame(
5273                &frame,
5274                "not_registered",
5275                "catalog.update requires an active module registration owned by this connection",
5276            )?]);
5277        };
5278
5279        if let Some(message) =
5280            catalog_update_frozen_field_message(&registration.manifest, &provides)
5281        {
5282            return Ok(vec![control_error_frame(
5283                &frame,
5284                "catalog_update_frozen_field",
5285                message,
5286            )?]);
5287        }
5288
5289        let mut candidate = registration.manifest.clone();
5290        candidate.provides = provides.clone();
5291        candidate.capabilities = capabilities
5292            .clone()
5293            .or_else(|| registration.manifest.capabilities.clone());
5294        if let Some(rich_ui) = &candidate.rich_ui {
5295            if let Err(err) = rich_ui.validate() {
5296                return Ok(vec![control_error_frame(
5297                    &frame,
5298                    "invalid_manifest",
5299                    err.to_string(),
5300                )?]);
5301            }
5302        }
5303        if let Err(err) = candidate.validate_capability_grammar() {
5304            return Ok(vec![control_error_frame(
5305                &frame,
5306                "invalid_capability_grammar",
5307                err.to_string(),
5308            )?]);
5309        }
5310
5311        // Updates must honor the same reserved owner as initial registration;
5312        // otherwise an empty HELLO could acquire the claim after admission.
5313        let mut conflicts = self
5314            .capability_evaluator
5315            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5316        if let Some(conflict) = conflicts.first() {
5317            let message = format!(
5318                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5319                conflict.capability, conflict.claimants[0], candidate.module_id
5320            );
5321            for conflict in &mut conflicts {
5322                conflict.source = DuplicateClaimSource::CatalogUpdate;
5323            }
5324            log_duplicate_claim_events(conflicts);
5325            return Ok(vec![control_error_frame(
5326                &frame,
5327                "reserved_capability",
5328                message,
5329            )?]);
5330        }
5331
5332        let updated = match self.registry.replace_catalog_for_connection(
5333            connection_id,
5334            provides,
5335            capabilities,
5336            ready,
5337        ) {
5338            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5339                return Ok(vec![control_error_frame(
5340                    &frame,
5341                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5342                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5343                )?])
5344            }
5345            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5346                return Ok(vec![control_error_frame(
5347                    &frame,
5348                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5349                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5350                )?])
5351            }
5352            result => {
5353                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5354            }
5355        };
5356        if updated.is_none() {
5357            return Ok(vec![control_error_frame(
5358                &frame,
5359                "not_registered",
5360                "catalog.update requires an active module registration owned by this connection",
5361            )?]);
5362        }
5363        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5364            log_duplicate_claim_events(
5365                self.capability_evaluator
5366                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5367            );
5368        }
5369        if capability_census_trigger(
5370            registration.manifest.capabilities.as_ref(),
5371            updated
5372                .as_ref()
5373                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5374        ) {
5375            self.enforce_capability_denies();
5376        }
5377        self.refresh_capability_requirements();
5378
5379        let response = ModuleControlResponseToModule::CatalogUpdate {};
5380        control_response_body_frame(
5381            &frame,
5382            &response,
5383            "ModuleControlResponseToModule::CatalogUpdate",
5384        )
5385        .map(|frame| vec![frame])
5386    }
5387
5388    pub(crate) fn with_activity_ledger_config(
5389        mut self,
5390        run_dir: &Path,
5391        incarnation: String,
5392        config: crate::activity::ActivityConfig,
5393    ) -> Self {
5394        self.activity = Some(crate::activity::ActivityLedger::open_config(
5395            run_dir.join("activity.jsonl"),
5396            incarnation,
5397            config,
5398        ));
5399        self.supervisor.set_activity(self.activity.clone());
5400        self
5401    }
5402
5403    pub(crate) async fn configure_activity(
5404        &self,
5405        config: crate::activity::ActivityConfig,
5406    ) -> Result<(), &'static str> {
5407        match &self.activity {
5408            Some(ledger) => ledger.configure(config).await,
5409            None => Ok(()),
5410        }
5411    }
5412
5413    fn cancel_activity_subscription(
5414        &self,
5415        ctx: &RouteCtx,
5416        frame: &Frame,
5417    ) -> Result<bool, RouterError> {
5418        let task = self
5419            .activity_streams
5420            .lock()
5421            .unwrap_or_else(|p| p.into_inner())
5422            .remove(&(ctx.connection_id, frame.header.corr));
5423        let Some(task) = task else {
5424            return Ok(false);
5425        };
5426        task.abort();
5427        let end = Frame::build_with_version(
5428            response_version(frame),
5429            FrameType::StreamEnd,
5430            control_flags(),
5431            0,
5432            0,
5433            frame.header.corr,
5434            Vec::new(),
5435        )
5436        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5437        let sink = ctx.egress.clone();
5438        tokio::spawn(async move {
5439            let _ = sink.send(end).await;
5440        });
5441        Ok(true)
5442    }
5443
5444    async fn handle_activity_read(
5445        &self,
5446        ctx: &RouteCtx,
5447        frame: Frame,
5448    ) -> Result<Vec<Frame>, RouterError> {
5449        #[cfg(test)]
5450        {
5451            let pause = self
5452                .activity_request_pause
5453                .lock()
5454                .unwrap()
5455                .clone()
5456                .filter(|pause| pause.connection == ctx.connection_id);
5457            if let Some(pause) = pause {
5458                let _cancelled = ActivityRequestCancellation(pause.clone());
5459                pause.started.notify_one();
5460                std::future::pending::<()>().await;
5461            }
5462        }
5463        use subc_control::{
5464            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5465            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5466        };
5467        #[derive(Deserialize)]
5468        struct Identity {
5469            #[serde(default)]
5470            consumer_identity: Option<ConsumerIdentity>,
5471        }
5472        // A registration channel or claim-bound connection carries its module in
5473        // its binding, so no request field can name another principal, and its
5474        // subscription ends when the bound spawn's authority does.
5475        let mut bound_spawn = None;
5476        let legacy = match self.activity_reader(ctx.connection_id) {
5477            channel_operations::ActivityReader::Module { module_id, spawn } => {
5478                bound_spawn = Some(spawn);
5479                Some(Ok(Principal::Reserved { module_id }))
5480            }
5481            // Refused outright: falling back to `direct` would admit it.
5482            channel_operations::ActivityReader::Refused => {
5483                return Ok(vec![control_error_frame(
5484                    &frame,
5485                    ACTIVITY_READ_FORBIDDEN,
5486                    "helper, relay and retired connections cannot read activity",
5487                )?]);
5488            }
5489            channel_operations::ActivityReader::Legacy => None,
5490        };
5491        // A registered module connection already identifies its caller. Ignore
5492        // consumer_identity there so a module cannot borrow a mirror's identity.
5493        // Only separate consumer connections use the Direct/nonce trust boundary.
5494        let principal = match legacy {
5495            Some(principal) => principal,
5496            None => match self
5497                .forwarding
5498                .module_id_for_connection(ctx.connection_id)
5499                .map_err(RouterError::Forwarding)?
5500            {
5501                Some(module_id) => Ok(Principal::Reserved { module_id }),
5502                None => {
5503                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5504                        Ok(identity) => identity,
5505                        Err(_) => {
5506                            return Ok(vec![control_error_frame(
5507                                &frame,
5508                                ACTIVITY_MALFORMED,
5509                                "malformed activity read",
5510                            )?])
5511                        }
5512                    };
5513                    self.route_open_principal(
5514                        ctx.connection_id,
5515                        &frame,
5516                        identity.consumer_identity,
5517                    )?
5518                }
5519            },
5520        };
5521        let admitted = matches!(principal, Ok(Principal::Direct))
5522            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5523        if !admitted {
5524            return Ok(vec![control_error_frame(
5525                &frame,
5526                ACTIVITY_READ_FORBIDDEN,
5527                "activity reads require an operator or trusted mirror principal",
5528            )?]);
5529        }
5530        let Some(ledger) = &self.activity else {
5531            return Ok(vec![control_error_frame(
5532                &frame,
5533                ACTIVITY_UNAVAILABLE,
5534                "activity ledger unavailable",
5535            )?]);
5536        };
5537        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5538            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5539        {
5540            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5541                Ok(request) => ledger.query(request).await,
5542                Err(_) => Err(ACTIVITY_MALFORMED),
5543            };
5544            return match result {
5545                Ok(reply) => Ok(vec![control_response_body_frame(
5546                    &frame,
5547                    &reply,
5548                    ops::ACTIVITY_QUERY,
5549                )?]),
5550                Err(code) => Ok(vec![control_error_frame(
5551                    &frame,
5552                    code,
5553                    "activity query refused",
5554                )?]),
5555            };
5556        }
5557        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5558            Ok(request) => request,
5559            Err(_) => {
5560                return Ok(vec![control_error_frame(
5561                    &frame,
5562                    ACTIVITY_MALFORMED,
5563                    "malformed activity subscription",
5564                )?])
5565            }
5566        };
5567        let mut subscription = match ledger.subscribe(request.since).await {
5568            Ok(subscription) => subscription,
5569            Err(code) => {
5570                return Ok(vec![control_error_frame(
5571                    &frame,
5572                    code,
5573                    "activity subscription refused",
5574                )?])
5575            }
5576        };
5577        let key = (ctx.connection_id, frame.header.corr);
5578        let sink = ctx.egress.clone();
5579        let mut streams = self
5580            .activity_streams
5581            .lock()
5582            .unwrap_or_else(|p| p.into_inner());
5583        streams.retain(|_, task| !task.is_finished());
5584        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5585            return Ok(vec![control_error_frame(
5586                &frame,
5587                "duplicate_subscription",
5588                "activity subscription correlation id already in use",
5589            )?]);
5590        }
5591        let stream = async move {
5592            loop {
5593                let entry = if let Some(entry) = subscription.replay.pop_front() {
5594                    Some(entry)
5595                } else {
5596                    subscription.receiver.recv().await
5597                };
5598                let Some(entry) = entry else {
5599                    break;
5600                };
5601                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5602                    return;
5603                };
5604                let Ok(next) = Frame::build_with_version(
5605                    response_version(&frame),
5606                    FrameType::StreamData,
5607                    control_flags(),
5608                    0,
5609                    0,
5610                    frame.header.corr,
5611                    body,
5612                ) else {
5613                    return;
5614                };
5615                if sink.send(next).await.is_err() {
5616                    return;
5617                }
5618            }
5619            // Dropping a full subscriber's sender drains its accepted entries
5620            // before the terminal error, preserving their order on the wire.
5621            if let Some(code) = subscription.terminal_code() {
5622                if let Ok(end) =
5623                    control_error_frame(&frame, code, "activity subscriber fell behind")
5624                {
5625                    let _ = sink.send(end).await;
5626                }
5627            }
5628        };
5629        // The spawn's retirement revokes this connection's authority. End the
5630        // subscription then, rather than when the connection's close is
5631        // eventually processed or the next entry fails to send.
5632        let task = tokio::spawn(async move {
5633            match bound_spawn {
5634                Some(spawn) => {
5635                    tokio::select! {
5636                        () = stream => {}
5637                        () = spawn.wait_closed() => {}
5638                    }
5639                }
5640                None => stream.await,
5641            }
5642        });
5643        streams.insert(key, task.abort_handle());
5644        Ok(Vec::new())
5645    }
5646
5647    async fn handle_activity_record(
5648        &self,
5649        ctx: &RouteCtx,
5650        frame: Frame,
5651    ) -> Result<Vec<Frame>, RouterError> {
5652        use subc_control::{
5653            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5654            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5655        };
5656        let result = async {
5657            let module = self
5658                .forwarding
5659                .module_id_for_connection(ctx.connection_id)
5660                .ok()
5661                .flatten()
5662                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5663            let request: ActivityRecordRequest =
5664                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5665            crate::activity::validate(&module, &request)?;
5666            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5667            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5668            let at_ms = std::time::SystemTime::now()
5669                .duration_since(std::time::UNIX_EPOCH)
5670                .unwrap_or_default()
5671                .as_millis() as u64;
5672            ledger.record(module, request, actor, at_ms).await
5673        }
5674        .await;
5675        match result {
5676            Ok(entry) => Ok(vec![control_response_body_frame(
5677                &frame,
5678                &ActivityRecordResponse { seq: entry.seq },
5679                "activity.record",
5680            )?]),
5681            Err(code) => Ok(vec![control_error_frame(
5682                &frame,
5683                code,
5684                "activity recording refused",
5685            )?]),
5686        }
5687    }
5688
5689    fn activity_actor(
5690        &self,
5691        connection: ConnectionId,
5692        module: &str,
5693        on: Option<&subc_control::ActivityOn>,
5694    ) -> Result<subc_control::ActivityActor, &'static str> {
5695        use crate::forwarding::{DataRoute, DataRouteState};
5696        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5697        let principal = |id: &str| Principal::Reserved {
5698            module_id: id.to_owned(),
5699        };
5700        let mut actor = ActivityActor {
5701            principal: principal(module),
5702            scope_owner: None,
5703            agent_id: None,
5704            run_id: None,
5705            flow_id: None,
5706            project_root: None,
5707            workdir: None,
5708            project_id: None,
5709        };
5710        let scope = match on {
5711            None => return Ok(actor),
5712            Some(ActivityOn::Scope(scope)) => {
5713                let selector = subc_protocol::scope::ScopeSelector::new(
5714                    principal(module),
5715                    scope.scope_ref.clone(),
5716                    Some(scope.epoch),
5717                );
5718                self.scopes
5719                    .read()
5720                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5721                    .attribute(&principal(module), module, &selector, true)
5722                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5723            }
5724            Some(ActivityOn::Route(route)) => {
5725                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5726                    .forwarding
5727                    .lookup_data_route(connection, route.channel, route.epoch)
5728                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5729                else {
5730                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5731                };
5732                if binding.module_id != module {
5733                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5734                }
5735                actor.principal = binding.principal.clone();
5736                actor.project_root = binding
5737                    .project_root
5738                    .as_ref()
5739                    .map(|root| root.as_path().to_path_buf());
5740                let Some(bound) = &binding.scope else {
5741                    return Ok(actor);
5742                };
5743                let owner = principal(&bound.owner);
5744                let selector = subc_protocol::scope::ScopeSelector::new(
5745                    owner.clone(),
5746                    bound.scope_ref.clone(),
5747                    Some(bound.tag.scope_epoch),
5748                );
5749                let admitted = self
5750                    .scopes
5751                    .read()
5752                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5753                    .attribute(&owner, module, &selector, true)
5754                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5755                if admitted.tag != bound.tag {
5756                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5757                }
5758                admitted
5759            }
5760        };
5761        actor.scope_owner = Some(scope.stamp.owner);
5762        actor.agent_id = scope.stamp.attributes.agent_id;
5763        actor.run_id = scope.stamp.attributes.run_id;
5764        actor.flow_id = scope.stamp.attributes.flow_id;
5765        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5766        actor.project_id = scope.stamp.project_id;
5767        Ok(actor)
5768    }
5769
5770    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5771        let module_id = self
5772            .claims
5773            .binding(connection)
5774            .filter(|binding| {
5775                binding.consumer_live(connection) && binding.registration.authority.alive()
5776            })
5777            .map(|binding| binding.registration.module_id.clone())
5778            .or_else(|| {
5779                self.registry
5780                    .module_id_for_connection(connection)
5781                    .ok()
5782                    .flatten()
5783            });
5784        let principal = module_id
5785            .map(|module_id| format!("reserved:{module_id}"))
5786            .unwrap_or_else(|| "direct".to_owned());
5787        self.control_usage
5788            .lock()
5789            .unwrap_or_else(|poisoned| poisoned.into_inner())
5790            .record(op, &principal);
5791    }
5792
5793    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5794        self.refresh_capability_requirements();
5795        // A bare connection count is ambiguous between many clients holding a
5796        // route each and one client accumulating hundreds, so publish the
5797        // concentration alongside it. Route state is best-effort here: a
5798        // diagnostic endpoint must still answer if the forwarding lock is
5799        // contended.
5800        let mut counters = self.counters.snapshot();
5801        if let Some(obj) = counters.as_object_mut() {
5802            obj.insert(
5803                "control_usage".into(),
5804                self.control_usage
5805                    .lock()
5806                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5807                    .snapshot(),
5808            );
5809        }
5810        let losses = self.resource_tracker.loss_diagnostics();
5811        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5812            if let Some(obj) = counters.as_object_mut() {
5813                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5814            }
5815        }
5816        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5817            obj.insert(
5818                "activity_unparseable_lines".into(),
5819                ledger.read_errors().into(),
5820            );
5821            obj.insert(
5822                "activity_lifecycle_append_failures".into(),
5823                ledger.lifecycle_failures().into(),
5824            );
5825            obj.insert(
5826                "activity_started_digest_skips".into(),
5827                ledger.lifecycle_digest_skips().into(),
5828            );
5829        }
5830        if let (Ok((connections_with_routes, max)), Some(obj)) = (
5831            self.forwarding.client_route_concentration(),
5832            counters.as_object_mut(),
5833        ) {
5834            obj.insert(
5835                "client_connections_with_routes".into(),
5836                connections_with_routes.into(),
5837            );
5838            obj.insert("max_routes_on_one_connection".into(), max.into());
5839        }
5840        // A module that is being fast-refused and a module that is fine look
5841        // identical from a client that retries and succeeds, so name the open
5842        // breakers here. This rides the existing free-form counters object
5843        // rather than a new wire field, so no sibling that deserializes
5844        // `ServerDescribe` has to be rebuilt to keep reading it.
5845        if let (Some(open_breakers), Some(obj)) = (
5846            self.route_bind_breakers.open_snapshot(),
5847            counters.as_object_mut(),
5848        ) {
5849            obj.insert("route_bind_breakers_open".into(), open_breakers);
5850        }
5851        // A daemon whose local endpoint could not be bound keeps serving TCP,
5852        // and the connection file names no endpoint. Name the reason here, in
5853        // the free-form counters object, so an operator reading daemon facts
5854        // sees it without searching the log, and no wire field changes.
5855        if let (Some(reason), Some(obj)) = (
5856            self.local_endpoint_unavailable.clone(),
5857            counters.as_object_mut(),
5858        ) {
5859            obj.insert("local_endpoint_unavailable".into(), reason.into());
5860        }
5861        let response = ClientControlResponse::ServerDescribe {
5862            protocol_ver: PROTOCOL_VERSION,
5863            subc_ops: subc_ops(),
5864            capabilities: self.describe_capabilities(),
5865            connected_clients: self.connected_clients.count(),
5866            counters: Some(counters),
5867            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
5868            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
5869            capability_requirements: self.capability_requirement_statuses(),
5870            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
5871            config_path: self
5872                .rescan
5873                .as_ref()
5874                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
5875        };
5876        Ok(vec![control_response_body_frame(
5877            &frame,
5878            &response,
5879            "ClientControlResponse::ServerDescribe",
5880        )?])
5881    }
5882
5883    fn handle_catalog_list(
5884        &self,
5885        frame: Frame,
5886        module_id: Option<String>,
5887    ) -> Result<Vec<Frame>, RouterError> {
5888        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
5889        Ok(vec![Frame::build_with_version(
5890            response_version(&frame),
5891            FrameType::Response,
5892            control_flags(),
5893            0,
5894            0,
5895            frame.header.corr,
5896            body,
5897        )
5898        .map_err(RouterError::FrameBuild)?])
5899    }
5900
5901    #[cfg(test)]
5902    fn uncached_catalog_list(
5903        &self,
5904        corr: u64,
5905        module_id: Option<&str>,
5906    ) -> Result<ClientControlResponse, RouterError> {
5907        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
5908    }
5909
5910    fn catalog_list_snapshot(
5911        &self,
5912        corr: u64,
5913        module_id: Option<&str>,
5914        include_declarations: bool,
5915    ) -> Result<ClientControlResponse, RouterError> {
5916        let (generation, modules) = self
5917            .registry
5918            .list_modules_with_nonce_verification()
5919            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
5920        let entries = modules
5921            .into_iter()
5922            .filter(|(registration, _)| {
5923                module_id
5924                    .map(|wanted| registration.manifest.module_id == wanted)
5925                    .unwrap_or(true)
5926            })
5927            .map(|(registration, nonce_verified)| {
5928                let entry = self
5929                    .catalog_discovery_entry(&registration, include_declarations)
5930                    .map_err(|err| RouterError::backend(0, corr, err))?;
5931                let not_ready = self.not_ready_reason(&registration);
5932                let mut entry = entry;
5933                entry.roles = registration.manifest.provides;
5934                entry.control_ops = registration.control_ops;
5935                Ok(entry
5936                    .with_ready(not_ready.is_none())
5937                    .with_display_name(registration.manifest.display_name)
5938                    .with_not_ready(not_ready)
5939                    .with_module_version(Some(registration.manifest.module_version))
5940                    .with_provenance(registration.manifest.provenance)
5941                    .with_capabilities(registration.manifest.capabilities)
5942                    .with_self_signals(registration.manifest.self_signals)
5943                    .with_events(registration.manifest.events)
5944                    .with_operation_delivery(registration.manifest.operation_delivery)
5945                    .with_operation_payload(registration.manifest.operation_payload)
5946                    .with_flow_operations(registration.manifest.flow_operations)
5947                    .with_operation_deferral(registration.manifest.operation_deferral)
5948                    .with_confirm_operations(registration.manifest.confirm_operations)
5949                    .with_rich_ui(registration.manifest.rich_ui)
5950                    .with_role_declarations(registration.manifest.role_declarations)
5951                    .with_nonce_verified(nonce_verified))
5952            })
5953            .collect::<Result<Vec<_>, RouterError>>()?;
5954        Ok(ClientControlResponse::CatalogList {
5955            generation,
5956            modules: entries,
5957            subc_ops: subc_ops(),
5958        })
5959    }
5960
5961    /// The caller fields for a refusal that only has the raw request frame,
5962    /// such as the connection-level admission refusal sent before the request
5963    /// reaches [`Self::handle_route_open`].
5964    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
5965        let Ok(ClientControlRequest::RouteOpen {
5966            identity,
5967            consumer_identity,
5968            scope,
5969            ..
5970        }) = parse_client_control_request(&frame.body)
5971        else {
5972            return RouteOpenCaller::unknown();
5973        };
5974        let principal = self
5975            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
5976            .map(|attested| attested.principal);
5977        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
5978    }
5979
5980    fn route_open_principal(
5981        &self,
5982        connection_id: ConnectionId,
5983        frame: &Frame,
5984        consumer_identity: Option<ConsumerIdentity>,
5985    ) -> Result<Result<Principal, Frame>, RouterError> {
5986        let attested = self
5987            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
5988            .map(|attested| attested.principal);
5989        self.route_open_principal_attested(frame, consumer_identity, attested)
5990    }
5991
5992    /// [`Self::route_open_principal`] with `attested` already taken by
5993    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
5994    /// claim or launch nonce once.
5995    fn route_open_principal_attested(
5996        &self,
5997        frame: &Frame,
5998        consumer_identity: Option<ConsumerIdentity>,
5999        attested: Option<Principal>,
6000    ) -> Result<Result<Principal, Frame>, RouterError> {
6001        if let Some(principal) = attested {
6002            return Ok(Ok(principal));
6003        }
6004        Ok(Err(control_error_frame(
6005            frame,
6006            "bad_consumer_identity",
6007            consumer_identity.map_or_else(
6008                || "connection claim is no longer authorized for routes".to_string(),
6009                |identity| format!(
6010                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
6011                    identity.module_id
6012                ),
6013            ),
6014        )?))
6015    }
6016
6017    /// Ordinary `route.open` refusals go through here; admission and breaker
6018    /// refusals log separately with their capacity or breaker state. The daemon can
6019    /// attest which code it sent: without the event, a client's "the daemon
6020    /// refused me" and the daemon's own view could only be reconciled by
6021    /// argument. Malformed input (`invalid_project_root`) does not come here;
6022    /// rejecting a request that was never a valid open is not a refusal of one.
6023    #[allow(clippy::too_many_arguments)]
6024    fn route_open_refusal_frame(
6025        &self,
6026        ctx: &RouteCtx,
6027        caller: &RouteOpenCaller,
6028        frame: &Frame,
6029        module_id: &str,
6030        reason: &'static str,
6031        code: &'static str,
6032        message: impl Into<String>,
6033    ) -> Result<Frame, RouterError> {
6034        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
6035        let detail = if matches!(
6036            reason,
6037            "registration_not_active"
6038                | "supervisor_not_live"
6039                | "no_forwarding_connection"
6040                | "reloading"
6041        ) {
6042            // A planned restart, reload or swap is already replacing the
6043            // process; it does not need a slot in the crash-restart budget.
6044            let expected_back = (reason == "reloading").then_some(true);
6045            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
6046        } else {
6047            None
6048        };
6049        control_error_body_frame(
6050            frame,
6051            ErrorBody {
6052                code: code.to_string(),
6053                message: message.into(),
6054                detail,
6055            },
6056        )
6057    }
6058
6059    fn route_open_recovery_detail(
6060        &self,
6061        module_id: &str,
6062        corr: u64,
6063        detail: Option<serde_json::Value>,
6064        expected_back: Option<bool>,
6065    ) -> Result<Option<serde_json::Value>, RouterError> {
6066        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
6067            return Ok(detail);
6068        };
6069        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
6070        detail["state"] = serde_json::json!(status.state.to_string());
6071        if let Some(expected_back) = expected_back {
6072            detail["expected_back"] = serde_json::json!(expected_back);
6073        } else if let Some(module) = self.supervisor.get(module_id) {
6074            match module.will_recover_after_connection_loss() {
6075                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
6076                Err(err) => warn!(
6077                    %module_id,
6078                    error = %err,
6079                    "failed to read route.open recovery verdict; omitting expected_back"
6080                ),
6081            }
6082        }
6083        Ok(Some(detail))
6084    }
6085
6086    /// Answer a waiting `route.open` whose relayed bind was refused.
6087    ///
6088    /// `daemon_authored` is provenance, not a code match: the daemon
6089    /// synthesized the refusal itself (a drain, a late reply, a scope that
6090    /// ended mid-bind) or the module refused the bind with its own body. A
6091    /// daemon refusal carries the daemon-origin bit; a module's own
6092    /// rejection is relayed with the bit clear, so a module that refuses
6093    /// with `module_reloading` still cannot mint a daemon refusal.
6094    #[allow(clippy::too_many_arguments)]
6095    fn route_bind_rejection(
6096        &self,
6097        ctx: &RouteCtx,
6098        caller: &RouteOpenCaller,
6099        frame: &Frame,
6100        target_module_id: &str,
6101        body: ErrorBody,
6102        daemon_authored: bool,
6103    ) -> Result<Vec<Frame>, RouterError> {
6104        // The daemon's own commit re-check refused the bind because the
6105        // scope ended or changed after admission. The module accepted;
6106        // counting it as a module rejection would blame the module. This
6107        // branch only runs for daemon-synthesized bodies: a module that
6108        // refuses with a scope code is answered as a module rejection below.
6109        if daemon_authored {
6110            let scope_code = match body.code.as_str() {
6111                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
6112                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
6113                _ => None,
6114            };
6115            if let Some(code) = scope_code {
6116                self.observe_route_open_refusal(
6117                    ctx,
6118                    caller,
6119                    target_module_id,
6120                    "scope_changed_before_commit",
6121                    code,
6122                );
6123                return Ok(vec![control_error_body_frame(frame, body)?]);
6124            }
6125        }
6126        self.counters
6127            .increment_route_open_refused("module_rejected");
6128        info!(
6129            target: "control",
6130            code = "module_rejected",
6131            module_code = ?body.code,
6132            module_id = ?target_module_id,
6133            connection_id = ctx.connection_id.get(),
6134            principal = %caller.principal,
6135            scope = %caller.scope,
6136            harness = %caller.harness,
6137            "route.open refused"
6138        );
6139        let refusal = if daemon_authored {
6140            control_error_body_frame(frame, body)?
6141        } else {
6142            control_relayed_error_body_frame(frame, body)?
6143        };
6144        Ok(vec![refusal])
6145    }
6146
6147    /// Refuse a `route.open` because the target module's bind-relay breaker is
6148    /// open, without attempting the relay.
6149    ///
6150    /// The wire code is `module_timeout`, which is the truth (the module has
6151    /// not been answering binds) and which both SDKs already classify as
6152    /// retryable with capped backoff. Reusing it is what keeps this change out
6153    /// of both SDKs; the daemon-side distinction lives in the counter key
6154    /// instead.
6155    ///
6156    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6157    /// While a breaker is open this fires on every open to that module, and the
6158    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6159    /// produced 261 lines about a single module inside 3000 lines of daemon
6160    /// log. The rare transitions are logged at warn/info instead and the volume
6161    /// is carried by the counter, so the evidence survives without the flood.
6162    /// The debug line keeps a per-refusal record reachable for whoever turns
6163    /// the level up.
6164    #[allow(clippy::too_many_arguments)]
6165    fn route_open_breaker_refusal_frame(
6166        &self,
6167        ctx: &RouteCtx,
6168        caller: &RouteOpenCaller,
6169        frame: &Frame,
6170        module_id: &str,
6171        consecutive_timeouts: u32,
6172        retry_in: Duration,
6173        probe_in_flight: bool,
6174    ) -> Result<Frame, RouterError> {
6175        self.counters
6176            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6177        debug!(
6178            target: "control",
6179            code = "module_timeout",
6180            module_id = ?module_id,
6181            connection_id = ctx.connection_id.get(),
6182            principal = %caller.principal,
6183            scope = %caller.scope,
6184            harness = %caller.harness,
6185            consecutive_timeouts,
6186            retry_in_ms = retry_in.as_millis() as u64,
6187            probe_in_flight,
6188            "route.open refused by open bind-relay breaker"
6189        );
6190        // Say what a caller can act on. An open bind-relay breaker means the
6191        // module timed out accepting several new routes in a row. The module
6192        // is still running and its established routes keep working; only new
6193        // route.open requests are refused until the cooldown ends and one
6194        // test route (the probe) gets through. A message that only counts
6195        // failed relays reads as "the module is down" to a worker that sees it.
6196        let detail = if probe_in_flight {
6197            "one test route is already being tried; retry once it settles".to_string()
6198        } else {
6199            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6200        };
6201        control_error_frame(
6202            frame,
6203            "module_timeout",
6204            format!(
6205                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6206                 timed out in a row); {detail}; its established routes are unaffected"
6207            ),
6208        )
6209    }
6210
6211    /// `code` is daemon vocabulary and prints plainly; `module_id` is the
6212    /// requester's bytes (an unknown target is whatever the client sent) and
6213    /// is Debug-formatted so control characters land in the log escaped
6214    /// rather than as terminal sequences for whoever tails it.
6215    ///
6216    /// `reason` names the check that refused, because one wire code has
6217    /// several senders: after a module registers, `target_unavailable` can
6218    /// come from a missing role, an inactive registration, a supervisor that
6219    /// has not marked the process live, a missing forwarding connection, or a
6220    /// failed relay, and a log that records only the code cannot say which of
6221    /// them fired. It is a static, daemon-chosen label per branch, so it is
6222    /// safe to print plainly and stays a closed set.
6223    fn observe_route_open_refusal(
6224        &self,
6225        ctx: &RouteCtx,
6226        caller: &RouteOpenCaller,
6227        module_id: &str,
6228        reason: &'static str,
6229        code: &'static str,
6230    ) {
6231        self.counters.increment_route_open_refused(code);
6232        info!(
6233            target: "control",
6234            code,
6235            reason,
6236            module_id = ?module_id,
6237            connection_id = ctx.connection_id.get(),
6238            principal = %caller.principal,
6239            scope = %caller.scope,
6240            harness = %caller.harness,
6241            "route.open refused"
6242        );
6243        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6244            self.route_outages.record_not_serving(module_id, reason);
6245        }
6246    }
6247
6248    /// Record an ACCEPTED route.open.
6249    ///
6250    /// Refusals have been logged and counted since the attestation work; accepts
6251    /// were invisible, so the daemon knew every principal it stamped and wrote
6252    /// none of them down. The party that attests the identity was the only party
6253    /// not recording it, which left a credential vault unable to name the sender
6254    /// of a call that reached it (claustrum #43) and left the launch-nonce
6255    /// concurrency question unanswerable from the outside.
6256    ///
6257    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6258    /// `code`/`module_id`/`connection_id` returns both directions of the same
6259    /// decision rather than two shapes a reader has to join by hand.
6260    ///
6261    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6262    /// and the difference carries information rather than being an
6263    /// inconsistency. This line is only reachable after a successful bind to a
6264    /// REGISTERED module, so the value has already passed HELLO validation
6265    /// including the path-hazard refusal and cannot contain control bytes. A
6266    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6267    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6268    ///
6269    /// Bare is also what every other daemon line already emits (`module
6270    /// registered`, `configured module supervised`). Shipping `?module_id` here
6271    /// made this instrument the only one in the file whose ids did not answer
6272    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6273    /// line whose whole purpose is being grepped beside its sibling.
6274    ///
6275    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6276    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6277    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6278    /// one are recorded identically. A test written against that harness passes
6279    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6280    /// green assertion that cannot fail. The same limit applies to the escaping
6281    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6282    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6283    /// Fencing either needs the real formatter, not the capture layer.
6284    ///
6285    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6286    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6287    /// to record. The ephemeral port would decay within minutes and answer only a
6288    /// live question. The identity question is instead answered by counting
6289    /// distinct live connections presenting one module's `consumer_identity` --
6290    /// "is anyone else holding this secret" rather than "is this the right
6291    /// process".
6292    fn observe_route_open_accept(
6293        &self,
6294        ctx: &RouteCtx,
6295        module_id: &str,
6296        principal: &str,
6297        scope: &str,
6298    ) {
6299        self.route_outages.record_accepted(module_id);
6300        self.counters.increment_route_open_accepted(principal);
6301        debug!(
6302            target: "control",
6303            principal,
6304            module_id,
6305            connection_id = ctx.connection_id.get(),
6306            scope = %scope,
6307            "route.open accepted"
6308        );
6309    }
6310
6311    fn supervised_absent_route_open_refusal_frame(
6312        &self,
6313        ctx: &RouteCtx,
6314        caller: &RouteOpenCaller,
6315        frame: &Frame,
6316        module_id: &str,
6317        code: &'static str,
6318        status: &crate::supervise::ModuleStatus,
6319    ) -> Result<Frame, RouterError> {
6320        self.counters.increment_route_open_refused(code);
6321        info!(
6322            target: "control",
6323            code,
6324            reason = "supervised_not_registered",
6325            module_id = ?module_id,
6326            connection_id = ctx.connection_id.get(),
6327            principal = %caller.principal,
6328            scope = %caller.scope,
6329            harness = %caller.harness,
6330            state = %status.state,
6331            enabled = status.enabled,
6332            live = status.live,
6333            "route.open refused"
6334        );
6335        // A supervised module whose process has not registered is not
6336        // serving, whatever the reason; the supervisor knows this id, so it is
6337        // safe to track.
6338        self.route_outages
6339            .record_not_serving(module_id, "supervised_not_registered");
6340        let message = if let Some(pid) = status.waiting_for_previous_pid {
6341            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6342                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6343            })
6344        } else {
6345            format!(
6346                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6347                status.state, status.enabled, status.live
6348            )
6349        };
6350        // `module_warming` here means the process is starting, running or
6351        // being restarted and has not registered yet. Nothing has to be
6352        // restarted for it to serve, so the crash budget does not decide it.
6353        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6354        control_error_body_frame(
6355            frame,
6356            ErrorBody {
6357                code: code.to_string(),
6358                message,
6359                detail: self.route_open_recovery_detail(
6360                    module_id,
6361                    frame.header.corr,
6362                    None,
6363                    expected_back,
6364                )?,
6365            },
6366        )
6367    }
6368
6369    async fn handle_route_open(
6370        &self,
6371        ctx: &RouteCtx,
6372        frame: Frame,
6373        request: RouteOpenRequest,
6374        timings: &mut RouteOpenTimings,
6375    ) -> Result<Vec<Frame>, RouterError> {
6376        let RouteOpenRequest {
6377            target,
6378            mut identity,
6379            consumer_identity,
6380            consumer_capabilities,
6381            role_versions,
6382            busy_refusals,
6383            admission_facts,
6384            scope,
6385            accepts_close_reasons,
6386        } = request;
6387        let target_module_id = target_module_id(&target).to_string();
6388        timings.module_id.clone_from(&target_module_id);
6389        if self
6390            .registry
6391            .get_module_by_connection(ctx.connection_id)
6392            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6393            .is_some()
6394        {
6395            return Ok(vec![control_error_frame(
6396                &frame,
6397                "invalid_request",
6398                "module connections cannot open client routes",
6399            )?]);
6400        }
6401        debug!(
6402            connection_id = ctx.connection_id.get(),
6403            corr = frame.header.corr,
6404            module_id = %target_module_id,
6405            "handling route.open"
6406        );
6407
6408        // The caller's attested principal, requested scope and harness, for
6409        // every `route.open refused` line below. The connection's claim
6410        // binding or launch nonce is checked here, once, and the answer is
6411        // reused where the principal is enforced further down, so the order
6412        // of refusals is unchanged.
6413        let attested =
6414            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6415        let mut caller = RouteOpenCaller::new(
6416            attested.as_ref().map(|attested| &attested.principal),
6417            scope.as_ref(),
6418            &identity,
6419        );
6420
6421        // A malformed declaration is refused first, before anything about the
6422        // target is looked up: the same body would be refused against any
6423        // module, so the caller learns nothing by retrying or waiting. An empty
6424        // map declares nothing and travels as no field at all, so a provider
6425        // only ever sees a missing field or a non-empty one.
6426        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6427        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6428            self.observe_route_open_refusal(
6429                ctx,
6430                &caller,
6431                &target_module_id,
6432                "invalid_role_versions",
6433                error_codes::INVALID_REQUEST,
6434            );
6435            return Ok(vec![control_error_body_frame(
6436                &frame,
6437                ErrorBody {
6438                    code: error_codes::INVALID_REQUEST.to_string(),
6439                    message: error.to_string(),
6440                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6441                },
6442            )?]);
6443        }
6444
6445        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6446            if status.waiting_for_previous_pid.is_some() {
6447                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6448                    ctx,
6449                    &caller,
6450                    &frame,
6451                    &target_module_id,
6452                    "module_warming",
6453                    &status,
6454                )?]);
6455            }
6456        }
6457
6458        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6459        // opposite. Below, a caller learns whether a module is unregistered,
6460        // supervised-but-down (with state/enabled/live), or registered without the
6461        // requested role. Elsewhere that is an enumeration leak: a probe learning
6462        // the shape of a fleet it cannot otherwise see.
6463        //
6464        // It is not one here, and the reason is the ACCESS MODEL rather than
6465        // anything about these errors. Reaching route.open requires the
6466        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6467        // connection file, so any caller who completes it already runs as this
6468        // user -- and can read subc.jsonc for the module list and `ck module
6469        // status` for live state. The reply discloses nothing the caller cannot
6470        // read more easily from disk, while the precision is load-bearing:
6471        // `unknown_module` is retryable and a missing role is not.
6472        //
6473        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6474        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6475        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6476        let admission_registry = self
6477            .registry
6478            .route_admission_snapshot()
6479            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6480        let Some(registration) =
6481            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6482        else {
6483            if let Some((status, warming)) =
6484                self.supervisor_status(&target_module_id, frame.header.corr)?
6485            {
6486                // BEFORE the two availability codes below, because for a module
6487                // that speaks no subc wire both of them are false comfort: they
6488                // say "not right now" and are retried, and this module will
6489                // never register no matter how long the caller waits. The
6490                // absence here is the declaration being honoured, not a module
6491                // that is late.
6492                if status.protocol == ModuleProtocol::None {
6493                    return Ok(vec![self.route_open_refusal_frame(
6494                        ctx,
6495                        &caller,
6496                        &frame,
6497                        &target_module_id,
6498                        "protocol_none",
6499                        error_codes::MODULE_NO_PROTOCOL,
6500                        format!(
6501                            "module_id '{target_module_id}' is declared protocol: none; \
6502                             it speaks no subc wire and serves no routes"
6503                        ),
6504                    )?]);
6505                }
6506                let code = if warming {
6507                    "module_warming"
6508                } else {
6509                    "target_unavailable"
6510                };
6511                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6512                    ctx,
6513                    &caller,
6514                    &frame,
6515                    &target_module_id,
6516                    code,
6517                    &status,
6518                )?]);
6519            }
6520            if let Some(removed_ago_ms) =
6521                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6522            {
6523                return Ok(vec![self.route_open_refusal_frame(
6524                    ctx,
6525                    &caller,
6526                    &frame,
6527                    &target_module_id,
6528                    "removed",
6529                    error_codes::MODULE_REMOVED,
6530                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6531                )?]);
6532            }
6533            return Ok(vec![self.route_open_refusal_frame(
6534                ctx,
6535                &caller,
6536                &frame,
6537                &target_module_id,
6538                "not_registered",
6539                error_codes::UNKNOWN_MODULE,
6540                format!("module_id '{target_module_id}' is not registered"),
6541            )?]);
6542        };
6543
6544        // Best-effort only: registry readiness and forwarding reservation use
6545        // different locks, so a module can flip readiness between this read and
6546        // the relay. Modules must still tolerate an `on_bind` while not ready.
6547        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6548            .is_err()
6549        {
6550            self.counters
6551                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6552            info!(
6553                target: "control",
6554                code = error_codes::MODULE_WARMING,
6555                module_id = ?target_module_id,
6556                connection_id = ctx.connection_id.get(),
6557                principal = %caller.principal,
6558                scope = %caller.scope,
6559                harness = %caller.harness,
6560                reason = "declared_not_ready",
6561                "route.open refused"
6562            );
6563            // The module is registered but says it cannot take work, which is
6564            // an outage from the caller's side even though its process is up.
6565            self.route_outages
6566                .record_not_serving(&target_module_id, "declared_not_ready");
6567            // The registered process can declare itself ready without a
6568            // restart, so an exhausted crash budget does not prevent serving.
6569            return Ok(vec![control_error_body_frame(
6570                &frame,
6571                ErrorBody {
6572                    code: error_codes::MODULE_WARMING.to_string(),
6573                    message: format!(
6574                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6575                    ),
6576                    detail: self.route_open_recovery_detail(
6577                        &target_module_id,
6578                        frame.header.corr,
6579                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6580                        Some(true),
6581                    )?,
6582                },
6583            )?]);
6584        }
6585
6586        // Effective readiness, second half: a module that declares a capability
6587        // `need: required` is not routable while that capability has no
6588        // registered provider. It is enforced HERE, as a retryable routing
6589        // refusal, and deliberately not as spawn ordering or a boot block. The
6590        // module is still started and registered and can make its own calls;
6591        // spawn ordering is a promise that cannot be kept once a provider
6592        // crashes at runtime, and refusing to boot would stop the whole
6593        // machine, including the tools needed to fix its configuration.
6594        //
6595        // "Provided" is the evaluator's verdict, which counts a provider as
6596        // soon as it has REGISTERED, not once it is ready. Two modules that
6597        // require each other's capabilities are therefore both routable once
6598        // both register; counting readiness instead would deadlock them.
6599        //
6600        // Only new opens are refused. Routes already bound when a provider
6601        // goes away stay bound: nothing here tears them down, and the module
6602        // answers them as it can. Like the readiness read above this is
6603        // best-effort against a provider registering or leaving concurrently.
6604        if let Some(capability) = self.first_unprovided_required_capability_for(
6605            &registration.module_id,
6606            registration.capabilities.as_ref(),
6607        ) {
6608            self.counters
6609                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6610            info!(
6611                target: "control",
6612                code = error_codes::MODULE_WARMING,
6613                module_id = ?target_module_id,
6614                connection_id = ctx.connection_id.get(),
6615                principal = %caller.principal,
6616                scope = %caller.scope,
6617                harness = %caller.harness,
6618                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6619                capability = %capability,
6620                "route.open refused"
6621            );
6622            return Ok(vec![control_error_body_frame(
6623                &frame,
6624                ErrorBody {
6625                    code: error_codes::MODULE_WARMING.to_string(),
6626                    message: format!(
6627                        "module_id '{target_module_id}' requires capability '{capability}', \
6628                         which no registered module provides; retry"
6629                    ),
6630                    detail: Some(serde_json::json!({
6631                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6632                        "capability": capability,
6633                    })),
6634                },
6635            )?]);
6636        }
6637
6638        if !target_has_required_role(&target, &registration.roles) {
6639            return Ok(vec![self.route_open_refusal_frame(
6640                ctx,
6641                &caller,
6642                &frame,
6643                &target_module_id,
6644                "role_not_provided",
6645                "target_unavailable",
6646                format!("module_id '{target_module_id}' does not provide the requested target"),
6647            )?]);
6648        }
6649
6650        if registration.state != ChannelState::Active {
6651            return Ok(vec![self.route_open_refusal_frame(
6652                ctx,
6653                &caller,
6654                &frame,
6655                &target_module_id,
6656                "registration_not_active",
6657                "target_unavailable",
6658                format!("module_id '{target_module_id}' is not active"),
6659            )?]);
6660        }
6661
6662        if self
6663            .forwarding
6664            .module_is_draining(&target_module_id)
6665            .map_err(RouterError::Forwarding)?
6666        {
6667            return Ok(vec![self.route_open_refusal_frame(
6668                ctx,
6669                &caller,
6670                &frame,
6671                &target_module_id,
6672                "reloading",
6673                "module_reloading",
6674                format!("module_id '{target_module_id}' is reloading"),
6675            )?]);
6676        }
6677
6678        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6679            process_liveness.process_live(&target_module_id) == Some(false)
6680        }) {
6681            // A module the supervisor is restarting or reloading can still hold
6682            // a registration: the old process before its connection closes, or
6683            // a new one that registered while the supervisor was draining. The
6684            // forwarding table does not see that as draining, but the consumer
6685            // should still be told to retry soon, exactly as for the drain
6686            // above, rather than that the target is unavailable.
6687            if process_liveness.process_replacing(&target_module_id) {
6688                return Ok(vec![self.route_open_refusal_frame(
6689                    ctx,
6690                    &caller,
6691                    &frame,
6692                    &target_module_id,
6693                    "reloading",
6694                    "module_reloading",
6695                    format!("module_id '{target_module_id}' is reloading"),
6696                )?]);
6697            }
6698            return Ok(vec![self.route_open_refusal_frame(
6699                ctx,
6700                &caller,
6701                &frame,
6702                &target_module_id,
6703                "supervisor_not_live",
6704                "target_unavailable",
6705                format!("module_id '{target_module_id}' is not live"),
6706            )?]);
6707        }
6708
6709        if !self
6710            .forwarding
6711            .has_live_module_connection(&target_module_id)
6712            .map_err(RouterError::Forwarding)?
6713        {
6714            return Ok(vec![self.route_open_refusal_frame(
6715                ctx,
6716                &caller,
6717                &frame,
6718                &target_module_id,
6719                "no_forwarding_connection",
6720                "target_unavailable",
6721                format!("module_id '{target_module_id}' has no live forwarding connection"),
6722            )?]);
6723        }
6724
6725        if let Some(error) =
6726            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6727        {
6728            self.observe_route_open_refusal(
6729                ctx,
6730                &caller,
6731                &target_module_id,
6732                "op_not_allowed",
6733                "op_not_allowed",
6734            );
6735            return Ok(vec![error]);
6736        }
6737
6738        let principal = match (&attested, consumer_identity.is_some()) {
6739            // A claim-bound connection whose launch ended attests nothing,
6740            // and it must never fall back to opening as `direct`.
6741            (None, false) => {
6742                self.observe_route_open_refusal(
6743                    ctx,
6744                    &caller,
6745                    &target_module_id,
6746                    "registration_channel_closed",
6747                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6748                );
6749                return Ok(vec![control_error_frame(
6750                    &frame,
6751                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6752                    "the claim binding's launch has ended",
6753                )?]);
6754            }
6755            _ => match self.route_open_principal_attested(
6756                &frame,
6757                consumer_identity,
6758                attested.as_ref().map(|attested| attested.principal.clone()),
6759            )? {
6760                Ok(principal) => principal,
6761                Err(error) => {
6762                    self.observe_route_open_refusal(
6763                        ctx,
6764                        &caller,
6765                        &target_module_id,
6766                        "bad_consumer_identity",
6767                        "bad_consumer_identity",
6768                    );
6769                    return Ok(vec![error]);
6770                }
6771            },
6772        };
6773        let attested = attested.expect("an attested principal was resolved above");
6774        timings.principal = principal_label(&principal);
6775
6776        // The opener's spawn authority, read once here and carried with the
6777        // relay; nothing below reads its record again.
6778        let Ok(mut caller_capture) = attested.capture() else {
6779            self.observe_route_open_refusal(
6780                ctx,
6781                &caller,
6782                &target_module_id,
6783                "registration_channel_closed",
6784                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6785            );
6786            return Ok(vec![control_error_frame(
6787                &frame,
6788                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6789                "the opener's launch has ended",
6790            )?]);
6791        };
6792        // The caller-side checks below read the opener's own spawn: its
6793        // module from its record and its manifest from its own registration,
6794        // never another launch's active registration under the same id.
6795        let caller_module_id = match &attested.spawn {
6796            Some((record, _)) => Some(record.module_id().to_owned()),
6797            None => match &principal {
6798                Principal::Reserved { module_id } => Some(module_id.clone()),
6799                _ => None,
6800            },
6801        };
6802
6803        // Only Callosum can attest a production phone build. Consume the raw
6804        // claim here; opted-in targets receive only the honoured peer fact.
6805        let build_class = identity.build_class.take().filter(|build_class| {
6806            if caller_module_id.as_deref() == Some("callosum") {
6807                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6808            } else {
6809                if self
6810                    .build_class_warned
6811                    .lock()
6812                    .unwrap_or_else(|p| p.into_inner())
6813                    .insert(ctx.connection_id)
6814                {
6815                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6816                        "ignoring build_class from a non-Callosum opener");
6817                }
6818                false
6819            }
6820        });
6821
6822        // This is attested, control-plane policy for supervised module origins.
6823        // Keep it before route reservation and out of the opaque forwarding hot
6824        // path: data frames must never acquire a per-frame capability check.
6825        if let Some(opening_registration) = self.caller_registration(&attested, &admission_registry)
6826        {
6827            let opening_module_id = opening_registration.module_id.as_str();
6828            if let Some(capability) = denied_capability(
6829                opening_registration.capabilities.as_ref(),
6830                registration.capabilities.as_ref(),
6831            ) {
6832                warn!(
6833                    opening_module_id,
6834                    target_module_id,
6835                    capability,
6836                    "refusing route.open because an attested capability deny edge matches"
6837                );
6838                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6839                    &frame,
6840                    &target_module_id,
6841                    "capability_deny_edge",
6842                    "capability_forbidden",
6843                    format!(
6844                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
6845                    ),
6846                )?]);
6847            }
6848        }
6849
6850        if admission_facts.is_some() {
6851            let carrier_matches = caller_module_id.is_some()
6852                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
6853            if !carrier_matches {
6854                return Ok(vec![self.route_open_refusal_frame(
6855                    ctx,
6856                    &caller,
6857                    &frame,
6858                    &target_module_id,
6859                    "admission_facts_carrier_not_permitted",
6860                    "admission_facts_not_permitted",
6861                    "admission facts may only be carried by the configured reserved module",
6862                )?]);
6863            }
6864
6865            let target_allowed = self
6866                .admission_facts_targets
6867                .as_ref()
6868                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
6869            if !target_allowed {
6870                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6871                    &frame,
6872                    &target_module_id,
6873                    "admission_facts_target_not_listed",
6874                    "admission_facts_target_not_allowed",
6875                    format!(
6876                        "admission facts are not permitted for target module_id '{target_module_id}'"
6877                    ),
6878                )?]);
6879            }
6880
6881            // Keep the value opaque to subc. The downstream admission validator owns
6882            // schema and semantic checks; this daemon only enforces carrier authority
6883            // and the configured destination allowlist.
6884        }
6885
6886        // Scope admission, on the attested principal above and never on the
6887        // request body. The tag read here travels with the pending bind and is
6888        // compared with the published one at commit, so a sync between here
6889        // and the module's ack refuses the open instead of binding a stamp
6890        // that is no longer true.
6891        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
6892            None => (None, None, false),
6893            Some(selector) => {
6894                let owner_configured = match &selector.owner {
6895                    // A reserved owner counts as configured from before its
6896                    // process is spawned (see `SupervisorHandle::is_configured`).
6897                    // So an owner that has not synced its scopes yet is refused
6898                    // as retryable (`scope_not_synced`), not as one that will
6899                    // never sync.
6900                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
6901                    _ => false,
6902                };
6903                let mut scopes = self
6904                    .scopes
6905                    .write()
6906                    .unwrap_or_else(|poisoned| poisoned.into_inner());
6907                let admitted = crate::scopes::admission::admit_route(
6908                    &scopes,
6909                    &admission_registry,
6910                    &principal,
6911                    &target_module_id,
6912                    Some(selector),
6913                    owner_configured,
6914                    crate::scopes::admission::AdmissionMode::Open,
6915                )
6916                .map(|route| {
6917                    let admission = route.scope.expect("scoped admission");
6918                    let bound = scopes.reserve_bind(
6919                        &admission,
6920                        &principal,
6921                        ctx.connection_id,
6922                        selector.hold_presence,
6923                    );
6924                    (admission, bound)
6925                });
6926                match admitted {
6927                    Ok((admission, bound)) => {
6928                        (Some(bound), Some(admission.stamp), admission.stamp_required)
6929                    }
6930                    Err(refusal) => {
6931                        return Ok(vec![self.route_open_refusal_frame(
6932                            ctx,
6933                            &caller,
6934                            &frame,
6935                            &target_module_id,
6936                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6937                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6938                            refusal.message,
6939                        )?]);
6940                    }
6941                }
6942            }
6943        };
6944        // From here on a refusal names the scope by the stamp admission
6945        // issued, exactly as the `route.open accepted` line does.
6946        if let Some(stamp) = &scope_stamp {
6947            caller.scope = route_open_scope_label(stamp);
6948        }
6949        // Decided from the admitted stamp, before any field of it is stripped
6950        // for a target that lacks the capability to read it.
6951        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
6952            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
6953        }
6954
6955        // Allow resolvable missing-tail paths so a vanished directory does not
6956        // prevent reopening an existing session for cleanup. Binding does not
6957        // authorize creation of durable provider state.
6958        //
6959        // Resolve real paths rather than lexical cleanup: canonicalize the
6960        // longest existing ancestor and append the missing tail, retaining the
6961        // path's real existing ancestry even when a leaf is missing.
6962        timings.enter(RouteOpenPhase::ProjectRoot);
6963        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
6964            Ok(project) => project,
6965            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
6966        };
6967        timings.enter(RouteOpenPhase::Admission);
6968        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
6969            Ok(root) => root,
6970            Err(err) => {
6971                return Ok(vec![control_error_frame(
6972                    &frame,
6973                    "invalid_project_root",
6974                    err.to_string(),
6975                )?])
6976            }
6977        };
6978        // Compute compatibility project fields before stripping optional stamp
6979        // members. Preserve the canonical opener root and its project ID,
6980        // including absence. For rootless openers, use stamp workdir or `/`, and
6981        // opener ID, else stamp ID, else no ID. Emit these identity fields only
6982        // to targets without bind-no-project/v1.
6983        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
6984
6985        // Last gate before any relay work, and deliberately after the cheap
6986        // registry and availability checks above: those name a more precise
6987        // condition (unknown, removed, reloading) and a caller is better served
6988        // by the precise code than by this one.
6989        //
6990        // Everything below this point costs an egress permit, a reserved handle
6991        // pair and, if the module does not answer, the whole relay budget. The
6992        // reader no longer waits for that budget, so cap each target explicitly;
6993        // serial dispatch used to provide the accidental cap of one relay per
6994        // connection. Admission is a mutex-protected count and never waits.
6995        let _concurrency_guard = match self
6996            .route_bind_concurrency
6997            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
6998        {
6999            Ok(guard) => guard,
7000            Err(in_flight) => {
7001                return Ok(vec![self.route_open_target_capacity_refusal(
7002                    ctx,
7003                    &caller,
7004                    &frame,
7005                    &target_module_id,
7006                    in_flight,
7007                )?]);
7008            }
7009        };
7010
7011        // A module that has already burned the whole budget `threshold` times
7012        // in a row does not get to charge it again until a probe says it recovered.
7013        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
7014            RouteBindAdmission::Admitted { guard, probe } => {
7015                if probe {
7016                    info!(
7017                        module_id = %target_module_id,
7018                        connection_id = ctx.connection_id.get(),
7019                        "route.bind breaker half-open: admitting one probe"
7020                    );
7021                }
7022                guard
7023            }
7024            RouteBindAdmission::Refused {
7025                consecutive_timeouts,
7026                retry_in,
7027                probe_in_flight,
7028            } => {
7029                return Ok(vec![self.route_open_breaker_refusal_frame(
7030                    ctx,
7031                    &caller,
7032                    &frame,
7033                    &target_module_id,
7034                    consecutive_timeouts,
7035                    retry_in,
7036                    probe_in_flight,
7037                )?]);
7038            }
7039        };
7040
7041        let operator_app = self
7042            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
7043            .await;
7044        // Resolve the per-module budget here so the wait matches the operator's
7045        // intent for this specific target. A per-module override in
7046        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
7047        // daemons) wins over the daemon-wide default.
7048        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
7049        let relay_deadline = Instant::now() + route_bind_relay_timeout;
7050        let production_peer_build =
7051            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
7052        timings.enter(RouteOpenPhase::EgressReservation);
7053        let pending = match self
7054            .forwarding
7055            .begin_route_bind_relay_for(
7056                ctx.connection_id,
7057                ctx.egress.clone(),
7058                response_version(&frame),
7059                frame.header.corr,
7060                &target_module_id,
7061                principal.clone(),
7062                bound_scope,
7063                project_root,
7064                identity.harness.clone(),
7065                build_class,
7066                operator_app.clone(),
7067                crate::forwarding::RouteAuthority {
7068                    incarnation: self.supervisor.daemon_incarnation(),
7069                    caller: caller_capture
7070                        .as_ref()
7071                        .map(|caller| caller.authority.pair()),
7072                },
7073                relay_deadline,
7074                busy_refusals == Some(true),
7075                accepts_close_reasons,
7076            )
7077            .await
7078        {
7079            Ok(pending) => pending,
7080            Err(err) => {
7081                return Ok(vec![self.route_open_refusal_frame(
7082                    ctx,
7083                    &caller,
7084                    &frame,
7085                    &target_module_id,
7086                    "relay_reservation_failed",
7087                    forwarding_error_code(&err),
7088                    err.to_string(),
7089                )?])
7090            }
7091        };
7092        timings.enter(RouteOpenPhase::Admission);
7093        let crate::forwarding::PendingRouteBindRelay {
7094            endpoint,
7095            module_sink,
7096            negotiated_ver,
7097            client_channel,
7098            client_epoch,
7099            module_channel,
7100            module_epoch,
7101            corr: relay_corr,
7102            receiver,
7103        } = pending;
7104        let mut reservation =
7105            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
7106
7107        // Reserving egress can wait while a module reconnects or a swap cuts
7108        // over. Check the relay's captured connection, not the earlier by-id
7109        // lookup: the original module's flow/run capabilities cannot authorize
7110        // its replacement. The captured sink stays bound to that connection.
7111        let relay_registration = self
7112            .registry
7113            .route_registration_by_connection(endpoint.connection_id)
7114            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7115        let relay_capabilities = relay_registration
7116            .as_ref()
7117            .and_then(|registration| registration.capabilities.as_ref());
7118        if let Some(selector) = &scope {
7119            // Egress reservation may wait across a scope update. Recheck the
7120            // proof against the current record before sending the captured bind.
7121            if let Err(refusal) = self
7122                .scopes
7123                .read()
7124                .unwrap_or_else(|poisoned| poisoned.into_inner())
7125                .check_bind_proof(&principal, selector)
7126            {
7127                reservation.release_and_disarm();
7128                return Ok(vec![self.route_open_refusal_frame(
7129                    ctx,
7130                    &caller,
7131                    &frame,
7132                    &target_module_id,
7133                    refusal.code,
7134                    refusal.code,
7135                    refusal.message,
7136                )?]);
7137            }
7138        }
7139        if let Some(stamp) = scope_stamp.as_ref() {
7140            if let Err(refusal) = crate::scopes::check_target_required_stamp(
7141                stamp_required,
7142                &target_module_id,
7143                relay_capabilities,
7144            )
7145            .and_then(|()| {
7146                crate::scopes::check_target_flow_support(
7147                    stamp,
7148                    &target_module_id,
7149                    relay_capabilities,
7150                )
7151            })
7152            .and_then(|()| {
7153                crate::scopes::check_target_agent_run_support(
7154                    stamp,
7155                    &target_module_id,
7156                    relay_capabilities,
7157                )
7158            }) {
7159                reservation.release_and_disarm();
7160                return Ok(vec![self.route_open_refusal_frame(
7161                    ctx,
7162                    &caller,
7163                    &frame,
7164                    &target_module_id,
7165                    refusal.code,
7166                    refusal.code,
7167                    refusal.message,
7168                )?]);
7169            }
7170        }
7171
7172        // Older readers may reject unknown fields. Select optional fields from
7173        // the captured endpoint's declaration, including on unscoped binds.
7174        if scope_stamp
7175            .as_ref()
7176            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7177            && !crate::scopes::target_supports_federated(relay_capabilities)
7178        {
7179            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7180            scope_stamp = None;
7181        }
7182        if !relay_capabilities.is_some_and(|caps| {
7183            caps.provides
7184                .iter()
7185                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7186        }) {
7187            if let Some(stamp) = scope_stamp.as_mut() {
7188                stamp.workdir = None;
7189                stamp.project_id = None;
7190            }
7191        }
7192        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7193        // attribution. The run gate above has already required the target to
7194        // declare `worker-runs/v1`, which promises to read both
7195        // `on_behalf_of_agent` and `call_mode`.
7196        let worker_run = scope_stamp
7197            .as_ref()
7198            .is_some_and(crate::scopes::is_worker_run)
7199            && relay_capabilities.is_some_and(|caps| {
7200                caps.provides
7201                    .iter()
7202                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7203            });
7204        if !worker_run
7205            && !relay_capabilities.is_some_and(|caps| {
7206                caps.provides
7207                    .iter()
7208                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7209            })
7210        {
7211            if let Some(stamp) = scope_stamp.as_mut() {
7212                stamp.attributes.on_behalf_of_agent = None;
7213            }
7214        }
7215        if !relay_capabilities.is_some_and(|caps| {
7216            caps.provides
7217                .iter()
7218                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7219        }) {
7220            if let Some(stamp) = scope_stamp.as_mut() {
7221                stamp.attributes.flow_version = None;
7222                stamp.attributes.flow_code_hash = None;
7223                stamp.attributes.flow_install_id = None;
7224            }
7225        }
7226        let call_mode = if worker_run
7227            || relay_capabilities
7228                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7229        {
7230            Some(derive_call_mode(scope_stamp.as_ref()))
7231        } else {
7232            if let Some(stamp) = scope_stamp.as_mut() {
7233                stamp.expires_at_ms = None;
7234            }
7235            None
7236        };
7237
7238        debug!(
7239            connection_id = ctx.connection_id.get(),
7240            client_channel,
7241            client_epoch,
7242            module_channel,
7243            module_epoch,
7244            "reserved route handle pair"
7245        );
7246        // Rendered BEFORE the move into the relay, because the accept arm below
7247        // is where it is logged and the principal is gone by then.
7248        let route_principal_label = principal_label(&principal);
7249        let relay = ModuleControlRequest::RouteBind {
7250            route_channel: module_channel,
7251            epoch: module_epoch,
7252            target,
7253            identity,
7254            principal: Some(principal),
7255            consumer_capabilities,
7256            role_versions,
7257            admission_facts,
7258            scope: scope_stamp,
7259            call_mode,
7260        };
7261        let peer = RouteBindPeer::new()
7262            .with_observed_peer(
7263                relay_capabilities
7264                    .is_some_and(|caps| {
7265                        caps.provides
7266                            .iter()
7267                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7268                    })
7269                    .then(|| {
7270                        self.observed_peers
7271                            .lock()
7272                            .unwrap_or_else(|p| p.into_inner())
7273                            .get(&ctx.connection_id)
7274                            .cloned()
7275                            .unwrap_or_else(ObservedPeer::unobserved)
7276                    }),
7277            )
7278            .with_operator_app(
7279                self.connection_operator_app(operator_app.as_ref())
7280                    .filter(|_| {
7281                        relay_capabilities.is_some_and(|caps| {
7282                            caps.provides
7283                                .iter()
7284                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7285                        })
7286                    }),
7287            )
7288            .with_caller(caller_for_target(
7289                caller_capture.as_ref(),
7290                relay_capabilities,
7291                &target_module_id,
7292            ))
7293            .with_peer_build(
7294                (production_peer_build
7295                    && relay_capabilities.is_some_and(|caps| {
7296                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7297                    }))
7298                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7299            );
7300        let relay_body = crate::bind_compat::encode_bind(
7301            &relay,
7302            &peer,
7303            &legacy_bind_project,
7304            relay_capabilities,
7305        )
7306        .map_err(|err| {
7307            RouterError::backend(
7308                0,
7309                frame.header.corr,
7310                format!("failed to encode route.bind request: {err}"),
7311            )
7312        })?;
7313        let relay_frame = Frame::build_with_version(
7314            negotiated_ver,
7315            FrameType::Request,
7316            control_flags(),
7317            0,
7318            0,
7319            relay_corr,
7320            relay_body,
7321        )
7322        .map_err(RouterError::FrameBuild)?;
7323
7324        timings.enter(RouteOpenPhase::BindSend);
7325        let sent = module_sink.send(relay_frame).await;
7326        timings.enter(RouteOpenPhase::Admission);
7327        if let Err(err) = sent {
7328            reservation.release_and_disarm();
7329            return Ok(vec![self.route_open_refusal_frame(
7330                ctx,
7331                &caller,
7332                &frame,
7333                &target_module_id,
7334                "relay_send_failed",
7335                "target_unavailable",
7336                err.to_string(),
7337            )?]);
7338        }
7339
7340        #[cfg(test)]
7341        if let Some(hold) = &self.route_bind_relay_sent_hold {
7342            // First wait: tell the test the bind is queued. Second wait: stay
7343            // here until the test has driven whatever it wants to happen
7344            // between queueing the bind and marking it enqueued.
7345            hold.wait().await;
7346            hold.wait().await;
7347        }
7348
7349        // A missing relay is not by itself an abandoned bind: the module may
7350        // already have acked it and the route may be committed. Only a relay
7351        // dropped without any module reply needs this GOODBYE; one a reply
7352        // settled has already had its GOODBYE decided by the reply path.
7353        if self
7354            .forwarding
7355            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7356            .map_err(RouterError::Forwarding)?
7357            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7358        {
7359            self.send_abandoned_route_bind_goodbye(
7360                &module_sink,
7361                negotiated_ver,
7362                module_channel,
7363                module_epoch,
7364            );
7365        }
7366
7367        timings.enter(RouteOpenPhase::BindAckWait);
7368        let outcome = timeout_at(relay_deadline, receiver).await;
7369        timings.enter(RouteOpenPhase::Admission);
7370        match outcome {
7371            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7372                reservation.disarm();
7373                if breaker.record_accepted() {
7374                    info!(
7375                        module_id = %target_module_id,
7376                        "route.bind breaker closed: the probe was accepted"
7377                    );
7378                }
7379                self.observe_route_open_accept(
7380                    ctx,
7381                    &target_module_id,
7382                    &route_principal_label,
7383                    &caller.scope,
7384                );
7385                Ok(Vec::new())
7386            }
7387            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7388                reservation.release_and_disarm();
7389                // A module that says no in microseconds is healthy. Rejection
7390                // is a different condition with its own refusal and must not
7391                // move the breaker.
7392                breaker.record_inconclusive();
7393                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7394            }
7395            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7396                reservation.release_and_disarm();
7397                breaker.record_inconclusive();
7398                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7399            }
7400            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7401                reservation.release_and_disarm();
7402                breaker.record_inconclusive();
7403                // Fires when the module's connection closes while a relayed
7404                // bind is pending -- typically a caller racing a module restart
7405                // whose bind was relayed BEFORE the drain mark went up. Logged
7406                // because the caller sees only its own error and the fleet has
7407                // already spent one diagnosis round unable to tell this arm
7408                // from a relay timeout without daemon-side evidence.
7409                tracing::warn!(
7410                    module_id = %target_module_id,
7411                    "route.bind relay abandoned: {message}"
7412                );
7413                Ok(vec![self.route_open_refusal_frame(
7414                    ctx,
7415                    &caller,
7416                    &frame,
7417                    &target_module_id,
7418                    "relay_abandoned",
7419                    "target_unavailable",
7420                    message,
7421                )?])
7422            }
7423            Ok(Err(_)) => {
7424                reservation.release_and_disarm();
7425                breaker.record_inconclusive();
7426                Ok(vec![self.route_open_refusal_frame(
7427                    ctx,
7428                    &caller,
7429                    &frame,
7430                    &target_module_id,
7431                    "relay_waiter_canceled",
7432                    "target_unavailable",
7433                    "route.bind relay waiter was canceled before the module responded",
7434                )?])
7435            }
7436            Err(_) => {
7437                reservation.release_and_disarm();
7438                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7439                // answer at all is the one condition a fast refusal can
7440                // usefully stand in for; every other arm already answered.
7441                if let Some(opened) = breaker.record_timeout(
7442                    self.route_bind_breaker_threshold,
7443                    self.route_bind_breaker_cooldown,
7444                ) {
7445                    warn!(
7446                        module_id = %target_module_id,
7447                        consecutive_timeouts = opened.consecutive_timeouts,
7448                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7449                        reopened_after_probe = opened.reopened_after_probe,
7450                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7451                    );
7452                }
7453                // The generous budget just burned to no answer: the module is
7454                // registered and its connection is up, but its bind handler sat
7455                // on the ack for the full budget (warm-on-bind, cold configure,
7456                // or a wedged handler). Every earlier unavailability shape
7457                // fast-refuses BEFORE the relay, so this arm firing means the
7458                // slowness is module-side -- log it so the per-module timeline
7459                // is reconstructable without client audit rows.
7460                tracing::warn!(
7461                    module_id = %target_module_id,
7462                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7463                    "route.bind relay timed out: module did not ack within budget"
7464                );
7465                Ok(vec![self.route_open_refusal_frame(
7466                    ctx,
7467                    &caller,
7468                    &frame,
7469                    &target_module_id,
7470                    "relay_timed_out",
7471                    "module_timeout",
7472                    format!(
7473                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7474                        route_bind_relay_timeout
7475                    ),
7476                )?])
7477            }
7478        }
7479    }
7480
7481    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7482        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7483            snapshot: self.supervisor.spawn_snapshot(),
7484        };
7485        Ok(vec![control_response_body_frame(
7486            &frame,
7487            &response,
7488            "ClientControlResponse::SupervisorSpawnSnapshot",
7489        )?])
7490    }
7491
7492    fn handle_supervisor_spawn_subscribe(
7493        &self,
7494        ctx: &RouteCtx,
7495        frame: Frame,
7496        since: Option<SpawnCursor>,
7497    ) -> Result<Vec<Frame>, RouterError> {
7498        match self.supervisor.subscribe_spawns(
7499            ctx.connection_id,
7500            frame.header.corr,
7501            response_version(&frame),
7502            since,
7503            ctx.egress.clone(),
7504        ) {
7505            Ok(()) => Ok(Vec::new()),
7506            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7507                Ok(vec![control_error_body_frame(
7508                    &frame,
7509                    ErrorBody {
7510                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7511                        message: "spawn cursor belongs to a different daemon incarnation"
7512                            .to_string(),
7513                        detail: Some(serde_json::json!({
7514                            "current_daemon_incarnation": current
7515                        })),
7516                    },
7517                )?])
7518            }
7519            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7520                &frame,
7521                ErrorBody {
7522                    code: "spawn_cursor_too_old".to_string(),
7523                    message: "spawn cursor predates the retained event ring".to_string(),
7524                    detail: Some(serde_json::json!({
7525                        "oldest_retained_cursor": oldest
7526                    })),
7527                },
7528            )?]),
7529            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7530                0,
7531                frame.header.corr,
7532                format!("failed to open supervisor spawn subscription: {error}"),
7533            )),
7534        }
7535    }
7536
7537    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7538        // Status/configuration snapshots may wait on synchronous supervisor
7539        // locks. Keep that work off the connection's async runtime thread.
7540        let handler = self.clone();
7541        let runtime = tokio::runtime::Handle::current();
7542        // The blocking pool does not inherit the control request's tracing
7543        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7544        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7545        let corr = frame.header.corr;
7546        tokio::task::spawn_blocking(move || {
7547            runtime.block_on(
7548                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7549                    .with_subscriber(subscriber),
7550            )
7551        })
7552        .await
7553        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7554    }
7555
7556    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7557        use crate::config_gate::runtime::ApprovedDaemonView;
7558        let publication = self
7559            .config_runtime
7560            .as_ref()
7561            .and_then(|owner| owner.polled_snapshot().ok());
7562        let approved = publication
7563            .as_ref()
7564            .map(|view| view.approved_daemon.clone())
7565            .unwrap_or_else(|| {
7566                if self.config_runtime.is_some() {
7567                    ApprovedDaemonView::Unavailable
7568                } else {
7569                    ApprovedDaemonView::NotStamped
7570                }
7571            });
7572        let generation = self
7573            .registry
7574            .generation()
7575            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7576        let supervised = self.supervisor.list();
7577        let mut statuses = BTreeMap::new();
7578        let mut not_running = BTreeSet::new();
7579        for module in &supervised {
7580            let status = module.status_for_control("list").map_err(|err| {
7581                RouterError::backend(
7582                    0,
7583                    frame.header.corr,
7584                    format!("failed to read supervisor status: {err}"),
7585                )
7586            })?;
7587            if !status.enabled || !status.process_alive {
7588                not_running.insert(module.module_id().to_owned());
7589            }
7590            statuses.insert(module.module_id().to_owned(), status);
7591        }
7592        // Legacy per-process diagnostics keep their shared optional budget.
7593        // The cached tree and accounting export below does not spend it.
7594        let mut process_resources = BTreeMap::new();
7595        for module in &supervised {
7596            process_resources.insert(
7597                module.module_id().to_owned(),
7598                crate::subtree_resources::read_process(module.clone()).await,
7599            );
7600        }
7601        // Image evidence uses the same optional deadline, but an exhausted
7602        // budget must not suppress the committed resource view.
7603        let mut image_readings = BTreeMap::new();
7604        for module in &supervised {
7605            image_readings.insert(
7606                module.module_id().to_owned(),
7607                module.running_image_agreement().await,
7608            );
7609        }
7610        let readings = self.resource_tracker.list(supervised.clone());
7611        let mut modules = Vec::new();
7612        for module in supervised {
7613            let status = statuses
7614                .remove(module.module_id())
7615                .expect("each supervised module has a status snapshot");
7616            let (configured, _) = module.configuration().map_err(|err| {
7617                RouterError::backend(
7618                    0,
7619                    frame.header.corr,
7620                    format!("failed to read module configuration: {err}"),
7621                )
7622            })?;
7623            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7624                RouterError::backend(
7625                    0,
7626                    frame.header.corr,
7627                    format!("failed to read retry time: {err}"),
7628                )
7629            })?;
7630            let image = image_readings
7631                .remove(module.module_id())
7632                .expect("each supervised module has an image snapshot");
7633            let resources = process_resources.remove(module.module_id());
7634            let mut verdict =
7635                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7636            verdict.spec = Some(launch_spec_agreement(
7637                &configured,
7638                status.process_alive,
7639                status.launch_spec_digest.as_ref(),
7640            ));
7641            let pending_reload = Some(verdict);
7642            let pending_entry = match &approved {
7643                ApprovedDaemonView::Approved { config, .. } => config
7644                    .modules
7645                    .iter()
7646                    .find(|m| m.module_id == module.module_id()),
7647                _ => None,
7648            };
7649            let pending = self
7650                .pending_module_fields(
7651                    &module,
7652                    pending_entry,
7653                    false,
7654                    Self::registration_channel_in_force(
7655                        publication
7656                            .as_ref()
7657                            .and_then(|view| view.registration_declaration(module.module_id()))
7658                            .as_deref(),
7659                        pending_entry.map(|entry| entry.registration_channel),
7660                    ),
7661                )
7662                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7663            let script = configured.script.as_ref().map(|entry| {
7664                let approved = self
7665                    .config_runtime
7666                    .as_ref()
7667                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7668                crate::supervise::script::status(entry, approved.as_ref())
7669            });
7670            let configured_enabled = match &approved {
7671                ApprovedDaemonView::Approved {
7672                    config: approved, ..
7673                } => approved
7674                    .modules
7675                    .iter()
7676                    .find(|module| module.module_id == status.module_id)
7677                    .map(|module| module.enabled),
7678                ApprovedDaemonView::NotStamped => self
7679                    .capability_evaluator
7680                    .configured_enabled(&status.module_id),
7681                ApprovedDaemonView::Unavailable => None,
7682            };
7683            let admission_refused = status
7684                .admission_refused
7685                .clone()
7686                .filter(|_| status.enabled && !status.process_alive)
7687                .filter(|_| {
7688                    publication
7689                        .as_ref()
7690                        .and_then(|view| view.registration_declaration(&status.module_id))
7691                        .as_deref()
7692                        == Some("undeclared")
7693                });
7694            // Keep the retired policy field on the wire for one release so
7695            // existing status consumers still receive the platform policy.
7696            let mut entry = SupervisorEntry::new(
7697                status.module_id,
7698                status.state.to_string(),
7699                status.enabled,
7700                status.live,
7701                status.health.status,
7702            )
7703            .with_configured_enabled(configured_enabled)
7704            .with_script(script)
7705            .with_admission_refused(admission_refused)
7706            .with_next_retry_at_ms(next_retry_at_ms)
7707            .with_launch_nonce_env(Some(!cfg!(unix)))
7708            .with_launch_nonce_source(status.launch_nonce_source)
7709            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7710            .with_protocol(status.protocol)
7711            .with_pending_reload(pending_reload)
7712            .with_last_probe_ms(status.health.last_probe_ms)
7713            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7714            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7715            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7716            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7717            .with_restart_count(Some(status.restart_count))
7718            .with_max_restarts(Some(status.max_restarts))
7719            .with_lifetime_restarts(Some(status.lifetime_restarts))
7720            .with_spawn_generation(Some(status.spawn_generation))
7721            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7722            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7723            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7724            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7725            .with_resources(resources);
7726            entry.pending = pending;
7727            modules.push(entry);
7728        }
7729        for module in &mut modules {
7730            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7731                module.tree = tree.clone();
7732                module.cpu_last_hour = hour.clone();
7733            }
7734            module.tree_unavailable = readings
7735                .reasons
7736                .get(&module.module_id)
7737                .map(|reason| (*reason).to_owned());
7738            if module.tree.is_none() {
7739                module.tree_unavailable = Some(
7740                    if not_running.contains(&module.module_id) {
7741                        "not_running"
7742                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7743                        reason
7744                    } else {
7745                        "not_yet_measured"
7746                    }
7747                    .to_owned(),
7748                );
7749            }
7750        }
7751        let response = ClientControlResponse::SupervisorList {
7752            generation,
7753            modules,
7754            daemon: readings.daemon,
7755            agent_commands: readings.agent_commands,
7756        };
7757        Ok(vec![control_response_body_frame(
7758            &frame,
7759            &response,
7760            "ClientControlResponse::SupervisorList",
7761        )?])
7762    }
7763
7764    fn handle_supervisor_stderr_tail(
7765        &self,
7766        frame: Frame,
7767        module_id: String,
7768        max_lines: Option<u32>,
7769        max_bytes: Option<u32>,
7770    ) -> Result<Vec<Frame>, RouterError> {
7771        let Some(module) = self.supervisor.get(&module_id) else {
7772            return Ok(vec![control_error_frame(
7773                &frame,
7774                "unknown_module",
7775                format!("module_id '{module_id}' is not supervised"),
7776            )?]);
7777        };
7778
7779        let snapshot = module.stderr_tail(
7780            max_lines.map(|value| value as usize),
7781            max_bytes.map(|value| value as usize),
7782        );
7783
7784        let response = ClientControlResponse::SupervisorStderrTail {
7785            module_id,
7786            tail: StderrTail {
7787                capture: match snapshot.capture {
7788                    CaptureState::Captured => StderrCaptureState::Captured,
7789                    CaptureState::Incomplete { reason } => {
7790                        StderrCaptureState::Incomplete { reason }
7791                    }
7792                    CaptureState::NotCaptured { reason } => {
7793                        StderrCaptureState::NotCaptured { reason }
7794                    }
7795                },
7796                entries: snapshot
7797                    .entries
7798                    .into_iter()
7799                    .map(|entry| match entry {
7800                        TailEntry::Line {
7801                            text,
7802                            truncated,
7803                            at_ms,
7804                        } => StderrTailEntry::Line {
7805                            text,
7806                            truncated,
7807                            at_ms,
7808                        },
7809                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7810                    })
7811                    .collect(),
7812                dropped_lines: snapshot.dropped_lines,
7813            },
7814        };
7815        Ok(vec![control_response_body_frame(
7816            &frame,
7817            &response,
7818            "ClientControlResponse::SupervisorStderrTail",
7819        )?])
7820    }
7821
7822    async fn observe_control_wait<F: std::future::Future>(
7823        &self,
7824        ctx: &RouteCtx,
7825        target: Option<&str>,
7826        kind: &'static str,
7827        future: F,
7828    ) -> F::Output {
7829        self.counters
7830            .observe_reader_wait(
7831                || {
7832                    let module = self
7833                        .forwarding
7834                        .module_id_for_connection(ctx.connection_id)
7835                        .ok()
7836                        .flatten();
7837                    let principal = if module.is_some() { "module" } else { "direct" };
7838                    (
7839                        self.resolve_reader_wait_target(kind, target)
7840                            .or(module)
7841                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7842                        principal.into(),
7843                    )
7844                },
7845                kind,
7846                future,
7847            )
7848            .await
7849    }
7850
7851    /// Resolve the reader-wait module ID only from supervisor or registry
7852    /// records; never attribute a wait from the request selector alone.
7853    pub(crate) fn resolve_reader_wait_target(
7854        &self,
7855        op: &str,
7856        selector: Option<&str>,
7857    ) -> Option<String> {
7858        let selector = selector?;
7859        match op {
7860            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7861                .supervisor
7862                .get(selector)
7863                .map(|module| module.module_id().to_owned()),
7864            ops::SUPERVISOR_HEALTH_PROBE => self
7865                .registry
7866                .get_module(selector)
7867                .ok()
7868                .flatten()
7869                .map(|registration| registration.manifest.module_id),
7870            _ => None,
7871        }
7872    }
7873
7874    async fn handle_supervisor_terminals(
7875        &self,
7876        ctx: &RouteCtx,
7877        frame: Frame,
7878        module_id: String,
7879    ) -> Result<Vec<Frame>, RouterError> {
7880        let Some(module) = self.supervisor.get(&module_id) else {
7881            return Ok(vec![control_error_frame(
7882                &frame,
7883                "unknown_module",
7884                format!("module_id '{module_id}' is not supervised"),
7885            )?]);
7886        };
7887
7888        // The journal read runs on a blocking thread: it can be megabytes of
7889        // file I/O and must not occupy a runtime worker.
7890        let terminals = self
7891            .observe_control_wait(
7892                ctx,
7893                Some(module.module_id()),
7894                ops::SUPERVISOR_TERMINALS,
7895                module.read_durable_terminal_history(),
7896            )
7897            .await
7898            .map_err(|error| {
7899                RouterError::backend(
7900                    0,
7901                    frame.header.corr,
7902                    format!("failed to read terminal history: {error}"),
7903                )
7904            })?;
7905        let response = ClientControlResponse::SupervisorTerminals {
7906            module_id,
7907            terminals,
7908        };
7909        Ok(vec![control_response_body_frame(
7910            &frame,
7911            &response,
7912            "ClientControlResponse::SupervisorTerminals",
7913        )?])
7914    }
7915
7916    fn handle_supervisor_routes(
7917        &self,
7918        frame: Frame,
7919        module_id: Option<String>,
7920    ) -> Result<Vec<Frame>, RouterError> {
7921        let modules = self
7922            .forwarding
7923            .route_census(module_id.as_deref())
7924            .map_err(RouterError::Forwarding)?
7925            .into_iter()
7926            .map(|(module_id, routes)| SupervisorRouteModule {
7927                module_id,
7928                routes: routes
7929                    .into_iter()
7930                    .map(|route| SupervisorRoute {
7931                        consumer: match route.principal {
7932                            Principal::Reserved { module_id } => {
7933                                SupervisorRouteConsumer::Reserved { module_id }
7934                            }
7935                            Principal::Direct | Principal::Unverified => {
7936                                SupervisorRouteConsumer::Direct {
7937                                    connection_id: route.goodbye_target.connection_id.get(),
7938                                }
7939                            }
7940                        },
7941                        age_ms: Instant::now()
7942                            .saturating_duration_since(route.bound_at)
7943                            .as_millis()
7944                            .try_into()
7945                            .unwrap_or(u64::MAX),
7946                        draining: route.draining,
7947                        drain_reason: route.drain_reason,
7948                    })
7949                    .collect(),
7950            })
7951            .collect();
7952        let response = ClientControlResponse::SupervisorRoutes { modules };
7953        Ok(vec![control_response_body_frame(
7954            &frame,
7955            &response,
7956            "ClientControlResponse::SupervisorRoutes",
7957        )?])
7958    }
7959
7960    fn running_registration_method(
7961        &self,
7962        module: &str,
7963    ) -> Option<subc_control::RegistrationMethod> {
7964        let registration = self.registry.get_module(module).ok()??;
7965        let connection = registration.connection_id;
7966        let channel = self.supervisor.registration_spawn(connection).is_some();
7967        let nonce = if channel {
7968            None
7969        } else {
7970            self.hello_launch_nonces
7971                .lock()
7972                .ok()?
7973                .nonce(connection)
7974                .map(str::to_owned)
7975        };
7976        if !channel && nonce.is_none() {
7977            return None;
7978        }
7979        self.supervisor
7980            .registration_snapshot_is_current_live(
7981                &self.registry,
7982                module,
7983                connection,
7984                nonce.as_deref(),
7985            )
7986            .then_some(if channel {
7987                subc_control::RegistrationMethod::Channel
7988            } else {
7989                subc_control::RegistrationMethod::Nonce
7990            })
7991    }
7992
7993    async fn handle_supervisor_provenance(
7994        &self,
7995        ctx: &RouteCtx,
7996        frame: Frame,
7997        module_id: Option<String>,
7998    ) -> Result<Vec<Frame>, RouterError> {
7999        let targeted = module_id.is_some();
8000        let selected = if let Some(module_id) = module_id {
8001            let Some(module) = self.supervisor.get(&module_id) else {
8002                return Ok(vec![control_error_frame(
8003                    &frame,
8004                    "unknown_module",
8005                    format!("module_id '{module_id}' is not supervised"),
8006                )?]);
8007            };
8008            vec![module]
8009        } else {
8010            self.supervisor.list()
8011        };
8012
8013        let target = targeted.then(|| selected[0].module_id());
8014        let declarations = if let Some(owner) = &self.config_runtime {
8015            owner
8016                .on_blocking(|owner| owner.registration_declarations())
8017                .await
8018                .ok()
8019        } else {
8020            None
8021        };
8022        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
8023            let mut modules = Vec::with_capacity(selected.len());
8024            let mut extensions = Vec::with_capacity(selected.len());
8025            for module in &selected {
8026                let (status, observed_image) = module
8027                    .status_and_running_image_agreement()
8028                    .await
8029                    .map_err(|err| {
8030                        RouterError::backend(
8031                            0,
8032                            frame.header.corr,
8033                            format!("failed to read supervisor status: {err}"),
8034                        )
8035                    })?;
8036                let module_declared = self
8037                    .registry
8038                    .get_module(&status.module_id)
8039                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8040                    .and_then(|registration| registration.manifest.provenance)
8041                    .map(|build| ModuleDeclaredProvenance::Reported { build })
8042                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
8043                #[cfg(test)]
8044                let running_image = match &self.provenance_probe_override {
8045                    Some(result) => result.clone(),
8046                    None => observed_image,
8047                };
8048                #[cfg(not(test))]
8049                let running_image = observed_image;
8050                let registration = self.running_registration_method(&status.module_id);
8051                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
8052                    .with_registration(registration);
8053                extension.registration_declaration = declarations
8054                    .as_ref()
8055                    .and_then(|entries| entries.get(&status.module_id))
8056                    .cloned();
8057                if status.process_alive && status.registration_declaration.is_some() {
8058                    extension.registration_declaration = status.registration_declaration.clone();
8059                }
8060                extensions.push(extension);
8061                modules.push(SupervisorModuleProvenance {
8062                    module_id: status.module_id,
8063                    module_declared,
8064                    daemon_observed: SupervisorObservedProcess {
8065                        launch_nonce_source: status.launch_nonce_source,
8066                        pid: status.pid,
8067                        spawned_at_ms: status.spawned_at_ms,
8068                        spawned_from: status.spawned_from,
8069                        running_image,
8070                    },
8071                });
8072            }
8073            let daemon = SupervisorDaemonProvenance {
8074                daemon_build: self.daemon_provenance.build.clone(),
8075                daemon_observed: DaemonObservedProcess {
8076                    pid: self.daemon_provenance.pid,
8077                    started_at_ms: self
8078                        .daemon_provenance
8079                        .start_clock
8080                        .map(|clock| clock.started_at_ms())
8081                        .or(self.daemon_provenance.started_at_ms),
8082                    running_image: self
8083                        .daemon_provenance
8084                        .probe
8085                        .observe(
8086                            self.daemon_provenance.pid,
8087                            self.daemon_provenance.executable_path.as_deref(),
8088                            self.daemon_provenance.executable_identity.clone(),
8089                            self.daemon_provenance.process_start_time,
8090                        )
8091                        .await,
8092                },
8093            };
8094            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8095            let mut response = serde_json::to_value(response)
8096                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8097            for (entry, extension) in response["modules"]
8098                .as_array_mut()
8099                .expect("provenance modules are an array")
8100                .iter_mut()
8101                .zip(extensions)
8102            {
8103                extension.write_to(entry).map_err(|error| {
8104                    RouterError::backend(0, frame.header.corr, error.to_string())
8105                })?;
8106            }
8107            Ok(vec![control_response_body_frame(
8108                &frame,
8109                &response,
8110                "ClientControlResponse::SupervisorProvenance",
8111            )?])
8112        })
8113        .await
8114    }
8115
8116    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8117        self.refresh_capability_requirements();
8118        let publication = self
8119            .config_runtime
8120            .as_ref()
8121            .and_then(|owner| owner.polled_snapshot().ok());
8122        let generation = self
8123            .registry
8124            .generation()
8125            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8126        let modules = self
8127            .supervisor
8128            .list()
8129            .into_iter()
8130            .map(|module| {
8131                let status = module.status_for_control("health").map_err(|err| {
8132                    RouterError::backend(
8133                        0,
8134                        frame.header.corr,
8135                        format!("failed to read supervisor health: {err}"),
8136                    )
8137                })?;
8138                let module_id = status.module_id;
8139                let capability_detail = self
8140                    .capability_evaluator
8141                    .required_problem_detail(&module_id);
8142                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8143                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8144                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8145                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8146                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8147                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8148                Ok(SupervisorHealthEntry {
8149                    module_id,
8150                    status: status.health.status,
8151                    detail: append_capability_problem_detail(
8152                        status.health.detail,
8153                        capability_detail,
8154                    ),
8155                    metrics: status.health.metrics,
8156                    consecutive_failures: status.health.consecutive_failures,
8157                    late_answer_count: status.health.late_answer_count,
8158                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8159                    last_action: status.health.last_action,
8160                    last_action_ms: status.health.last_action_ms,
8161                    last_probe_ms: status.health.last_probe_ms,
8162                })
8163            })
8164            .collect::<Result<Vec<_>, RouterError>>()?;
8165        let response = ClientControlResponse::SupervisorHealth {
8166            generation,
8167            modules,
8168        };
8169        Ok(vec![control_response_body_frame(
8170            &frame,
8171            &response,
8172            "ClientControlResponse::SupervisorHealth",
8173        )?])
8174    }
8175
8176    async fn handle_supervisor_restart(
8177        &self,
8178        frame: Frame,
8179        module_id: String,
8180        drain_timeout_ms: Option<u64>,
8181        requester: Principal,
8182    ) -> Result<Vec<Frame>, RouterError> {
8183        let operation_lock = self.supervisor.operation_lock();
8184        let _operation_guard = operation_lock.lock().await;
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
8193        self.route_outages.mark_operator_action(&module_id);
8194        if let Err(err) = module
8195            .restart_requested(drain_timeout_ms, Some(requester))
8196            .await
8197        {
8198            self.route_outages
8199                .operator_action_ended_unrefused(&module_id);
8200            let (code, message) = match err {
8201                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8202                crate::supervise::SuperviseError::Disabled { .. } => {
8203                    ("module_disabled", err.to_string())
8204                }
8205                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8206                    ("swap_in_progress", err.to_string())
8207                }
8208                _ => (
8209                    "target_unavailable",
8210                    format!("failed to restart module_id '{module_id}': {err}"),
8211                ),
8212            };
8213            return Ok(vec![control_error_frame(&frame, code, message)?]);
8214        }
8215
8216        let response = ClientControlResponse::SupervisorAck {
8217            module_id,
8218            applied: true,
8219        };
8220        Ok(vec![control_response_body_frame(
8221            &frame,
8222            &response,
8223            "ClientControlResponse::SupervisorAck",
8224        )?])
8225    }
8226
8227    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8228    /// when the old process has finished draining: a caller whose own lane
8229    /// rides the old process must get its reply before that drain waits on it.
8230    async fn handle_supervisor_swap(
8231        &self,
8232        frame: Frame,
8233        module_id: String,
8234        ready_timeout_ms: Option<u64>,
8235        requester: Principal,
8236    ) -> Result<Vec<Frame>, RouterError> {
8237        // The daemon-wide operation lock is held only to resolve the handle,
8238        // not across the swap. The swap can take its whole readiness budget,
8239        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8240        // holding it here would park an operator's stop behind the swap it is
8241        // meant to abort. A rescan or stop that reaches the module during the
8242        // swap is served by the swap itself (see `supervise_swap`).
8243        let module = {
8244            let operation_lock = self.supervisor.operation_lock();
8245            let _operation_guard = operation_lock.lock().await;
8246            self.supervisor.get(&module_id)
8247        };
8248        let Some(module) = module else {
8249            return Ok(vec![control_error_frame(
8250                &frame,
8251                "unknown_module",
8252                format!("module_id '{module_id}' is not supervised"),
8253            )?]);
8254        };
8255
8256        self.route_outages.mark_operator_action(&module_id);
8257        if let Err(err) = module
8258            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8259            .await
8260        {
8261            self.route_outages
8262                .operator_action_ended_unrefused(&module_id);
8263            use crate::supervise::SuperviseError;
8264            let message = err.to_string();
8265            let error = match err {
8266                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8267                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8268                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8269                    code: "swap_refused".to_string(),
8270                    message,
8271                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8272                },
8273                SuperviseError::SwapFailed {
8274                    arm,
8275                    candidate_exit,
8276                    ..
8277                } => ErrorBody {
8278                    code: "swap_failed".to_string(),
8279                    message,
8280                    detail: Some(serde_json::json!({
8281                        "arm": arm.as_str(),
8282                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8283                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8284                    })),
8285                },
8286                _ => ErrorBody::new(
8287                    "target_unavailable",
8288                    format!("failed to swap module_id '{module_id}': {message}"),
8289                ),
8290            };
8291            return Ok(vec![control_error_body_frame(&frame, error)?]);
8292        }
8293        // A completed swap kept the incumbent serving until cutover, so it
8294        // usually opened no outage; a mark left behind would make the next,
8295        // unrelated outage read as requested.
8296        self.route_outages
8297            .operator_action_ended_unrefused(&module_id);
8298
8299        let response = ClientControlResponse::SupervisorAck {
8300            module_id,
8301            applied: true,
8302        };
8303        Ok(vec![control_response_body_frame(
8304            &frame,
8305            &response,
8306            "ClientControlResponse::SupervisorAck",
8307        )?])
8308    }
8309
8310    async fn handle_supervisor_reload(
8311        &self,
8312        frame: Frame,
8313        module_id: String,
8314        requester: Principal,
8315    ) -> Result<Vec<Frame>, RouterError> {
8316        let operation_lock = self.supervisor.operation_lock();
8317        let _operation_guard = operation_lock.lock().await;
8318        let Some(module) = self.supervisor.get(&module_id) else {
8319            return Ok(vec![control_error_frame(
8320                &frame,
8321                "unknown_module",
8322                format!("module_id '{module_id}' is not supervised"),
8323            )?]);
8324        };
8325
8326        self.route_outages.mark_operator_action(&module_id);
8327        if let Err(err) = module.reload_requested(Some(requester)).await {
8328            self.route_outages
8329                .operator_action_ended_unrefused(&module_id);
8330            let (code, message) = match err {
8331                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8332                crate::supervise::SuperviseError::Disabled { .. } => {
8333                    ("module_disabled", err.to_string())
8334                }
8335                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8336                    ("swap_in_progress", err.to_string())
8337                }
8338                _ => (
8339                    "reload_failed",
8340                    format!("failed to reload module_id '{module_id}': {err}"),
8341                ),
8342            };
8343            return Ok(vec![control_error_frame(&frame, code, message)?]);
8344        }
8345
8346        let response = ClientControlResponse::SupervisorAck {
8347            module_id,
8348            applied: true,
8349        };
8350        Ok(vec![control_response_body_frame(
8351            &frame,
8352            &response,
8353            "ClientControlResponse::SupervisorAck",
8354        )?])
8355    }
8356
8357    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8358    /// the configuration comes from and whether to apply it; every mode then
8359    /// runs the same comparison, so a preview describes the apply it previews.
8360    async fn handle_supervisor_rescan(
8361        &self,
8362        frame: Frame,
8363        mode: RescanMode,
8364        requester: Principal,
8365    ) -> Result<Vec<Frame>, RouterError> {
8366        let preview = mode.previews();
8367        let Some(context) = self.rescan.clone() else {
8368            return Ok(vec![control_error_frame(
8369                &frame,
8370                "rescan_unavailable",
8371                "the daemon was not started with a reloadable config path".to_string(),
8372            )?]);
8373        };
8374
8375        let _rescan_guard = context.rescan_lock.lock().await;
8376        let rescan_checked::RescanInput {
8377            config: loaded,
8378            approved_preview,
8379            guard: _operation_guard,
8380        } = match self.rescan_input(&mode, &context).await {
8381            Ok(input) => input,
8382            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
8383        };
8384        // `load` reports a missing file as Ok(None), which is correct at boot
8385        // (no config, nothing to supervise) and catastrophic here: rescan treats
8386        // "not in the config" as "remove it", so an absent file would read as an
8387        // empty module list and retire the entire running fleet. An editor
8388        // writing via write-new-then-rename, or a half-finished edit, is enough
8389        // to open that window. Refuse instead: a config that cannot be read
8390        // carries no instruction to remove anything.
8391        let Some((config, activity_config)) = loaded else {
8392            return Ok(vec![control_error_frame(
8393                &frame,
8394                "invalid_daemon_config",
8395                format!(
8396                    "daemon config not found at {}; refusing to rescan (an absent config would \
8397                     retire every supervised module)",
8398                    context.config_path.display()
8399                ),
8400            )?]);
8401        };
8402        let (
8403            configured_port,
8404            storage_config,
8405            admission_facts_carrier_module_id,
8406            admission_facts_targets,
8407            scope_authority_owners,
8408            federated_scope_owner,
8409            privileged_operator_prompt,
8410            modules,
8411            reserved_capabilities,
8412        ) = (
8413            config.port,
8414            config.storage,
8415            config.admission_facts_carrier_module_id,
8416            config.admission_facts_targets,
8417            config.scope_authority_owners,
8418            config.federated_scope_owner,
8419            config.privileged_operator_prompt,
8420            config.modules,
8421            config.reserved_capabilities,
8422        );
8423
8424        // Collect the sections rescan cannot apply, so the REPLY carries them.
8425        //
8426        // The warning below has always been correct and has always gone only to
8427        // the journal -- addressed to whoever reads logs, while the person who
8428        // just edited the config is looking at the CLI. Naming each section
8429        // individually rather than setting a flag: "something outside modules
8430        // changed" sends the operator back to diffing their own file, which is
8431        // the work this is meant to save.
8432        let mut restart_required = Vec::new();
8433        for section in RestartRequiredSection::ALL {
8434            let changed = match section {
8435                RestartRequiredSection::Port => configured_port != context.configured_port,
8436                RestartRequiredSection::Storage => storage_config != context.storage_config,
8437                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8438                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8439                }
8440                RestartRequiredSection::AdmissionFactsTargets => {
8441                    admission_facts_targets != context.admission_facts_targets
8442                }
8443                RestartRequiredSection::ScopeAuthorityOwners => {
8444                    scope_authority_owners != context.scope_authority_owners
8445                }
8446                RestartRequiredSection::FederatedScopeOwner => {
8447                    federated_scope_owner != context.federated_scope_owner
8448                }
8449                RestartRequiredSection::PrivilegedOperatorPrompt => {
8450                    privileged_operator_prompt != context.privileged_operator_prompt
8451                }
8452            };
8453            if changed {
8454                restart_required.push(section.label().to_string());
8455            }
8456        }
8457        if !restart_required.is_empty() {
8458            warn!(
8459                config_path = %context.config_path.display(),
8460                sections = %restart_required.join(", "),
8461                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8462            );
8463        }
8464
8465        for configured in &modules {
8466            if let Err(err) = validate_spec(&configured.module_spec()) {
8467                return Ok(vec![control_error_frame(
8468                    &frame,
8469                    "invalid_daemon_config",
8470                    format!("supervisor rescan rejected daemon config: {err}"),
8471                )?]);
8472            }
8473        }
8474
8475        let configured_capabilities = modules
8476            .iter()
8477            .map(|module| (module.module_id.clone(), module.enabled))
8478            .collect::<Vec<_>>();
8479        let preview_capability_warnings = if preview {
8480            let (_, registrations) = self.runtime_capability_snapshot()?;
8481            let current_modules = self
8482                .supervisor
8483                .list()
8484                .into_iter()
8485                .map(|module| module.module_id().to_string())
8486                .collect::<BTreeSet<_>>();
8487            let resulting_modules = configured_capabilities.clone();
8488            let removed = current_modules
8489                .into_iter()
8490                .filter(|module_id| {
8491                    !resulting_modules
8492                        .iter()
8493                        .any(|(configured_id, _)| configured_id == module_id)
8494                })
8495                .collect::<Vec<_>>();
8496            // A candidate preview also names providers the candidate disables.
8497            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8498            let disabled = match &mode {
8499                RescanMode::Candidate(_) => resulting_modules
8500                    .iter()
8501                    .filter(|(_, enabled)| !enabled)
8502                    .map(|(module_id, _)| module_id.clone())
8503                    .collect::<Vec<_>>(),
8504                _ => Vec::new(),
8505            };
8506            self.capability_evaluator.preview_warnings(
8507                resulting_modules,
8508                &removed,
8509                &disabled,
8510                &registrations,
8511            )
8512        } else {
8513            Vec::new()
8514        };
8515        let reconciled = match (&mode, approved_preview.as_ref()) {
8516            (RescanMode::Preview, Some(approved)) => Ok((
8517                config_gate::preview_approved_daemon(approved, &modules),
8518                Vec::new(),
8519            )),
8520            (RescanMode::Candidate(candidate), _) => self
8521                .preview_candidate(&context, modules, candidate)
8522                .map(|result| (result, Vec::new())),
8523            _ => {
8524                self.reconcile_supervised_modules(
8525                    &context.supervisor,
8526                    modules,
8527                    preview,
8528                    requester.clone(),
8529                )
8530                .await
8531            }
8532        };
8533        let (result, changed) = match reconciled {
8534            Ok(result) => result,
8535            Err(message) => {
8536                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8537            }
8538        };
8539        if !preview {
8540            if let Some(ledger) = &self.activity {
8541                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8542                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8543            }
8544            if let Err(code) = self.configure_activity(activity_config).await {
8545                warn!(
8546                    code,
8547                    "activity retention could not be applied during rescan"
8548                );
8549            }
8550            self.capability_evaluator
8551                .configure(configured_capabilities, reserved_capabilities);
8552            self.capability_evaluator.wake_deadline_loop();
8553            self.refresh_capability_requirements();
8554        }
8555        let mut result = result;
8556        result.restart_required = restart_required;
8557        result.capability_warnings = preview_capability_warnings;
8558        let response = ClientControlResponse::SupervisorRescan { result };
8559        Ok(vec![control_response_body_frame(
8560            &frame,
8561            &response,
8562            "ClientControlResponse::SupervisorRescan",
8563        )?])
8564    }
8565
8566    async fn handle_supervisor_release_reserved(
8567        &self,
8568        frame: Frame,
8569        module_id: String,
8570    ) -> Result<Vec<Frame>, RouterError> {
8571        let Some(context) = self.rescan.clone() else {
8572            return Ok(vec![control_error_frame(
8573                &frame,
8574                "release_unavailable",
8575                "reserved-id release requires a daemon started with a reloadable config path",
8576            )?]);
8577        };
8578        let operation_lock = self.supervisor.operation_lock();
8579        let _operation_guard = operation_lock.lock().await;
8580        let approved = if let Some(owner) = &self.config_runtime {
8581            // Observe the file as a proposal, but decide membership solely from
8582            // approved bytes. A proposed re-add must not retain a removed id.
8583            match owner
8584                .on_blocking(|owner| {
8585                    owner.observe_file_proposal()?;
8586                    owner.approved_daemon_configuration()
8587                })
8588                .await
8589            {
8590                Ok(config) => config,
8591                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8592            }
8593        } else {
8594            None
8595        };
8596        let loaded = if let Some(approved) = approved {
8597            Ok(Some(approved))
8598        } else {
8599            crate::daemon_config::load(&context.config_path)
8600        };
8601        let loaded = match loaded {
8602            Ok(Some(config)) => config,
8603            Ok(None) => {
8604                return Ok(vec![control_error_frame(
8605                    &frame,
8606                    "invalid_daemon_config",
8607                    format!(
8608                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8609                        context.config_path.display()
8610                    ),
8611                )?])
8612            }
8613            Err(err) => {
8614                return Ok(vec![control_error_frame(
8615                    &frame,
8616                    "invalid_daemon_config",
8617                    format!("unable to verify reserved-id release against daemon config: {err}"),
8618                )?])
8619            }
8620        };
8621        if loaded
8622            .modules
8623            .iter()
8624            .any(|configured| configured.module_id == module_id)
8625        {
8626            return Ok(vec![control_error_frame(
8627                &frame,
8628                "reserved_module_configured",
8629                format!(
8630                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8631                ),
8632            )?]);
8633        }
8634        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8635            return Ok(vec![control_error_frame(
8636                &frame,
8637                "reserved_gate_not_retained",
8638                format!(
8639                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8640                ),
8641            )?]);
8642        }
8643
8644        let response = ClientControlResponse::SupervisorAck {
8645            module_id,
8646            applied: true,
8647        };
8648        Ok(vec![control_response_body_frame(
8649            &frame,
8650            &response,
8651            "ClientControlResponse::SupervisorAck",
8652        )?])
8653    }
8654
8655    /// Compare the configured module set with the supervised one, changing
8656    /// nothing. The staged spec each supervised module holds is what the
8657    /// configured entry is compared with.
8658    fn plan_rescan(
8659        &self,
8660        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8661    ) -> Result<RescanPlan, String> {
8662        let mut current = BTreeMap::new();
8663        for module in self.supervisor.list() {
8664            let (spec, health) = module.configuration().map_err(|err| {
8665                format!(
8666                    "failed to read configuration for module_id '{}': {err}",
8667                    module.module_id()
8668                )
8669            })?;
8670            let enabled = module
8671                .status()
8672                .map_err(|err| {
8673                    format!(
8674                        "failed to read status for module_id '{}': {err}",
8675                        module.module_id()
8676                    )
8677                })?
8678                .enabled;
8679            current.insert(
8680                module.module_id().to_string(),
8681                (module, spec, health, enabled),
8682            );
8683        }
8684        let configured = configured_modules
8685            .into_iter()
8686            .map(|module| (module.module_id.clone(), module))
8687            .collect::<BTreeMap<_, _>>();
8688
8689        let added = configured
8690            .keys()
8691            .filter(|module_id| !current.contains_key(*module_id))
8692            .cloned()
8693            .collect::<Vec<_>>();
8694        let removed = current
8695            .keys()
8696            .filter(|module_id| !configured.contains_key(*module_id))
8697            .cloned()
8698            .collect::<Vec<_>>();
8699        let mut changed_pending_reload = Vec::new();
8700        let mut changed_pending = Vec::new();
8701        let mut configuration_changes = BTreeSet::new();
8702        let mut enabled_changes = BTreeSet::new();
8703        let mut unchanged = 0_u32;
8704        let publication = self
8705            .config_runtime
8706            .as_ref()
8707            .and_then(|owner| owner.polled_snapshot().ok());
8708
8709        for (module_id, configured_module) in &configured {
8710            let Some((module, current_spec, current_health, current_enabled)) =
8711                current.get(module_id)
8712            else {
8713                continue;
8714            };
8715            // Compare the whole launch spec so a future launch field cannot
8716            // accidentally become a live-only policy change. Health is stored
8717            // separately and applies live without replacing the process.
8718            let launch_changed = *current_spec != configured_module.module_spec();
8719            let configuration_changed =
8720                launch_changed || *current_health != configured_module.health;
8721            let pending = self.pending_module_fields(
8722                module,
8723                Some(configured_module),
8724                configuration_changed,
8725                Self::registration_channel_in_force(
8726                    publication
8727                        .as_ref()
8728                        .and_then(|view| view.registration_declaration(module_id))
8729                        .as_deref(),
8730                    publication
8731                        .as_ref()
8732                        .and_then(|view| match &view.approved_daemon {
8733                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8734                                config,
8735                                ..
8736                            } => config
8737                                .modules
8738                                .iter()
8739                                .find(|entry| entry.module_id == *module_id)
8740                                .map(|entry| entry.registration_channel),
8741                            _ => None,
8742                        }),
8743                ),
8744            )?;
8745            let has_pending = !pending.is_empty();
8746            if has_pending {
8747                changed_pending.push(subc_control::SupervisorPendingModule {
8748                    module_id: module_id.clone(),
8749                    fields: pending
8750                        .into_iter()
8751                        .map(|mut field| {
8752                            field.value = None;
8753                            field
8754                        })
8755                        .collect(),
8756                });
8757            }
8758            // Applying a rescan also replaces the recorded config value, even
8759            // when an operator already put the runtime in the requested state.
8760            let enabled_changed = *current_enabled != configured_module.enabled
8761                || self
8762                    .capability_evaluator
8763                    .configured_enabled(module_id)
8764                    .is_some_and(|enabled| enabled != configured_module.enabled);
8765            if configuration_changed {
8766                configuration_changes.insert(module_id.clone());
8767            }
8768            if launch_changed {
8769                changed_pending_reload.push(module_id.clone());
8770            }
8771            if enabled_changed {
8772                enabled_changes.insert(module_id.clone());
8773            }
8774            if !configuration_changed && !enabled_changed && !has_pending {
8775                unchanged = unchanged.saturating_add(1);
8776            }
8777        }
8778        Ok(RescanPlan {
8779            current,
8780            configured,
8781            added,
8782            removed,
8783            changed_pending_reload,
8784            changed_pending,
8785            configuration_changes,
8786            enabled_changes,
8787            unchanged,
8788        })
8789    }
8790
8791    /// Reconcile the running module set against the configured one.
8792    ///
8793    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8794    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8795    /// deliberately shares this function with the executing path rather than
8796    /// computing the same diff somewhere else -- two implementations of one
8797    /// decision agree until they do not, and the whole value of a preview is that
8798    /// it describes the operation that will actually run.
8799    async fn reconcile_supervised_modules(
8800        &self,
8801        supervisor: &Supervisor,
8802        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8803        preview: bool,
8804        requester: Principal,
8805    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8806        let plan = self.plan_rescan(configured_modules)?;
8807
8808        // Everything above this point is pure computation over two snapshots.
8809        // Everything below MUTATES. The preview returns here so the boundary is a
8810        // single early return rather than a condition repeated at each mutation
8811        // site, where one missed guard would apply part of a change the caller was
8812        // told would not happen.
8813        if preview {
8814            return Ok((plan.preview_result(), Vec::new()));
8815        }
8816        let changed = plan
8817            .configuration_changes
8818            .union(&plan.enabled_changes)
8819            .cloned()
8820            .collect::<Vec<_>>();
8821        let RescanPlan {
8822            current,
8823            configured,
8824            added,
8825            removed,
8826            changed_pending_reload,
8827            changed_pending,
8828            configuration_changes,
8829            enabled_changes,
8830            unchanged,
8831        } = plan;
8832        // The staged generation moves before the first change rather than
8833        // after the last, so a rescan that fails partway still invalidates
8834        // every earlier `supervisor.rescan_checked` preview: part of its diff
8835        // may have run.
8836        if !(added.is_empty()
8837            && removed.is_empty()
8838            && configuration_changes.is_empty()
8839            && changed_pending.is_empty()
8840            && enabled_changes.is_empty())
8841        {
8842            if let Some(context) = &self.rescan {
8843                context
8844                    .generation
8845                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8846            }
8847        }
8848
8849        for module_id in &removed {
8850            let module = &current
8851                .get(module_id)
8852                .expect("removed module came from current supervisor state")
8853                .0;
8854            module
8855                .retire_requested(Some(requester.clone()))
8856                .await
8857                .map_err(|err| {
8858                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8859                })?;
8860            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8861            //
8862            // `handle_route_open` resolves an absent module in three steps:
8863            // registry, then supervisor status, then tombstone. Retiring first
8864            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8865            // went with the teardown above, the supervisor entry went with
8866            // `retire`, and the tombstone does not exist yet -- so a route.open
8867            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8868            // it") for a module that was deliberately removed and whose caller
8869            // should get `module_removed` (TERMINAL, carrying a removal age).
8870            //
8871            // Writing the tombstone first closes it: during the window the
8872            // supervisor entry still answers, so the caller gets
8873            // `target_unavailable` -- retryable, and TRUE, because the module
8874            // is mid-teardown. After both statements it is `module_removed`.
8875            // No instant remains where a removed module reads as one that
8876            // never existed.
8877            //
8878            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8879            // the absence of a test beside a fix invites deletion: these are
8880            // two sync statements with no await between them, so reaching the
8881            // window needs a second worker thread to land exactly between them
8882            // and there is no hook to force it. MEASURED: the 25 daemon_config
8883            // tests pass identically with the old order and the new one, so
8884            // the existing suite cannot see this and a green run is not
8885            // evidence either way. What the suite does hold is the
8886            // post-condition -- a removed module answers `module_removed` --
8887            // which this preserves.
8888            //
8889            // Found by an Athena panel reading the shipped tree against a
8890            // design note (2026-09-19), as the one concrete instance of that
8891            // note's class that survived contact with source. Direction is
8892            // benign: retryable where terminal was intended, never the reverse.
8893            self.supervisor.record_rescan_removal(module_id);
8894            self.supervisor.retire(module_id);
8895            self.route_outages.forget(module_id);
8896        }
8897
8898        for module_id in configured.keys() {
8899            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8900                continue;
8901            };
8902            let configured_module = configured
8903                .get(module_id)
8904                .expect("configured module id came from configured map");
8905            if configuration_changes.contains(module_id) {
8906                module
8907                    .update_configuration(
8908                        configured_module.module_spec(),
8909                        configured_module.health.clone(),
8910                        configured_module.drain_timeout_ms,
8911                    )
8912                    .await
8913                    .map_err(|err| {
8914                        format!(
8915                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8916                        )
8917                    })?;
8918            }
8919            // Config-only drift is applied by the evaluator's config update;
8920            // do not turn it into a runtime start or stop.
8921            if *current_enabled != configured_module.enabled {
8922                // A rescan that starts or stops a module applies an operator's
8923                // edit to the config, so the resulting outage was asked for.
8924                self.route_outages.mark_operator_action(module_id);
8925                module
8926                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8927                    .await
8928                    .map_err(|err| {
8929                        self.route_outages.operator_action_ended_unrefused(module_id);
8930                        format!(
8931                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8932                            configured_module.enabled
8933                        )
8934                    })?;
8935            }
8936        }
8937
8938        for module_id in &added {
8939            let configured_module = configured
8940                .get(module_id)
8941                .expect("added module id came from configured map");
8942            supervisor
8943                .supervise_configured_requested_async(
8944                    configured_module.module_spec(),
8945                    configured_module.enabled,
8946                    configured_module.health.clone(),
8947                    configured_module.drain_timeout_ms,
8948                    configured_module.restart,
8949                    configured_module.register_timeout,
8950                    Some(requester.clone()),
8951                )
8952                .await
8953                .map_err(|err| {
8954                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8955                })?;
8956        }
8957
8958        if let Some(context) = &self.rescan {
8959            let mut entries = context
8960                .module_entries
8961                .lock()
8962                .unwrap_or_else(|e| e.into_inner());
8963            entries.record(&configured, &added, &removed);
8964        }
8965
8966        Ok((
8967            SupervisorRescanResult {
8968                added,
8969                removed,
8970                changed_pending_reload,
8971                changed_pending,
8972                enabled_changes: enabled_changes.iter().cloned().collect(),
8973                unchanged,
8974                preview: false,
8975                // Filled by the caller, which is the only layer that can see the
8976                // previous config to diff against.
8977                restart_required: Vec::new(),
8978                capability_warnings: Vec::new(),
8979                module_actions: Vec::new(),
8980                earlier_pending: Vec::new(),
8981                expect: None,
8982            },
8983            changed,
8984        ))
8985    }
8986
8987    async fn handle_supervisor_set_enabled(
8988        &self,
8989        frame: Frame,
8990        module_id: String,
8991        enabled: bool,
8992        requester: Principal,
8993    ) -> Result<Vec<Frame>, RouterError> {
8994        let operation_lock = self.supervisor.operation_lock();
8995        let _operation_guard = operation_lock.lock().await;
8996        let Some(module) = self.supervisor.get(&module_id) else {
8997            return Ok(vec![control_error_frame(
8998                &frame,
8999                "unknown_module",
9000                format!("module_id '{module_id}' is not supervised"),
9001            )?]);
9002        };
9003
9004        // Enabling counts as well as disabling: a module an operator starts
9005        // is refused until it registers, and that wait was asked for.
9006        self.route_outages.mark_operator_action(&module_id);
9007        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
9008            Ok(applied) => applied,
9009            Err(err) => {
9010                self.route_outages
9011                    .operator_action_ended_unrefused(&module_id);
9012                return Ok(vec![control_error_frame(
9013                    &frame,
9014                    if err.is_config_gate_error() {
9015                        "config_gated"
9016                    } else {
9017                        "target_unavailable"
9018                    },
9019                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
9020                )?]);
9021            }
9022        };
9023        if !applied {
9024            // Already in the requested state: nothing was made unavailable,
9025            // so the mark must not outlive this request.
9026            self.route_outages
9027                .operator_action_ended_unrefused(&module_id);
9028        }
9029
9030        self.capability_evaluator.wake_deadline_loop();
9031        self.refresh_capability_requirements();
9032        let response = ClientControlResponse::SupervisorAck { module_id, applied };
9033        Ok(vec![control_response_body_frame(
9034            &frame,
9035            &response,
9036            "ClientControlResponse::SupervisorAck",
9037        )?])
9038    }
9039
9040    async fn handle_supervisor_health_probe(
9041        &self,
9042        ctx: &RouteCtx,
9043        frame: Frame,
9044        module_id: String,
9045    ) -> Result<Vec<Frame>, RouterError> {
9046        self.refresh_capability_requirements();
9047        let Some(registration) = self
9048            .registry
9049            .get_module(&module_id)
9050            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
9051        else {
9052            return Ok(vec![control_error_frame(
9053                &frame,
9054                "unknown_module",
9055                format!("module_id '{module_id}' is not registered"),
9056            )?]);
9057        };
9058
9059        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
9060        // named for it. Making `module_registration_grants_op` return false
9061        // unconditionally reddens five tests, and every one is named for something
9062        // else -- capability relay, probe/bind demultiplexing, supervision-only
9063        // probing. They exercise a successful advertisement check on the way to their
9064        // own subject.
9065        //
9066        // Real protection, fragile in a specific way: narrowing any of those tests to
9067        // focus on its stated subject would silently remove coverage nobody knows
9068        // they are carrying. Recorded here rather than as a sixth test, because the
9069        // useful fact is WHICH tests hold the guard up -- a new test would add
9070        // coverage without telling the next person what the existing ones quietly do.
9071        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
9072        {
9073            return Ok(vec![control_error_frame(
9074                &frame,
9075                "health_not_advertised",
9076                format!("module_id '{module_id}' did not advertise health.check"),
9077            )?]);
9078        }
9079
9080        self.observe_control_wait(
9081            ctx,
9082            Some(&registration.manifest.module_id),
9083            ops::SUPERVISOR_HEALTH_PROBE,
9084            async {
9085                let deadline = Instant::now() + self.health_probe_timeout;
9086                let pending = match self.forwarding.begin_module_control_rpc_for(
9087                    &module_id,
9088                    MODULE_CONTROL_OP_HEALTH_CHECK,
9089                    deadline,
9090                ) {
9091                    Ok(pending) => pending,
9092                    Err(err) => {
9093                        return Ok(vec![control_error_frame(
9094                            &frame,
9095                            forwarding_error_code(&err),
9096                            err.to_string(),
9097                        )?])
9098                    }
9099                };
9100
9101                let PendingModuleControlRpc {
9102                    endpoint,
9103                    module_sink,
9104                    negotiated_ver,
9105                    corr: probe_corr,
9106                    receiver,
9107                } = pending;
9108                let mut guard =
9109                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9110                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9111                    .map_err(|err| {
9112                        RouterError::backend(
9113                            0,
9114                            frame.header.corr,
9115                            format!("failed to encode health.check request: {err}"),
9116                        )
9117                    })?;
9118                let probe_frame = Frame::build_with_version(
9119                    negotiated_ver,
9120                    FrameType::Request,
9121                    control_flags(),
9122                    0,
9123                    0,
9124                    probe_corr,
9125                    probe_body,
9126                )
9127                .map_err(RouterError::FrameBuild)?;
9128
9129                // Queue admission and the reply share one deadline, so a module that
9130                // stops reading cannot park the requesting connection's reader forever.
9131                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9132                    Ok(Ok(())) => {}
9133                    Ok(Err(err)) => {
9134                        return Ok(vec![control_error_frame(
9135                            &frame,
9136                            "target_unavailable",
9137                            err.to_string(),
9138                        )?]);
9139                    }
9140                    Err(_) => {
9141                        return Ok(vec![control_error_frame(
9142                            &frame,
9143                            "module_timeout",
9144                            format!(
9145                                "module_id '{module_id}' did not answer health.check within {:?}",
9146                                self.health_probe_timeout
9147                            ),
9148                        )?]);
9149                    }
9150                }
9151
9152                match timeout_at(deadline, receiver).await {
9153                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9154                        Ok(vec![control_error_frame(
9155                            &frame,
9156                            "invalid_control_body",
9157                            "health.check returned an unexpected config response",
9158                        )?])
9159                    }
9160                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9161                        guard.disarm();
9162                        let Some(report) = response.health_report() else {
9163                            return Ok(vec![control_error_frame(
9164                                &frame,
9165                                "invalid_control_body",
9166                                "health.check RPC returned a non-health response",
9167                            )?]);
9168                        };
9169                        // Metrics go out whole here. The supervisor's cached snapshot
9170                        // caps this blob (see truncate_health_metrics), and this path
9171                        // exists precisely to answer without that cap -- so applying it
9172                        // here would leave no way to see what the cached view drops.
9173                        let HealthReport {
9174                            status,
9175                            detail,
9176                            metrics,
9177                        } = report;
9178                        let capability_detail = self
9179                            .capability_evaluator
9180                            .required_problem_detail(&module_id);
9181                        let response = ClientControlResponse::SupervisorHealthProbe {
9182                            module_id,
9183                            status,
9184                            detail: append_capability_problem_detail(detail, capability_detail),
9185                            metrics,
9186                        };
9187                        Ok(vec![control_response_body_frame(
9188                            &frame,
9189                            &response,
9190                            "ClientControlResponse::SupervisorHealthProbe",
9191                        )?])
9192                    }
9193                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9194                        guard.disarm();
9195                        // The module refused the health probe with its own body, so
9196                        // the refusal is relayed without the daemon-origin flag
9197                        // (bit 6): a client must not read it as the daemon's own
9198                        // refusal, which it may treat as never forwarded.
9199                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9200                    }
9201                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9202                        guard.disarm();
9203                        Ok(vec![control_error_frame(
9204                            &frame,
9205                            "target_unavailable",
9206                            message,
9207                        )?])
9208                    }
9209                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9210                        guard.disarm();
9211                        Ok(vec![control_error_frame(
9212                            &frame,
9213                            "invalid_control_body",
9214                            message,
9215                        )?])
9216                    }
9217                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9218                        guard.disarm();
9219                        Ok(vec![control_error_frame(
9220                            &frame,
9221                            "invalid_control_body",
9222                            format!("expected module-control op '{expected}', got '{actual}'"),
9223                        )?])
9224                    }
9225                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9226                        guard.disarm();
9227                        Ok(vec![control_error_frame(
9228                            &frame,
9229                            "module_timeout",
9230                            format!(
9231                                "module_id '{module_id}' answered health.check after {:?}",
9232                                self.health_probe_timeout
9233                            ),
9234                        )?])
9235                    }
9236                    Ok(Err(_)) => Ok(vec![control_error_frame(
9237                        &frame,
9238                        "target_unavailable",
9239                        "health.check waiter was canceled before the module responded",
9240                    )?]),
9241                    Err(_) => Ok(vec![control_error_frame(
9242                        &frame,
9243                        "module_timeout",
9244                        format!(
9245                            "module_id '{module_id}' did not answer health.check within {:?}",
9246                            self.health_probe_timeout
9247                        ),
9248                    )?]),
9249                }
9250            },
9251        )
9252        .await
9253    }
9254
9255    fn supervisor_status(
9256        &self,
9257        module_id: &str,
9258        corr: u64,
9259    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9260        self.supervisor
9261            .get(module_id)
9262            .map(|module| {
9263                let warming = module.is_warming_for_control("status").map_err(|err| {
9264                    RouterError::backend(
9265                        0,
9266                        corr,
9267                        format!(
9268                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9269                        ),
9270                    )
9271                })?;
9272                module.status_for_control("status").map_err(|err| {
9273                    RouterError::backend(
9274                        0,
9275                        corr,
9276                        format!(
9277                            "failed to read supervisor status for module_id '{module_id}': {err}"
9278                        ),
9279                    )
9280                }).map(|status| (status, warming))
9281            })
9282            .transpose()
9283    }
9284
9285    fn guard_module_control_op(
9286        &self,
9287        frame: &Frame,
9288        module_id: &str,
9289        op: &str,
9290    ) -> Result<Option<Frame>, RouterError> {
9291        if self.module_grants_op(module_id, op, frame.header.corr)? {
9292            return Ok(None);
9293        }
9294
9295        Ok(Some(control_error_frame(
9296            frame,
9297            "op_not_allowed",
9298            format!("module_id '{module_id}' did not grant control op '{op}'"),
9299        )?))
9300    }
9301
9302    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9303        self.registry
9304            .grants_control_op(module_id, op)
9305            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9306    }
9307
9308    fn handle_status_update(
9309        &self,
9310        endpoint: ModuleEndpointId,
9311        frame: Frame,
9312    ) -> Result<Vec<Frame>, RouterError> {
9313        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9314            Ok(update) => update,
9315            Err(err) => {
9316                // Forward-compat: a newer module may push a channel-0 op this subc
9317                // version doesn't know. The control contract says unknown push ops
9318                // are IGNORED, never answered with an error. Only a malformed body
9319                // for an op we DO know is a real error worth surfacing.
9320                if is_known_module_push_op(&frame.body) {
9321                    return Ok(vec![control_error_frame(
9322                        &frame,
9323                        "invalid_control_body",
9324                        format!("malformed module control push body: {err}"),
9325                    )?]);
9326                }
9327                return Ok(Vec::new());
9328            }
9329        };
9330
9331        match update {
9332            ModuleControlPush::RouteStatus {
9333                route_channel,
9334                route_epoch,
9335                status,
9336            } => {
9337                self.forwarding
9338                    .cache_status(endpoint, route_channel, route_epoch, status)
9339                    .map_err(RouterError::Forwarding)?;
9340            }
9341        }
9342        Ok(Vec::new())
9343    }
9344
9345    fn handle_route_poll(
9346        &self,
9347        ctx: &RouteCtx,
9348        frame: Frame,
9349        route_channel: u16,
9350        route_epoch: u32,
9351        kind: PollKind,
9352    ) -> Result<Vec<Frame>, RouterError> {
9353        let snapshot = self
9354            .forwarding
9355            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9356            .map_err(RouterError::Forwarding)?;
9357        let response = match (kind, snapshot) {
9358            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9359                ClientControlResponse::RoutePoll {
9360                    route_channel,
9361                    route_epoch,
9362                    status,
9363                    live: None,
9364                }
9365            }
9366            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9367                route_channel,
9368                route_epoch,
9369                status: None,
9370                live: None,
9371            },
9372            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9373                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9374                // is what makes reporting `true` correct rather than a
9375                // confident guess. `process_live` returns None only when the
9376                // module id has no supervisor snapshot at all -- an
9377                // externally-started module the daemon did not spawn -- and
9378                // for those the supervisor has no opinion to offer, ever. It
9379                // is never None for a supervised module in an unknown state:
9380                // a supervised module always has a snapshot, and the answer
9381                // comes from `state == Running && process_alive`.
9382                //
9383                // The route is Bound, so the module completed a HELLO on a
9384                // live connection; "the process this route points at is
9385                // running" is therefore attested by the binding rather than
9386                // assumed. Reporting `false` for an unsupervised module would
9387                // be the actual lie -- it would tell a client its healthy
9388                // route is dead because the daemon does not manage the
9389                // process.
9390                //
9391                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9392                // module whose liveness is genuinely unknown, e.g. a snapshot
9393                // that has not been populated yet -- THIS DEFAULT BECOMES
9394                // WRONG and must split: unsupervised stays true, unknown
9395                // becomes null so the client can tell the two apart. The
9396                // response field is already `Option<bool>`, so the wire can
9397                // carry that distinction today.
9398                let live = self
9399                    .process_liveness
9400                    .as_ref()
9401                    .and_then(|source| source.process_live(&module_id))
9402                    .unwrap_or(true);
9403                ClientControlResponse::RoutePoll {
9404                    route_channel,
9405                    route_epoch,
9406                    status: None,
9407                    live: Some(live),
9408                }
9409            }
9410            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9411                route_channel,
9412                route_epoch,
9413                status: None,
9414                live: Some(false),
9415            },
9416        };
9417
9418        Ok(vec![control_response_body_frame(
9419            &frame,
9420            &response,
9421            "ClientControlResponse::RoutePoll",
9422        )?])
9423    }
9424
9425    pub(crate) fn observe_module_control_completion(
9426        &self,
9427        completion: ModuleControlRpcCompletion,
9428    ) -> bool {
9429        match completion {
9430            ModuleControlRpcCompletion::Unknown => false,
9431            ModuleControlRpcCompletion::Settled => true,
9432            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9433                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9434                info!(
9435                    module_id = %module_id,
9436                    latency_ms,
9437                    "late health.check answer proves the module is alive"
9438                );
9439                match self
9440                    .supervisor
9441                    .record_late_health_answer(&module_id, latency_ms)
9442                {
9443                    Ok(true) => {}
9444                    Ok(false) => debug!(
9445                        module_id = %module_id,
9446                        latency_ms,
9447                        "late health.check answer has no active supervisor snapshot"
9448                    ),
9449                    Err(err) => warn!(
9450                        module_id = %module_id,
9451                        latency_ms,
9452                        error = %err,
9453                        "failed to record late health.check answer"
9454                    ),
9455                }
9456                true
9457            }
9458        }
9459    }
9460
9461    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9462    /// the module connection whose frame is being handled, or to the client that
9463    /// relay was opened for.
9464    ///
9465    /// This runs on the MODULE connection's frame handler, where returning `Err`
9466    /// ends that connection -- and a module connection carries every client's
9467    /// routes to that module, so ending it costs the whole fleet its tools.
9468    /// `ConnectionClosing` carries the id of the connection that is closing, and
9469    /// when that id is a CLIENT's, the condition is entirely about that one
9470    /// client's route.open. A client-scoped condition has no authority over a
9471    /// shared module connection, so it is logged and the single relay is dropped:
9472    /// the client is going away, and `complete_pending_relay` already removed the
9473    /// relay before failing, so there is nothing left to settle. Anything that
9474    /// relay still reserved is released by that client's own connection teardown,
9475    /// which is already under way -- that is what "closing" means.
9476    ///
9477    /// Every other failure is a statement about THIS connection and stays fatal:
9478    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9479    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9480    /// frames correctly.
9481    fn refuse_to_end_module_connection_for_a_client(
9482        &self,
9483        module_connection_id: ConnectionId,
9484        corr: u64,
9485        err: ForwardingError,
9486    ) -> Result<(), RouterError> {
9487        if let ForwardingError::ConnectionClosing { connection_id } = err {
9488            if connection_id != module_connection_id {
9489                warn!(
9490                    module_connection_id = module_connection_id.get(),
9491                    client_connection_id = connection_id.get(),
9492                    corr,
9493                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9494                );
9495                return Ok(());
9496            }
9497        }
9498        Err(RouterError::Forwarding(err))
9499    }
9500
9501    fn handle_module_relay_response(
9502        &self,
9503        connection_id: ConnectionId,
9504        frame: Frame,
9505    ) -> Result<Vec<Frame>, RouterError> {
9506        let mut secondary_error = None;
9507        let outcome = match frame.header.ty {
9508            FrameType::Response => match module_control_response_probe(&frame.body) {
9509                Ok(probe) if probe.op == "route.bind" => {
9510                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9511                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9512                            RouteBindRelayOutcome::Accepted
9513                        }
9514                        Ok(other) => {
9515                            let message =
9516                                format!("route.bind response carried unexpected body: {other:?}");
9517                            secondary_error = Some(control_error_frame(
9518                                &frame,
9519                                "invalid_control_body",
9520                                message.clone(),
9521                            )?);
9522                            RouteBindRelayOutcome::ModuleGone(message)
9523                        }
9524                        Err(err) => {
9525                            let message = format!("malformed route.bind response body: {err}");
9526                            secondary_error = Some(control_error_frame(
9527                                &frame,
9528                                "invalid_control_body",
9529                                message.clone(),
9530                            )?);
9531                            RouteBindRelayOutcome::ModuleGone(message)
9532                        }
9533                    }
9534                }
9535                Ok(probe) => {
9536                    let outcome = if matches!(
9537                        probe.op.as_str(),
9538                        "config.review" | "consent/v1" | "projects.enumerate"
9539                    ) {
9540                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9541                    } else {
9542                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9543                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9544                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9545                                "malformed {} response body: {err}",
9546                                probe.op
9547                            )),
9548                        }
9549                    };
9550                    let completion = self
9551                        .forwarding
9552                        .complete_module_control_rpc(
9553                            connection_id,
9554                            frame.header.corr,
9555                            Some(&probe.op),
9556                            outcome,
9557                        )
9558                        .map_err(RouterError::Forwarding)?;
9559                    if !self.observe_module_control_completion(completion) {
9560                        debug!(
9561                            connection_id = connection_id.get(),
9562                            corr = frame.header.corr,
9563                            op = %probe.op,
9564                            "dropping late or unknown module-control RPC response"
9565                        );
9566                    }
9567                    return Ok(Vec::new());
9568                }
9569                Err(err) => {
9570                    if let Some(expected_op) = self
9571                        .forwarding
9572                        .pending_module_control_op(connection_id, frame.header.corr)
9573                        .map_err(RouterError::Forwarding)?
9574                    {
9575                        let completion = self
9576                            .forwarding
9577                            .complete_module_control_rpc(
9578                                connection_id,
9579                                frame.header.corr,
9580                                None,
9581                                ModuleControlRpcOutcome::MalformedResponse(format!(
9582                                    "malformed {expected_op} response body: {err}"
9583                                )),
9584                            )
9585                            .map_err(RouterError::Forwarding)?;
9586                        if !self.observe_module_control_completion(completion) {
9587                            debug!(
9588                                connection_id = connection_id.get(),
9589                                corr = frame.header.corr,
9590                                "dropping late malformed module-control RPC response"
9591                            );
9592                        }
9593                        return Ok(Vec::new());
9594                    }
9595                    let message = format!("malformed route.bind response body: {err}");
9596                    secondary_error = Some(control_error_frame(
9597                        &frame,
9598                        "invalid_control_body",
9599                        message.clone(),
9600                    )?);
9601                    RouteBindRelayOutcome::ModuleGone(message)
9602                }
9603            },
9604            FrameType::Error => {
9605                if self
9606                    .forwarding
9607                    .pending_module_control_op(connection_id, frame.header.corr)
9608                    .map_err(RouterError::Forwarding)?
9609                    .is_some()
9610                {
9611                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9612                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9613                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9614                            "malformed module-control ERROR body: {err}"
9615                        )),
9616                    };
9617                    let completion = self
9618                        .forwarding
9619                        .complete_module_control_rpc(
9620                            connection_id,
9621                            frame.header.corr,
9622                            None,
9623                            outcome,
9624                        )
9625                        .map_err(RouterError::Forwarding)?;
9626                    if !self.observe_module_control_completion(completion) {
9627                        debug!(
9628                            connection_id = connection_id.get(),
9629                            corr = frame.header.corr,
9630                            "dropping late or unknown module-control RPC error"
9631                        );
9632                    }
9633                    return Ok(Vec::new());
9634                }
9635                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9636                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9637                    Err(err) => {
9638                        let message = format!("malformed route.bind ERROR body: {err}");
9639                        secondary_error = Some(control_error_frame(
9640                            &frame,
9641                            "invalid_control_body",
9642                            message.clone(),
9643                        )?);
9644                        RouteBindRelayOutcome::ModuleGone(message)
9645                    }
9646                }
9647            }
9648            ty => {
9649                return Ok(vec![control_error_frame(
9650                    &frame,
9651                    "unsupported_control_frame",
9652                    format!("unsupported module channel-0 frame {ty:?}"),
9653                )?])
9654            }
9655        };
9656
9657        let settled =
9658            self.forwarding
9659                .complete_pending_relay(connection_id, frame.header.corr, outcome);
9660        let completion = match settled {
9661            Ok(completion) => completion,
9662            Err(err) => {
9663                self.refuse_to_end_module_connection_for_a_client(
9664                    connection_id,
9665                    frame.header.corr,
9666                    err,
9667                )?;
9668                return Ok(secondary_error.into_iter().collect());
9669            }
9670        };
9671        if let Some(target) = completion.abandoned.as_ref() {
9672            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9673        }
9674        if !completion.settled {
9675            debug!(
9676                connection_id = connection_id.get(),
9677                corr = frame.header.corr,
9678                frame_type = ?frame.header.ty,
9679                "dropping late or unknown route.bind relay response"
9680            );
9681        }
9682        Ok(secondary_error.into_iter().collect())
9683    }
9684
9685    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9686        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9687        // GOODBYE ends the connection's logical session even when its socket
9688        // stays open. Use disconnect teardown so verdicts, client notices and
9689        // scope authority are released at the same lifecycle boundary.
9690        self.cleanup_connection_with_end_reason(
9691            connection_id,
9692            RegistrationEndReason::ExplicitGoodbye,
9693        )
9694        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9695        Ok(Vec::new())
9696    }
9697}
9698
9699impl Default for ControlHandler {
9700    fn default() -> Self {
9701        Self::new(Arc::new(Registry::default()))
9702    }
9703}
9704
9705impl crate::supervise::SwapPromotionObserver for ControlHandler {
9706    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9707        self.apply_registration_capabilities(registration);
9708    }
9709}
9710
9711fn capability_requirement_status(status: RequirementStatus) -> CapabilityRequirementStatus {
9712    CapabilityRequirementStatus {
9713        consumer: status.consumer,
9714        capability: status.capability,
9715        need: match status.need {
9716            subc_protocol::manifest::CapabilityNeed::Required => "required".to_string(),
9717            subc_protocol::manifest::CapabilityNeed::Optional => "optional".to_string(),
9718        },
9719        verdict: status.verdict.as_str().to_string(),
9720        episode_seq: status.episode_seq,
9721        config_satisfiable: status.config_satisfiable,
9722        runtime_available: status.runtime_available,
9723        detail: status.detail,
9724    }
9725}
9726
9727fn append_capability_problem_detail(
9728    detail: Option<String>,
9729    capability_detail: Option<String>,
9730) -> Option<String> {
9731    match (detail, capability_detail) {
9732        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9733        (Some(detail), None) => Some(detail),
9734        (None, Some(capability_detail)) => Some(capability_detail),
9735        (None, None) => None,
9736    }
9737}
9738
9739fn subc_ops() -> Vec<String> {
9740    SUBC_CONTROL_OPS
9741        .iter()
9742        .map(|op| (*op).to_string())
9743        .collect()
9744}
9745
9746fn module_subc_ops() -> Vec<String> {
9747    SUBC_CONTROL_OPS
9748        .iter()
9749        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9750        .map(|op| (*op).to_string())
9751        .collect()
9752}
9753
9754#[cfg(test)]
9755fn module_baseline_control_ops() -> Vec<String> {
9756    MODULE_BASELINE_CONTROL_OPS
9757        .iter()
9758        .map(|op| (*op).to_string())
9759        .collect()
9760}
9761
9762fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9763    let mut seen = HashSet::new();
9764    let mut effective = Vec::new();
9765    for op in MODULE_BASELINE_CONTROL_OPS {
9766        if seen.insert((*op).to_string()) {
9767            effective.push((*op).to_string());
9768        }
9769    }
9770    for op in declared.unwrap_or_default() {
9771        if seen.insert(op.clone()) {
9772            effective.push(op);
9773        }
9774    }
9775    effective
9776}
9777
9778fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9779    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9780}
9781
9782fn target_module_id(target: &RouteTarget) -> &str {
9783    match target {
9784        RouteTarget::ToolProvider { module_id }
9785        | RouteTarget::ManagementSurface { module_id }
9786        | RouteTarget::InternalService { module_id, .. } => module_id,
9787    }
9788}
9789
9790fn target_has_required_role(
9791    target: &RouteTarget,
9792    roles: &[crate::registry::AdmissionRole],
9793) -> bool {
9794    use crate::registry::AdmissionRole;
9795    roles.iter().any(|role| match (target, role) {
9796        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9797        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9798        (
9799            RouteTarget::InternalService { service_id, .. },
9800            AdmissionRole::InternalService(provided),
9801        ) => service_id == provided,
9802        _ => false,
9803    })
9804}
9805
9806fn is_routable_role(role: &ProviderRole) -> bool {
9807    matches!(
9808        role,
9809        ProviderRole::ToolProvider { .. }
9810            | ProviderRole::ManagementSurface { .. }
9811            | ProviderRole::InternalService { .. }
9812    )
9813}
9814
9815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9816enum ControlRequestBodyError {
9817    UnknownOp,
9818    InvalidBody,
9819}
9820
9821#[derive(Debug, Deserialize)]
9822struct ControlOpProbe {
9823    op: String,
9824}
9825
9826fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9827    serde_json::from_slice(body).or_else(|original| {
9828        #[derive(Deserialize)]
9829        struct ConsentProbe {
9830            protocol: String,
9831        }
9832        match serde_json::from_slice::<ConsentProbe>(body) {
9833            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9834                Ok(ControlOpProbe { op: probe.protocol })
9835            }
9836            _ => Err(original),
9837        }
9838    })
9839}
9840
9841/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9842/// this set is treated as a forward-compat unknown and ignored rather than errored.
9843const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9844
9845fn is_known_module_push_op(body: &[u8]) -> bool {
9846    serde_json::from_slice::<ControlOpProbe>(body)
9847        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9848        .unwrap_or(false)
9849}
9850
9851fn is_known_module_request_op(body: &[u8]) -> bool {
9852    serde_json::from_slice::<ControlOpProbe>(body)
9853        .map(|probe| is_module_to_subc_op(&probe.op))
9854        .unwrap_or(false)
9855}
9856
9857fn is_module_to_subc_op(op: &str) -> bool {
9858    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9859}
9860
9861fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9862    debug!(
9863        op = %op,
9864        connection_id = connection_id.get(),
9865        corr,
9866        "control dispatch"
9867    );
9868}
9869
9870fn log_slow_control_dispatch(
9871    dispatch_started_at: Option<StdInstant>,
9872    op: &'static str,
9873    connection_id: ConnectionId,
9874    corr: u64,
9875    route_open_timings: Option<&RouteOpenTimings>,
9876) {
9877    let Some(dispatch_started_at) = dispatch_started_at else {
9878        return;
9879    };
9880    // Use the same monotonic clock as the phase timers and relay deadline.
9881    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9882    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9883        if let Some(timings) = route_open_timings {
9884            warn!(
9885                op = %op,
9886                connection_id = connection_id.get(),
9887                corr,
9888                elapsed_ms = elapsed.as_millis() as u64,
9889                module_id = ?timings.module_id,
9890                principal = %timings.principal,
9891                admission_ms = timings.admission.as_millis() as u64,
9892                project_root_ms = timings.project_root.as_millis() as u64,
9893                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9894                bind_send_ms = timings.bind_send.as_millis() as u64,
9895                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9896                "slow control dispatch"
9897            );
9898            return;
9899        }
9900        warn!(
9901            op = %op,
9902            connection_id = connection_id.get(),
9903            corr,
9904            elapsed_ms = elapsed.as_millis() as u64,
9905            "slow control dispatch"
9906        );
9907    }
9908}
9909
9910/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9911#[cfg(test)]
9912type TestCallerLookup =
9913    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9914
9915/// Every new client operation needs an explicit privilege decision here.
9916fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9917    request.privileged_operation()
9918}
9919
9920trait PrivilegedRequest {
9921    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9922}
9923
9924impl PrivilegedRequest for ClientControlRequest {
9925    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9926        let request = self;
9927        match request {
9928        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9929            Some(PrivilegedOperation::Restart { module_id })
9930        }
9931        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9932            Some(PrivilegedOperation::Swap { module_id })
9933        }
9934        ClientControlRequest::SupervisorReload { module_id } => {
9935            Some(PrivilegedOperation::Reload { module_id })
9936        }
9937        ClientControlRequest::SupervisorRescan { preview } => {
9938            if *preview {
9939                None
9940            } else {
9941                Some(PrivilegedOperation::Rescan)
9942            }
9943        }
9944        // Only the well-formed apply asks for approval. A preview changes
9945        // nothing, and any other combination is refused before it touches
9946        // anything, so prompting the operator for it would ask about a request
9947        // that cannot run.
9948        ClientControlRequest::SupervisorRescanChecked {
9949            preview,
9950            candidate,
9951            expect,
9952        } => (!*preview && candidate.is_none() && expect.is_some())
9953            .then_some(PrivilegedOperation::Rescan),
9954        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9955            Some(PrivilegedOperation::SetEnabled {
9956                module_id,
9957                enabled: *enabled,
9958            })
9959        }
9960        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9961            Some(PrivilegedOperation::ReleaseReserved { module_id })
9962        }
9963        ClientControlRequest::ServerDescribe {}
9964        // The announcement uses the same client admission as supervisor.restart,
9965        // but cannot stop anything itself and needs no operator confirmation.
9966        | ClientControlRequest::DaemonShutdownIntent { .. }
9967        | ClientControlRequest::CatalogList { .. }
9968        | ClientControlRequest::RouteOpen { .. }
9969        | ClientControlRequest::RoutePoll { .. }
9970        | ClientControlRequest::SupervisorList {}
9971        | ClientControlRequest::SupervisorHealth {}
9972        | ClientControlRequest::SupervisorHealthProbe { .. }
9973        | ClientControlRequest::SupervisorRoutes { .. }
9974        | ClientControlRequest::SupervisorProvenance { .. }
9975        | ClientControlRequest::SupervisorStderrTail { .. }
9976        | ClientControlRequest::SupervisorTerminals { .. }
9977        | ClientControlRequest::SupervisorSpawnSnapshot {}
9978        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9979    }
9980    }
9981}
9982
9983fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9984    match request {
9985        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9986        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9987        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
9988        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
9989        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
9990        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
9991        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
9992        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
9993        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
9994        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
9995        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
9996        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
9997        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
9998        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
9999        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
10000        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
10001        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
10002        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
10003        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
10004        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
10005        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
10006    }
10007}
10008
10009/// The caller of one `route.open`, as its `route.open refused` line names it.
10010///
10011/// A connection id alone cannot name a caller after the fact: ids restart at
10012/// every daemon restart, so the same number belongs to different modules
10013/// before and after one. These three fields are what the refused line needs
10014/// to be attributable on its own, and they are rendered with the same helpers
10015/// as the `route.open accepted` line so both directions grep alike.
10016struct RouteOpenCaller {
10017    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
10018    /// when the request presented a consumer identity whose launch nonce did
10019    /// not verify. The claimed module id is never printed as a principal.
10020    principal: String,
10021    /// `none` for an unscoped open; the admitted stamp's label once scope
10022    /// admission issued one; before that, the requested selector's label.
10023    scope: String,
10024    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
10025    /// because it is a string the caller chose.
10026    harness: String,
10027}
10028
10029impl RouteOpenCaller {
10030    fn new(
10031        principal: Option<&Principal>,
10032        scope: Option<&ScopeSelector>,
10033        identity: &BindIdentity,
10034    ) -> Self {
10035        Self {
10036            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
10037            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
10038            harness: bounded_log_text(&identity.harness),
10039        }
10040    }
10041
10042    /// For a refusal that has no parsed request at hand: names whatever the
10043    /// frame still says, and `unknown` where it says nothing parseable.
10044    fn unknown() -> Self {
10045        Self {
10046            principal: "unknown".to_string(),
10047            scope: "unknown".to_string(),
10048            harness: "unknown".to_string(),
10049        }
10050    }
10051}
10052
10053/// Longest client-chosen text (a scope ref, a harness) a route.open log line
10054/// prints before cutting it.
10055const MAX_LOGGED_TEXT_CHARS: usize = 64;
10056
10057/// `value` Debug-quoted, so control characters land escaped and cannot forge
10058/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
10059/// `…` inside the quotes so one request cannot flood the line.
10060fn bounded_log_text(value: &str) -> String {
10061    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
10062    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
10063        bounded.push('…');
10064    }
10065    format!("{bounded:?}")
10066}
10067
10068/// The `scope=` field of the `route.open accepted` line, from the stamp that
10069/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
10070/// so a ref holding control characters cannot forge a log line, and cut to 64
10071/// characters with a trailing `…` to bound the line. The bind proof and the
10072/// scope's attributes never appear.
10073fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
10074    use subc_protocol::scope::ScopeKind;
10075    let kind = match stamp.kind {
10076        ScopeKind::Head => "head",
10077        ScopeKind::Worker => "worker",
10078        ScopeKind::Ephemeral => "ephemeral",
10079        ScopeKind::Federated => "federated",
10080        _ => "unknown",
10081    };
10082    format!(
10083        "{kind}/{}/{}@{}",
10084        principal_label(&stamp.owner),
10085        bounded_log_text(&stamp.scope_ref),
10086        stamp.scope_epoch
10087    )
10088}
10089
10090/// The `scope=` field of a `route.open refused` line for an open refused
10091/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
10092/// The kind is not known yet, so the literal `requested` stands in its place.
10093/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
10094/// owner it has not been checked against the configured modules: a quoted
10095/// owner means the value was never validated. The bind proof never appears.
10096fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10097    let epoch = selector
10098        .scope_epoch
10099        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10100    format!(
10101        "requested/{}/{}@{epoch}",
10102        bounded_log_text(&principal_label(&selector.owner)),
10103        bounded_log_text(&selector.scope_ref),
10104    )
10105}
10106
10107fn principal_label(principal: &Principal) -> String {
10108    match principal {
10109        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10110        Principal::Direct => "direct".to_string(),
10111        other => format!("{other:?}"),
10112    }
10113}
10114
10115fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10116    match request {
10117        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10118        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10119            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10120        }
10121        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10122        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10123        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10124        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10125        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10126            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10127        }
10128        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10129        _ => "unsupported",
10130    }
10131}
10132
10133fn parse_client_control_request(
10134    body: &[u8],
10135) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10136    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10137        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10138            Ok(probe)
10139                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10140                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10141            {
10142                ControlRequestBodyError::InvalidBody
10143            }
10144            Ok(_) => ControlRequestBodyError::UnknownOp,
10145            Err(_) => ControlRequestBodyError::InvalidBody,
10146        };
10147        (err, classification)
10148    })
10149}
10150
10151fn parse_module_control_request_from_module(
10152    body: &[u8],
10153) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10154    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10155        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10156            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10157            Ok(_) => ControlRequestBodyError::UnknownOp,
10158            Err(_) => ControlRequestBodyError::InvalidBody,
10159        };
10160        (err, classification)
10161    })
10162}
10163
10164#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10165enum ProviderRoleKind {
10166    ToolProvider,
10167    PipelineStage,
10168    ManagementSurface,
10169    InternalService,
10170}
10171
10172fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10173    match role {
10174        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10175        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10176        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10177        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10178    }
10179}
10180
10181fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10182    roles.iter().map(provider_role_kind).collect()
10183}
10184
10185/// Most refused scope records named individually in the log per sync; the
10186/// `refused` count on the accepted line is always complete.
10187const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10188
10189/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10190#[derive(Debug, Default, PartialEq, Eq)]
10191struct ScopeOutcomeCounts {
10192    created: usize,
10193    replaced: usize,
10194    updated: usize,
10195    unchanged: usize,
10196    refused: usize,
10197}
10198
10199impl ScopeOutcomeCounts {
10200    fn of(results: &[ScopeRecordResult]) -> Self {
10201        let mut counts = Self::default();
10202        for result in results {
10203            let slot = match result.outcome {
10204                ScopeRecordOutcome::Created => &mut counts.created,
10205                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10206                ScopeRecordOutcome::Updated => &mut counts.updated,
10207                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10208                ScopeRecordOutcome::Refused => &mut counts.refused,
10209            };
10210            *slot += 1;
10211        }
10212        counts
10213    }
10214}
10215
10216#[cfg(test)]
10217mod scope_outcome_count_tests {
10218    use super::*;
10219
10220    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10221        ScopeRecordResult {
10222            scope_ref: "r".to_string(),
10223            scope_epoch: 1,
10224            outcome,
10225            code: None,
10226            message: None,
10227            version: None,
10228            parent_state: None,
10229        }
10230    }
10231
10232    /// Each outcome lands in its own count, so a refused record can never be
10233    /// hidden inside the total the log already printed.
10234    #[test]
10235    fn every_outcome_is_counted_in_its_own_field() {
10236        let results = [
10237            result(ScopeRecordOutcome::Created),
10238            result(ScopeRecordOutcome::Created),
10239            result(ScopeRecordOutcome::Replaced),
10240            result(ScopeRecordOutcome::Updated),
10241            result(ScopeRecordOutcome::Unchanged),
10242            result(ScopeRecordOutcome::Refused),
10243            result(ScopeRecordOutcome::Refused),
10244            result(ScopeRecordOutcome::Refused),
10245        ];
10246        assert_eq!(
10247            ScopeOutcomeCounts::of(&results),
10248            ScopeOutcomeCounts {
10249                created: 2,
10250                replaced: 1,
10251                updated: 1,
10252                unchanged: 1,
10253                refused: 3,
10254            }
10255        );
10256    }
10257}
10258
10259/// Return whether a catalog change can create a newly violating live route.
10260/// Removing an attested claim is intentionally excluded: it makes fewer routes
10261/// forbidden and therefore must leave the existing route census untouched.
10262fn capability_census_trigger(
10263    old: Option<&CapabilityDeclarations>,
10264    new: Option<&CapabilityDeclarations>,
10265) -> bool {
10266    let old_provides = old
10267        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10268        .unwrap_or_default();
10269    let old_denies = old
10270        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10271        .unwrap_or_default();
10272    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10273        provides: Vec::new(),
10274        requires: Vec::new(),
10275        must_never_reach: Vec::new(),
10276    });
10277
10278    new.provides
10279        .iter()
10280        .any(|capability| !old_provides.contains(capability))
10281        || new
10282            .must_never_reach
10283            .iter()
10284            .any(|capability| !old_denies.contains(capability))
10285}
10286
10287fn catalog_update_frozen_field_message(
10288    registered: &ModuleManifest,
10289    provides: &[ProviderRole],
10290) -> Option<String> {
10291    let old_has_provides = !registered.provides.is_empty();
10292    let new_has_provides = !provides.is_empty();
10293    if old_has_provides != new_has_provides {
10294        return Some(format!(
10295            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10296            registered.module_id
10297        ));
10298    }
10299
10300    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10301        return Some(format!(
10302            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10303            registered.module_id
10304        ));
10305    }
10306
10307    let registered_concurrency = manifest_concurrency(registered);
10308    let mut candidate = registered.clone();
10309    candidate.provides = provides.to_vec();
10310    let candidate_concurrency = manifest_concurrency(&candidate);
10311    if candidate_concurrency != registered_concurrency {
10312        return Some(format!(
10313            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10314            registered.module_id, registered_concurrency, candidate_concurrency
10315        ));
10316    }
10317
10318    // control_ops live beside the manifest in the HELLO body, not inside
10319    // ModuleManifest, so a provides-only catalog.update cannot change them.
10320    None
10321}
10322
10323fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10324    manifest.provides.iter().any(is_routable_role)
10325}
10326
10327/// Returns the routable-provider concurrency subc should enforce for this manifest.
10328///
10329/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10330/// InternalService has no role-specific concurrency field, so it retains the
10331/// existing ModuleManaged default for backward compatibility.
10332fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10333    manifest
10334        .provides
10335        .iter()
10336        .find_map(|provider| match provider {
10337            ProviderRole::ToolProvider { concurrency, .. }
10338            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10339            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10340        })
10341        .unwrap_or(Concurrency::ModuleManaged)
10342}
10343
10344/// True when the manifest carries a ManagementSurface role whose concurrency
10345/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10346/// bytes because the typed manifest deliberately erases that distinction: the
10347/// default exists for wire compatibility, and this probe exists so the default
10348/// stays observable. Any parse irregularity returns false -- the caller only
10349/// logs, and a malformed body already failed registration upstream.
10350fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10351    let has_management_surface = manifest
10352        .provides
10353        .iter()
10354        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10355    if !has_management_surface {
10356        return false;
10357    }
10358    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10359        return false;
10360    };
10361    let Some(provides) = raw
10362        .get("manifest")
10363        .and_then(|manifest| manifest.get("provides"))
10364        .and_then(serde_json::Value::as_array)
10365    else {
10366        return false;
10367    };
10368    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10369    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10370    // against the management_surface_manifest_without_concurrency golden, not
10371    // recalled (the externally-tagged guess was this function's first bug).
10372    provides.iter().any(|role| {
10373        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10374            && role.get("concurrency").is_none()
10375    })
10376}
10377
10378fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10379    if peer_version != PROTOCOL_VERSION {
10380        return Err(format!(
10381            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10382        ));
10383    }
10384    Ok(PROTOCOL_VERSION)
10385}
10386
10387fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10388    Frame::build_with_version(
10389        response_version(frame),
10390        FrameType::Pong,
10391        frame.header.flags,
10392        0,
10393        0,
10394        frame.header.corr,
10395        Vec::new(),
10396    )
10397    .map_err(RouterError::FrameBuild)
10398}
10399
10400pub(crate) fn control_error_frame(
10401    frame: &Frame,
10402    code: &'static str,
10403    message: impl Into<String>,
10404) -> Result<Frame, RouterError> {
10405    control_error_body_frame(
10406        frame,
10407        ErrorBody {
10408            code: code.to_string(),
10409            message: message.into(),
10410            detail: None,
10411        },
10412    )
10413}
10414
10415/// A channel-0 ERROR for a refusal the daemon decided itself: every
10416/// route.open refusal, the drain `module_reloading` and scope-change/end
10417/// bodies, spawn-subscription and supervisor refusals. Carries the
10418/// daemon-origin bit, which is what lets a client treat `module_reloading`
10419/// as proof that its request never reached a module. Response, push,
10420/// goodbye and relay-request frames keep the plain control flags in their
10421/// own builders.
10422pub(crate) fn control_error_body_frame(
10423    frame: &Frame,
10424    error: ErrorBody,
10425) -> Result<Frame, RouterError> {
10426    control_error_frame_with_flags(frame, error, daemon_error_flags())
10427}
10428
10429/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10430/// refused route.bind answered as a route.open refusal, or a refused
10431/// module-control RPC. Plain control flags — the code and message are
10432/// module-chosen, so the frame must not claim daemon authorship, even when
10433/// the module picks a daemon code like `module_reloading`.
10434fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10435    control_error_frame_with_flags(frame, error, control_flags())
10436}
10437
10438fn control_error_frame_with_flags(
10439    frame: &Frame,
10440    error: ErrorBody,
10441    flags: Flags,
10442) -> Result<Frame, RouterError> {
10443    let body = serde_json::to_vec(&error).map_err(|err| {
10444        RouterError::backend(
10445            0,
10446            frame.header.corr,
10447            format!("failed to encode control ERROR: {err}"),
10448        )
10449    })?;
10450
10451    Frame::build_with_version(
10452        response_version(frame),
10453        FrameType::Error,
10454        flags,
10455        0,
10456        0,
10457        frame.header.corr,
10458        body,
10459    )
10460    .map_err(RouterError::FrameBuild)
10461}
10462
10463pub(crate) fn control_response_body_frame<T: Serialize>(
10464    frame: &Frame,
10465    reply: &T,
10466    label: &'static str,
10467) -> Result<Frame, RouterError> {
10468    let body = serde_json::to_vec(reply).map_err(|err| {
10469        RouterError::backend(
10470            0,
10471            frame.header.corr,
10472            format!("failed to encode {label}: {err}"),
10473        )
10474    })?;
10475
10476    Frame::build_with_version(
10477        response_version(frame),
10478        FrameType::Response,
10479        control_flags(),
10480        0,
10481        0,
10482        frame.header.corr,
10483        body,
10484    )
10485    .map_err(RouterError::FrameBuild)
10486}
10487
10488/// Map a forwarding failure to the wire code a client sees.
10489///
10490/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10491/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10492/// chosen here decides whether a caller retries or gives up.
10493///
10494/// That makes attribution the load-bearing property, not merely having a code. A
10495/// permanent fault published as a retryable one produces a fleet-wide retry storm
10496/// against something that can never recover; a transient fault published as
10497/// permanent gives up on work that would have succeeded. Both look correct in a
10498/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10499/// the mapping per variant rather than merely asserting that some code exists.
10500///
10501/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10502/// two codes on the same side of the boundary passes it. Measured rather than
10503/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10504/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10505/// a test named for something else that happens to assert the string.
10506///
10507/// That accidental coverage is deliberately left alone rather than promoted to a
10508/// named test, because it guards a property this function does not promise.
10509/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10510/// specific code within a class, so identity is free to change and only the
10511/// partition is a contract. Splitting it out would assert a guarantee nothing
10512/// depends on — and a suite that promises more than the code does is the harder
10513/// thing to correct later, because the next reader cannot tell which assertions
10514/// are load-bearing.
10515///
10516/// Pin identity here the moment a consumer branches on a specific code.
10517/// The spawn a HELLO would register as and the provider declarations it
10518/// requests, carried from the HELLO's checks to the point the registry
10519/// accepts it.
10520struct HelloAuthority {
10521    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10522    requested: ProviderDeclarations,
10523    /// Whether admitting this HELLO froze the spawn's requested declarations,
10524    /// so a refusal after admission undoes that freeze and no other.
10525    froze: std::sync::atomic::AtomicBool,
10526}
10527
10528fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10529    match err {
10530        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10531        ForwardingError::NoModuleConnection => "target_unavailable",
10532        ForwardingError::ModuleReloading { .. } => "module_reloading",
10533        ForwardingError::ClientRouteChannelExhausted { .. }
10534        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10535        ForwardingError::StaleModuleEndpoint
10536        | ForwardingError::UnknownReservation { .. }
10537        | ForwardingError::ConnectionClosing { .. }
10538        | ForwardingError::ClientEgressClosed { .. }
10539        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10540        // Only a swap candidate's registration can produce this, and it means
10541        // exactly what a second active HELLO for a live id means.
10542        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10543        ForwardingError::RelayCorrelationExhausted
10544        | ForwardingError::RouteOpenBuild(_)
10545        | ForwardingError::Poisoned => "forwarding_error",
10546    }
10547}
10548
10549fn response_version(frame: &Frame) -> u8 {
10550    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10551        frame.header.ver
10552    } else {
10553        PROTOCOL_VERSION
10554    }
10555}
10556
10557pub(crate) fn control_flags() -> Flags {
10558    Flags::new(false, Priority::Passive, false)
10559}
10560
10561/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10562/// channel. The target is the module (a client never saw the route), so this
10563/// takes the module path: delivered late rather than dropped when the module's
10564/// queue is momentarily full, and never closing its connection.
10565fn send_goodbye_target_best_effort(
10566    counters: &DaemonCounters,
10567    target: &GoodbyeTarget,
10568    context: &'static str,
10569) {
10570    let Ok(frame) = Frame::build_with_version(
10571        target.negotiated_ver,
10572        FrameType::Goodbye,
10573        control_flags(),
10574        target.channel,
10575        target.epoch,
10576        0,
10577        Vec::new(),
10578    ) else {
10579        return;
10580    };
10581    crate::forwarding::send_module_route_goodbye(
10582        counters,
10583        &target.sink,
10584        frame,
10585        target.module_id.as_deref(),
10586        context,
10587    );
10588}
10589
10590fn route_close_reason_for_opener(
10591    reason: RouteCloseReason,
10592    accepts_close_reasons: Option<&[String]>,
10593) -> RouteCloseReason {
10594    if reason == RouteCloseReason::AuthorityChanged
10595        && !accepts_close_reasons
10596            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10597    {
10598        // Older readers forbid reopening for unknown reasons. Reload already
10599        // permits reopening and, like an authority change, requires a new bind.
10600        RouteCloseReason::Reload
10601    } else {
10602        reason
10603    }
10604}
10605
10606pub(crate) fn send_route_control_pushes(
10607    forwarding: &ForwardingTable,
10608    routes: Vec<EndpointRoute>,
10609    push: ClientControlPush,
10610) {
10611    let reason = match &push {
10612        ClientControlPush::RouteClosing { reason, .. }
10613        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10614    };
10615    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10616    for route in routes {
10617        let recipient_reason =
10618            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10619        let target = route.goodbye_target;
10620        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10621            existing.connection_id == target.connection_id && *reason == recipient_reason
10622        }) {
10623            debug_assert_eq!(
10624                existing.negotiated_ver, target.negotiated_ver,
10625                "one connection cannot negotiate multiple frame versions"
10626            );
10627            if !channels.contains(&target.channel) {
10628                channels.push(target.channel);
10629            }
10630            continue;
10631        }
10632        let channel = target.channel;
10633        targets.push((target, recipient_reason, vec![channel]));
10634    }
10635    for (target, recipient_reason, mut channels) in targets {
10636        channels.sort_unstable();
10637        let mut push = push.clone();
10638        match &mut push {
10639            ClientControlPush::RouteClosing {
10640                channels: covered,
10641                reason,
10642                ..
10643            }
10644            | ClientControlPush::RouteClosed {
10645                channels: covered,
10646                reason,
10647                ..
10648            } => {
10649                *covered = channels;
10650                *reason = recipient_reason;
10651            }
10652        }
10653        let body = match serde_json::to_vec(&push) {
10654            Ok(body) => body,
10655            Err(err) => {
10656                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10657                continue;
10658            }
10659        };
10660        let frame = match Frame::build_with_version(
10661            target.negotiated_ver,
10662            FrameType::Push,
10663            control_flags(),
10664            0,
10665            0,
10666            0,
10667            body.clone(),
10668        ) {
10669            Ok(frame) => frame,
10670            Err(err) => {
10671                warn!(
10672                    route_channel = target.channel,
10673                    error = %err,
10674                    "failed to build route lifecycle control PUSH frame"
10675                );
10676                continue;
10677            }
10678        };
10679        if let Err(err) = target.sink.try_send(frame) {
10680            if target.close_on_delivery_failure() {
10681                warn!(
10682                    target_connection_id = target.connection_id.get(),
10683                    route_channel = target.channel,
10684                    error = %err,
10685                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10686                );
10687                let _ = forwarding.escalate_client_delivery_failure(
10688                    target.connection_id,
10689                    target.channel,
10690                    target.epoch,
10691                    CloseReason::new(
10692                        "route_lifecycle_push_delivery_failed",
10693                        format!(
10694                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10695                            target.channel
10696                        ),
10697                    ),
10698                    crate::forwarding::UndeliveredFrame {
10699                        module_id: target.module_id.as_deref(),
10700                        sink: &target.sink,
10701                    },
10702                );
10703            }
10704        }
10705    }
10706}
10707
10708#[cfg(test)]
10709mod tests {
10710    include!("control/agent_commands_tests.rs");
10711    include!("control/supervisor_health_vectors_tests.rs");
10712    include!("control/resource_revision_tests.rs");
10713    include!("control/route_open_recovery_tests.rs");
10714    #[tokio::test]
10715    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10716        let registry = Arc::new(Registry::default());
10717        let handler = ControlHandler::new(registry);
10718        assert_eq!(
10719            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10720            None
10721        );
10722        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10723        hello_via_sink(
10724            &handler,
10725            &ctx,
10726            &mut rx,
10727            hello_frame("daemon", PROTOCOL_VERSION, 1),
10728        )
10729        .await;
10730        assert_eq!(
10731            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10732            Some("daemon".into())
10733        );
10734        assert_eq!(
10735            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10736            None
10737        );
10738        assert_eq!(
10739            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10740            None,
10741            "a registered module is not necessarily supervised"
10742        );
10743        assert_eq!(
10744            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10745            None,
10746            "aggregate provenance has no single target"
10747        );
10748        assert_eq!(
10749            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10750            None
10751        );
10752    }
10753
10754    mod peer_manifest {
10755        include!("peer_manifest_tests.rs");
10756    }
10757    mod catalog_declarations {
10758        include!("control/catalog_tests.rs");
10759    }
10760    mod activity_read {
10761        include!("activity_read_tests.rs");
10762    }
10763
10764    mod lifecycle_activity {
10765        include!("control_lifecycle_tests.rs");
10766    }
10767    #[cfg(unix)]
10768    #[tokio::test]
10769    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10770        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10771        let path = dir.join("subc.jsonc");
10772        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10773            "program":"/bin/sleep","args":["60"],"protocol":"none",
10774            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10775        }}}).to_string()).unwrap();
10776        let mut configured = crate::daemon_config::load(&path)
10777            .unwrap()
10778            .unwrap()
10779            .modules
10780            .pop()
10781            .unwrap();
10782        let registry = std::sync::Arc::new(crate::Registry::default());
10783        let handle = crate::SupervisorHandle::new();
10784        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10785            .with_handle(handle.clone());
10786        let module = supervisor
10787            .supervise_configured_with_health(
10788                configured.module_spec(),
10789                true,
10790                configured.health.clone(),
10791                None,
10792                configured.restart,
10793            )
10794            .unwrap();
10795        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10796        let before = module.status().unwrap().pid;
10797        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10798        configured.health.cadence = std::time::Duration::from_secs(3600);
10799        let health_only = handler
10800            .reconcile_supervised_modules(
10801                &supervisor,
10802                vec![configured.clone()],
10803                false,
10804                Principal::Direct,
10805            )
10806            .await
10807            .unwrap();
10808        assert!(
10809            health_only.0.changed_pending_reload.is_empty(),
10810            "health policy is already applied live"
10811        );
10812        assert_eq!(module.status().unwrap().pid, before);
10813        assert_eq!(
10814            module.configuration().unwrap().1.http,
10815            configured.health.http
10816        );
10817        configured.args = vec!["61".into()];
10818        let launch = handler
10819            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10820            .await
10821            .unwrap();
10822        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10823        assert_eq!(
10824            module.status().unwrap().pid,
10825            before,
10826            "a launch edit is stored until reload"
10827        );
10828        module.drain().await.unwrap();
10829    }
10830    use cortexkit_test_support::ScratchDir;
10831    use std::{
10832        collections::BTreeMap,
10833        fmt,
10834        path::PathBuf,
10835        sync::{Arc, Mutex},
10836        time::Duration,
10837    };
10838
10839    use serde_json::{json, Value};
10840    use subc_protocol::{
10841        manifest::{
10842            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10843            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10844        },
10845        session::HealthStatus,
10846        FrameType,
10847    };
10848
10849    use super::*;
10850    use crate::{
10851        forwarding::{DataRoute, DataRouteState},
10852        registry::ChannelState,
10853        router::FrameSink,
10854        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10855        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10856        RouteCtx, Router,
10857    };
10858    use tokio::{
10859        sync::mpsc,
10860        time::{sleep, Instant},
10861    };
10862    use tracing::{
10863        field::{Field, Visit},
10864        Event, Subscriber,
10865    };
10866    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10867
10868    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10869    ///
10870    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10871    /// is only populated for `tests/*.rs` integration test binaries -- this file
10872    /// compiles as part of the library target, which gets neither. The binary
10873    /// lives in the profile folder this test was built into,
10874    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10875    /// from the test's own path.
10876    ///
10877    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10878    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10879    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10880    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10881    /// `NotFound`, which reads as a broken test rather than an unbuilt
10882    /// dependency -- so state the cause and the remedy instead. Deliberately a
10883    /// panic and not a silent skip: a test that quietly passes when it could not
10884    /// run is worse than one that fails, because it reports health it never
10885    /// verified.
10886    fn fake_aft_stub_path() -> PathBuf {
10887        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10888        assert!(
10889            path.exists(),
10890            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10891             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10892            path.display()
10893        );
10894        path
10895    }
10896
10897    /// Whether clients retry `code` in place: the predicate itself, never a copy
10898    /// of its set. A copied list breaks silently when a code is added to or
10899    /// removed from the real one, and a stale copy here would let exactly the
10900    /// failure this test exists to catch pass.
10901    fn client_retries(code: &str) -> bool {
10902        subc_protocol::error_codes::is_retryable_route_open(code)
10903    }
10904
10905    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10906    /// of failure is worse than publishing none. A permanent fault dressed as
10907    /// retryable makes every client in the fleet retry forever against something
10908    /// that cannot recover; a transient fault dressed as permanent abandons work
10909    /// that would have succeeded.
10910    ///
10911    /// Asserting "a code exists" cannot catch either, because the string is free
10912    /// to say anything. This enumerates every variant and pins which side of the
10913    /// retry boundary it lands on, so a new variant must be classified here
10914    /// deliberately rather than inheriting whichever arm it was appended to.
10915    #[test]
10916    fn retryability_of_forwarding_codes_matches_the_failure() {
10917        // Transient by nature: the target is booting, reloading, or its endpoint
10918        // was swapped mid-flight. Retrying is how these resolve.
10919        let transient = [
10920            ForwardingError::NoModuleConnection,
10921            ForwardingError::ModuleReloading {
10922                module_id: "m".into(),
10923            },
10924            ForwardingError::StaleModuleEndpoint,
10925            ForwardingError::UnknownReservation {
10926                client_channel: 1,
10927                module_channel: 1,
10928            },
10929            ForwardingError::ConnectionClosing {
10930                connection_id: ConnectionId::new(1),
10931            },
10932            ForwardingError::ClientEgressClosed {
10933                connection_id: ConnectionId::new(1),
10934            },
10935            ForwardingError::ModuleEgressUnavailable {
10936                connection_id: ConnectionId::new(1),
10937            },
10938        ];
10939        for err in transient {
10940            let code = forwarding_error_code(&err);
10941            assert!(
10942                client_retries(code),
10943                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10944            );
10945        }
10946
10947        // Not fixed by retrying. Channel and correlation exhaustion need the
10948        // caller to close routes, and a poisoned lock is a daemon that cannot
10949        // recover at all — the worst thing to advertise as retryable, since every
10950        // client would storm a daemon that will never answer.
10951        let permanent = [
10952            ForwardingError::ConnectionRoleConflict {
10953                connection_id: ConnectionId::new(1),
10954            },
10955            ForwardingError::ClientRouteChannelExhausted {
10956                connection_id: ConnectionId::new(1),
10957            },
10958            ForwardingError::ModuleRouteChannelExhausted {
10959                endpoint: ModuleEndpointId {
10960                    connection_id: ConnectionId::new(1),
10961                    generation: 1,
10962                },
10963            },
10964            ForwardingError::RelayCorrelationExhausted,
10965            ForwardingError::RouteOpenBuild("x".into()),
10966            ForwardingError::Poisoned,
10967        ];
10968        for err in permanent {
10969            let code = forwarding_error_code(&err);
10970            assert!(
10971                !client_retries(code),
10972                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10973            );
10974        }
10975    }
10976
10977    /// The principal is the daemon's answer to "who is calling", and modules
10978    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10979    /// plexus gates connector invocation. So a stamp is an authorization input in
10980    /// another process, not a label — and both possible answers SUCCEED, which is
10981    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10982    /// first-party capability to something that never proved it; a supervised one
10983    /// stamped `Direct` silently strips a module of capability it is entitled to.
10984    ///
10985    /// Neither shows up in a test that only checks the bind succeeded. Before this
10986    /// test the only coverage was accidental —
10987    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
10988    /// stamped principal on its way past, so narrowing that wire-shape test to its
10989    /// stated subject would have deleted the last assertion on this value. It
10990    /// still asserts the stamp, which is now redundancy rather than the only
10991    /// guard: both fail under the same mutation, and this one names the reason.
10992    /// SCOPE: this handler's supervisor has spawned nothing, so
10993    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
10994    /// is unreachable here. Both assertions below are refusals, and a mutant that
10995    /// refuses everything would satisfy them.
10996    ///
10997    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
10998    /// spawns a supervised consumer, reads its live nonce, and asserts the module
10999    /// observed `principal.kind == "reserved"` carrying that module_id — verified
11000    /// at source rather than assumed, since a citation is a claim about another
11001    /// file and ages like one. Recorded because a harness that structurally
11002    /// cannot reach an arm reports "none" for that arm identically to one that
11003    /// covers it and found nothing.
11004    #[tokio::test]
11005    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
11006        let handler = ControlHandler::default();
11007        let frame =
11008            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
11009
11010        // Absent consumer_identity is the ordinary case: a human at a terminal, or
11011        // any process holding the connection file. Nothing was proved, so nothing
11012        // may be granted beyond the unattested floor.
11013        let stamped = handler
11014            .route_open_principal(ConnectionId::new(1), &frame, None)
11015            .unwrap()
11016            .unwrap();
11017        assert_eq!(
11018            stamped,
11019            Principal::Direct,
11020            "a caller that proved nothing must not be stamped as a supervised module"
11021        );
11022
11023        // A claimed module_id with a nonce no supervised child was given is a
11024        // forgery attempt, not a weaker caller: it must be REFUSED rather than
11025        // quietly demoted to Direct, or an impersonation attempt looks identical
11026        // to an ordinary unattested connection.
11027        let forged = handler
11028            .route_open_principal(
11029                ConnectionId::new(1),
11030                &frame,
11031                Some(ConsumerIdentity {
11032                    module_id: "aft".to_string(),
11033                    launch_nonce: "not-a-real-nonce".to_string(),
11034                }),
11035            )
11036            .unwrap();
11037        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
11038        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
11039    }
11040
11041    /// The test above hands `route_open_principal` an identity it built itself,
11042    /// which proves the stamping rule and nothing about where the identity comes
11043    /// from. The real producer is a wire body, and the two are joined by a serde
11044    /// field name that nothing else asserts.
11045    ///
11046    /// That join fails quietly in one specific way: an unrecognised key is simply
11047    /// absent after parsing, so a renamed or misspelled `consumer_identity`
11048    /// yields `None` and every supervised module silently drops to `Direct`.
11049    /// Capability-wise that is the safe direction, but it surfaces far from its
11050    /// cause — as a module mysteriously refused bash — and it would pass every
11051    /// test that builds its own input.
11052    ///
11053    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
11054    /// would break every client the moment the daemon gains a field, trading a
11055    /// quiet demotion for a hard refusal on additive change. Asserting the join
11056    /// instead means a rename breaks a test here rather than the fleet.
11057    #[test]
11058    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
11059        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"}}"#;
11060        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
11061        let ClientControlRequest::RouteOpen {
11062            consumer_identity, ..
11063        } = parsed
11064        else {
11065            panic!("route.open body must parse as RouteOpen");
11066        };
11067        assert_eq!(
11068            consumer_identity,
11069            Some(ConsumerIdentity {
11070                module_id: "aft".to_string(),
11071                launch_nonce: "n".to_string(),
11072            }),
11073            "the wire field name must reach the value route_open_principal reads"
11074        );
11075    }
11076
11077    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
11078        ModuleManifest::builder(module_id, "0.1.0")
11079            .protocol_ver(protocol_ver)
11080            .provides(vec![ProviderRole::ToolProvider {
11081                tools: vec![Tool {
11082                    name: "read".to_string(),
11083                    description: None,
11084                    execution_mode: ExecutionMode::Pure,
11085                    schema: json!({"type": "object"}),
11086                }],
11087                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
11088                concurrency: Concurrency::ModuleManaged,
11089                emits_push: true,
11090                sub_supervises: true,
11091            }])
11092            .build()
11093    }
11094
11095    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11096        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11097    }
11098
11099    fn hello_frame_with_control_ops(
11100        module_id: &str,
11101        protocol_ver: u8,
11102        corr: u64,
11103        control_ops: Option<Vec<String>>,
11104    ) -> Frame {
11105        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11106    }
11107
11108    fn hello_frame_with_nonce(
11109        module_id: &str,
11110        protocol_ver: u8,
11111        corr: u64,
11112        launch_nonce: Option<&str>,
11113    ) -> Frame {
11114        hello_frame_full(
11115            module_id,
11116            protocol_ver,
11117            corr,
11118            None,
11119            launch_nonce.map(ToOwned::to_owned),
11120        )
11121    }
11122
11123    fn hello_frame_full(
11124        module_id: &str,
11125        protocol_ver: u8,
11126        corr: u64,
11127        control_ops: Option<Vec<String>>,
11128        launch_nonce: Option<String>,
11129    ) -> Frame {
11130        let body = serde_json::to_vec(&ModuleHelloBody {
11131            manifest: manifest(module_id, protocol_ver),
11132            protocol_ver,
11133            control_ops,
11134            launch_nonce,
11135        })
11136        .unwrap();
11137        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11138    }
11139
11140    fn hello_frame_with_rich_ui(
11141        module_id: &str,
11142        protocol_ver: u8,
11143        corr: u64,
11144        launch_nonce: Option<&str>,
11145        rich_ui: Value,
11146    ) -> Frame {
11147        let mut body = serde_json::to_value(ModuleHelloBody {
11148            manifest: manifest(module_id, protocol_ver),
11149            protocol_ver,
11150            control_ops: None,
11151            launch_nonce: launch_nonce.map(str::to_string),
11152        })
11153        .unwrap();
11154        body["manifest"]["rich_ui"] = rich_ui;
11155        Frame::build(
11156            FrameType::Hello,
11157            control_flags(),
11158            0,
11159            0,
11160            corr,
11161            serde_json::to_vec(&body).unwrap(),
11162        )
11163        .unwrap()
11164    }
11165
11166    fn non_routable_hello_frame_with_control_ops(
11167        module_id: &str,
11168        corr: u64,
11169        control_ops: Option<Vec<String>>,
11170    ) -> Frame {
11171        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11172        manifest.provides.clear();
11173        let body = serde_json::to_vec(&ModuleHelloBody {
11174            manifest,
11175            protocol_ver: PROTOCOL_VERSION,
11176            control_ops,
11177            launch_nonce: None,
11178        })
11179        .unwrap();
11180        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11181    }
11182
11183    fn capability_grammar_hello_frame(
11184        capabilities: Value,
11185        runtime_computed: Option<Value>,
11186        corr: u64,
11187    ) -> Frame {
11188        let mut body = serde_json::to_value(ModuleHelloBody {
11189            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11190            protocol_ver: PROTOCOL_VERSION,
11191            control_ops: None,
11192            launch_nonce: None,
11193        })
11194        .expect("HELLO body serializes");
11195        body["manifest"]["capabilities"] = capabilities;
11196        if let Some(runtime_computed) = runtime_computed {
11197            body["runtime_computed"] = runtime_computed;
11198        }
11199        Frame::build(
11200            FrameType::Hello,
11201            control_flags(),
11202            0,
11203            0,
11204            corr,
11205            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11206        )
11207        .expect("HELLO frame builds")
11208    }
11209
11210    fn channel_request(channel: u16, corr: u64) -> Frame {
11211        Frame::build(
11212            FrameType::Request,
11213            Flags::new(true, Priority::Interactive, false),
11214            channel,
11215            0,
11216            corr,
11217            b"opaque".to_vec(),
11218        )
11219        .unwrap()
11220    }
11221
11222    fn route_ctx(
11223        connection_id: ConnectionId,
11224    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11225        let (tx, rx) = mpsc::channel(8);
11226        (
11227            RouteCtx {
11228                connection_id,
11229                egress: FrameSink::new(tx),
11230            },
11231            rx,
11232        )
11233    }
11234
11235    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11236        serde_json::from_slice(&frame.body).unwrap()
11237    }
11238
11239    /// Register a module over a connection that has a sink and return the
11240    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11241    /// module's own sink rather than returning it as a reply, so the ack is
11242    /// taken off `rx` here and whatever the test reads next is what followed it.
11243    async fn hello_via_sink(
11244        handler: &ControlHandler,
11245        ctx: &RouteCtx,
11246        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11247        hello: Frame,
11248    ) -> Frame {
11249        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11250        assert!(
11251            replies.is_empty(),
11252            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11253        );
11254        let ack = rx
11255            .try_recv()
11256            .expect("HELLO_ACK is queued on the module sink")
11257            .frame;
11258        assert_eq!(ack.header.ty, FrameType::HelloAck);
11259        ack
11260    }
11261
11262    fn parse_error(frame: &Frame) -> Value {
11263        serde_json::from_slice(&frame.body).unwrap()
11264    }
11265
11266    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11267        serde_json::from_slice(&frame.body).unwrap()
11268    }
11269
11270    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11271        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11272            route_channel,
11273            route_epoch: 0,
11274            kind,
11275        })
11276        .unwrap();
11277        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11278    }
11279
11280    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11281        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11282            module_id: module_id.to_string(),
11283        })
11284        .unwrap();
11285        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11286    }
11287
11288    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11289        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11290    }
11291
11292    // Exercise retired opener fields without putting them back in BindIdentity.
11293    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11294        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11295        let mut frame = route_open_frame(corr, module_id, root);
11296        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11297        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11298        frame.body = serde_json::to_vec(&body).unwrap();
11299        frame
11300    }
11301
11302    fn route_open_frame_with_consumer_capabilities(
11303        corr: u64,
11304        module_id: &str,
11305        _project_root: ScratchDir,
11306        consumer_capabilities: Option<Vec<String>>,
11307    ) -> Frame {
11308        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11309            busy_refusals: None,
11310            target: RouteTarget::ToolProvider {
11311                module_id: module_id.to_string(),
11312            },
11313            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11314            consumer_identity: None,
11315            consumer_capabilities,
11316            role_versions: None,
11317            admission_facts: None,
11318            scope: None,
11319        })
11320        .unwrap();
11321        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11322    }
11323
11324    fn route_open_frame_with_role_versions(
11325        corr: u64,
11326        module_id: &str,
11327        _project_root: ScratchDir,
11328        role_versions: Option<BTreeMap<String, String>>,
11329    ) -> Frame {
11330        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11331            busy_refusals: None,
11332            target: RouteTarget::ToolProvider {
11333                module_id: module_id.to_string(),
11334            },
11335            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11336            consumer_identity: None,
11337            consumer_capabilities: None,
11338            role_versions,
11339            admission_facts: None,
11340            scope: None,
11341        })
11342        .unwrap();
11343        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11344    }
11345
11346    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11347        entries
11348            .iter()
11349            .map(|(role, version)| (role.to_string(), version.to_string()))
11350            .collect()
11351    }
11352
11353    fn route_open_frame_with_admission_facts(
11354        corr: u64,
11355        module_id: &str,
11356        _project_root: ScratchDir,
11357        consumer_identity: Option<subc_control::ConsumerIdentity>,
11358        facts: Option<Value>,
11359    ) -> Frame {
11360        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11361            busy_refusals: None,
11362            target: RouteTarget::ToolProvider {
11363                module_id: module_id.to_string(),
11364            },
11365            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11366            consumer_identity,
11367            consumer_capabilities: None,
11368            role_versions: None,
11369            admission_facts: facts,
11370            scope: None,
11371        })
11372        .unwrap();
11373        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11374    }
11375
11376    #[derive(Clone, Default)]
11377    struct EventCapture {
11378        events: Arc<Mutex<Vec<CapturedEvent>>>,
11379    }
11380
11381    #[derive(Clone, Debug)]
11382    struct CapturedEvent {
11383        target: String,
11384        level: tracing::Level,
11385        fields: BTreeMap<String, String>,
11386    }
11387
11388    impl EventCapture {
11389        fn events(&self) -> Vec<CapturedEvent> {
11390            self.events.lock().unwrap().clone()
11391        }
11392    }
11393
11394    impl<S> Layer<S> for EventCapture
11395    where
11396        S: Subscriber,
11397    {
11398        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11399            let mut visitor = EventFieldVisitor::default();
11400            event.record(&mut visitor);
11401            self.events.lock().unwrap().push(CapturedEvent {
11402                target: event.metadata().target().to_string(),
11403                level: *event.metadata().level(),
11404                fields: visitor.fields,
11405            });
11406        }
11407    }
11408
11409    #[derive(Default)]
11410    struct EventFieldVisitor {
11411        fields: BTreeMap<String, String>,
11412    }
11413
11414    impl Visit for EventFieldVisitor {
11415        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11416            self.fields
11417                .insert(field.name().to_string(), format!("{value:?}"));
11418        }
11419    }
11420
11421    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11422        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11423            status,
11424            detail: Some("warming".to_string()),
11425            metrics: Some(json!({"queue_depth": 3})),
11426        })
11427        .unwrap();
11428        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11429    }
11430
11431    fn route_bind_ack(corr: u64) -> Frame {
11432        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11433        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11434    }
11435
11436    fn unique_project_root(label: &str) -> ScratchDir {
11437        ScratchDir::new(label)
11438    }
11439
11440    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11441        match parse_route_poll(frame) {
11442            ClientControlResponse::RoutePoll {
11443                status: None,
11444                live: Some(live),
11445                ..
11446            } => assert_eq!(live, expected_live),
11447            other => panic!("unexpected route.poll response: {other:?}"),
11448        }
11449    }
11450
11451    fn bind_liveness_route(
11452        registry: &Registry,
11453        forwarding: &ForwardingTable,
11454        module_id: &str,
11455    ) -> (RouteCtx, u16, u32) {
11456        let module_connection = ConnectionId::new(101);
11457        let client_connection = ConnectionId::new(202);
11458        let registration = registry
11459            .register_with_control_ops(
11460                manifest(module_id, PROTOCOL_VERSION),
11461                PROTOCOL_VERSION,
11462                module_connection,
11463                module_baseline_control_ops(),
11464            )
11465            .unwrap();
11466        let (module_tx, _module_rx) = mpsc::channel(8);
11467        let endpoint = forwarding
11468            .register_module_connection(
11469                module_connection,
11470                module_id.to_string(),
11471                PROTOCOL_VERSION,
11472                manifest_concurrency(&registration.manifest),
11473                FrameSink::new(module_tx),
11474            )
11475            .unwrap();
11476        let (client_ctx, _client_rx) = route_ctx(client_connection);
11477        let pending = forwarding
11478            .begin_route_bind_relay_for_test(
11479                client_connection,
11480                client_ctx.egress.clone(),
11481                1,
11482                module_id,
11483            )
11484            .unwrap();
11485        assert_eq!(pending.endpoint, endpoint);
11486        let route_channel = pending.client_channel;
11487        let route_epoch = pending.client_epoch;
11488        forwarding
11489            .complete_pending_relay(
11490                module_connection,
11491                pending.corr,
11492                RouteBindRelayOutcome::Accepted,
11493            )
11494            .unwrap();
11495        (client_ctx, route_channel, route_epoch)
11496    }
11497
11498    struct FakeProcessLiveness {
11499        live: Option<bool>,
11500    }
11501
11502    impl ModuleProcessLiveness for FakeProcessLiveness {
11503        fn process_live(&self, _module_id: &str) -> Option<bool> {
11504            self.live
11505        }
11506    }
11507
11508    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11509    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11510    {
11511        let registry = Arc::new(Registry::default());
11512        let supervisor_handle = SupervisorHandle::new();
11513        let supervisor = Supervisor::new_for_test(
11514            Arc::clone(&registry),
11515            RestartPolicy::new(1, Duration::from_millis(10)),
11516        )
11517        .with_handle(supervisor_handle.clone());
11518        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11519        let module = supervisor
11520            .spawn(ModuleSpec {
11521                script: None,
11522                carry_containment: false,
11523                module_id: "stderr-tail-wire".to_string(),
11524                program: fake_aft_stub_path(),
11525                args: Vec::new(),
11526                env: vec![
11527                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11528                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11529                ],
11530                reserved: false,
11531                reserved_prefixes: Vec::new(),
11532                protocol: ModuleProtocol::Subc,
11533                overlap: Default::default(),
11534            })
11535            .unwrap();
11536
11537        let deadline = Instant::now() + Duration::from_secs(5);
11538        loop {
11539            let tail = module.stderr_tail(None, None);
11540            if tail
11541                .entries
11542                .iter()
11543                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11544                && tail.entries.iter().any(|entry| {
11545                    matches!(
11546                        entry,
11547                        TailEntry::Line {
11548                            truncated: true,
11549                            ..
11550                        }
11551                    )
11552                })
11553            {
11554                break;
11555            }
11556            assert!(
11557                Instant::now() < deadline,
11558                "module did not produce a truncated line and restart boundary: {tail:?}"
11559            );
11560            sleep(Duration::from_millis(10)).await;
11561        }
11562
11563        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11564        let request = ClientControlRequest::SupervisorStderrTail {
11565            module_id: "stderr-tail-wire".to_string(),
11566            max_lines: None,
11567            max_bytes: None,
11568        };
11569        let frame = Frame::build(
11570            FrameType::Request,
11571            control_flags(),
11572            0,
11573            0,
11574            1,
11575            serde_json::to_vec(&request).unwrap(),
11576        )
11577        .unwrap();
11578        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11579        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11580        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11581            serde_json::from_slice(&responses[0].body).unwrap()
11582        else {
11583            panic!("expected supervisor.stderr_tail response");
11584        };
11585
11586        assert!(
11587            tail.entries
11588                .iter()
11589                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11590            "the control response lost the restart boundary"
11591        );
11592        let Some(StderrTailEntry::Line {
11593            text,
11594            truncated,
11595            at_ms,
11596        }) = tail.entries.iter().find(|entry| {
11597            matches!(
11598                entry,
11599                StderrTailEntry::Line {
11600                    truncated: true,
11601                    ..
11602                }
11603            )
11604        })
11605        else {
11606            panic!("the control response lost the truncated line");
11607        };
11608        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11609        assert!(*truncated);
11610        assert!(
11611            at_ms.is_some(),
11612            "the control response lost the line's capture time"
11613        );
11614    }
11615
11616    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11617    /// read done on the worker thread would stall every other task until it
11618    /// finished; the read must run off the worker so this test's own task keeps
11619    /// running while the read is paused.
11620    #[tokio::test(flavor = "current_thread")]
11621    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11622        let dir = ScratchDir::new("terminals-off-worker");
11623        let journal_path = dir.join("terminals.jsonl");
11624        let registry = Arc::new(Registry::default());
11625        let supervisor_handle = SupervisorHandle::new();
11626        let supervisor =
11627            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11628                .with_handle(supervisor_handle.clone())
11629                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11630        let module = supervisor
11631            .spawn(ModuleSpec {
11632                script: None,
11633                carry_containment: false,
11634                module_id: "terminal-off-worker".to_string(),
11635                program: fake_aft_stub_path(),
11636                args: Vec::new(),
11637                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11638                reserved: false,
11639                reserved_prefixes: Vec::new(),
11640                protocol: ModuleProtocol::Subc,
11641                overlap: Default::default(),
11642            })
11643            .unwrap();
11644        let deadline = Instant::now() + Duration::from_secs(5);
11645        while module.terminal_history().entries.len() != 2 {
11646            assert!(Instant::now() < deadline, "module did not record two exits");
11647            sleep(Duration::from_millis(10)).await;
11648        }
11649
11650        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11651        let handler =
11652            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11653        let frame = Frame::build(
11654            FrameType::Request,
11655            control_flags(),
11656            0,
11657            0,
11658            1,
11659            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11660                module_id: "terminal-off-worker".to_string(),
11661            })
11662            .unwrap(),
11663        )
11664        .unwrap();
11665        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11666        let spawned_at = std::time::Instant::now();
11667        let read = tokio::spawn({
11668            let handler = Arc::clone(&handler);
11669            async move { handler.handle_control_frame(&ctx, frame).await }
11670        });
11671        // Waiting for the pause from a blocking thread keeps this task pending,
11672        // so the runtime's single worker is free to run the read task.
11673        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11674            .await
11675            .unwrap()
11676            .expect("the history read reached its pause");
11677        let elapsed = spawned_at.elapsed();
11678        assert!(
11679            elapsed < Duration::from_secs(2) && !read.is_finished(),
11680            "this task could not run while the history read was paused \
11681             (resumed after {elapsed:?}, read finished: {})",
11682            read.is_finished()
11683        );
11684
11685        drop(release);
11686        let responses = read.await.unwrap().unwrap();
11687        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11688        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11689            panic!("expected supervisor.terminals response");
11690        };
11691        assert_eq!(terminals.entries.len(), 2);
11692        assert_eq!(terminals.journal_skipped_lines, 0);
11693        assert_eq!(terminals.journal_read_errors, 0);
11694    }
11695
11696    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11697    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11698        let registry = Arc::new(Registry::default());
11699        let supervisor_handle = SupervisorHandle::new();
11700        let supervisor =
11701            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11702                .with_handle(supervisor_handle.clone());
11703        let module = supervisor
11704            .spawn(ModuleSpec {
11705                script: None,
11706                carry_containment: false,
11707                module_id: "terminal-golden".to_string(),
11708                program: fake_aft_stub_path(),
11709                args: Vec::new(),
11710                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11711                reserved: false,
11712                reserved_prefixes: Vec::new(),
11713                protocol: ModuleProtocol::Subc,
11714                overlap: Default::default(),
11715            })
11716            .unwrap();
11717
11718        let deadline = Instant::now() + Duration::from_secs(5);
11719        while module.terminal_history().entries.len() != 2 {
11720            assert!(
11721                Instant::now() < deadline,
11722                "module did not retain two terminal exits: {:?}",
11723                module.terminal_history()
11724            );
11725            sleep(Duration::from_millis(10)).await;
11726        }
11727
11728        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11729        let request = ClientControlRequest::SupervisorTerminals {
11730            module_id: "terminal-golden".to_string(),
11731        };
11732        let frame = Frame::build(
11733            FrameType::Request,
11734            control_flags(),
11735            0,
11736            0,
11737            1,
11738            serde_json::to_vec(&request).unwrap(),
11739        )
11740        .unwrap();
11741        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11742        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11743        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11744        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11745            panic!("expected supervisor.terminals response");
11746        };
11747        assert_eq!(terminals.entries.len(), 2);
11748        assert_eq!(terminals.dropped, 0);
11749
11750        let mut rendered = serde_json::to_value(response).unwrap();
11751        // Wall-clock fields are the observation contract, but not stable fixture
11752        // bytes; normalize only them after the real handler has shaped the response.
11753        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11754        for (index, entry) in rendered["entries"]
11755            .as_array_mut()
11756            .expect("terminal response entries array")
11757            .iter_mut()
11758            .enumerate()
11759        {
11760            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11761        }
11762
11763        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11764            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11765        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11766        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11767            std::fs::write(&golden_path, &serialized).unwrap();
11768        }
11769        let expected: Value =
11770            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11771        assert_eq!(rendered, expected);
11772    }
11773
11774    #[test]
11775    fn hello_registers_manifest_and_returns_ack() {
11776        let registry = Arc::new(Registry::default());
11777        let handler = ControlHandler::new(Arc::clone(&registry));
11778        let conn = ConnectionId::new(1);
11779
11780        let responses = handler
11781            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11782            .unwrap();
11783
11784        assert_eq!(responses.len(), 1);
11785        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11786        assert_eq!(responses[0].header.channel, 0);
11787        assert_eq!(responses[0].header.corr, 7);
11788        let ack = parse_ack(&responses[0]);
11789        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11790        assert!(ack
11791            .subc_capabilities
11792            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11793        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11794        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11795        assert!(ack
11796            .subc_ops
11797            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11798        assert!(ack
11799            .subc_ops
11800            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11801        assert!(ack
11802            .subc_ops
11803            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11804
11805        let registration = registry.get_module("aft").unwrap().unwrap();
11806        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11807        assert_eq!(registration.state, ChannelState::Active);
11808        assert_eq!(registration.connection_id, conn);
11809        assert_eq!(registration.control_ops, module_baseline_control_ops());
11810        assert!(registration.manifest.display_name.is_none());
11811    }
11812
11813    #[test]
11814    fn hello_display_name_refuses_invalid_manifest_by_field() {
11815        let registry = Arc::new(Registry::default());
11816        let handler = ControlHandler::new(Arc::clone(&registry));
11817        for (index, invalid) in [
11818            json!(""),
11819            json!("a".repeat(41)),
11820            json!(" Routing"),
11821            json!("a\nb"),
11822            json!("a\u{202e}b"),
11823            json!(7),
11824        ]
11825        .into_iter()
11826        .enumerate()
11827        {
11828            let module_id = format!("bad-display-name-{index}");
11829            let mut body = serde_json::to_value(ModuleHelloBody {
11830                manifest: manifest(&module_id, PROTOCOL_VERSION),
11831                protocol_ver: PROTOCOL_VERSION,
11832                control_ops: None,
11833                launch_nonce: None,
11834            })
11835            .unwrap();
11836            body["manifest"]["display_name"] = invalid;
11837            let hello = Frame::build(
11838                FrameType::Hello,
11839                control_flags(),
11840                0,
11841                0,
11842                7,
11843                serde_json::to_vec(&body).unwrap(),
11844            )
11845            .unwrap();
11846            let response = handler
11847                .handle_control(ConnectionId::new(100 + index as u64), hello)
11848                .unwrap();
11849            assert_eq!(response[0].header.ty, FrameType::Error);
11850            let error = parse_error(&response[0]);
11851            assert_eq!(error["code"], "invalid_manifest");
11852            assert!(error["message"].as_str().unwrap().contains("display_name"));
11853            assert!(registry.get_module(&module_id).unwrap().is_none());
11854        }
11855    }
11856
11857    #[test]
11858    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11859        let invalid_identifiers = [
11860            ("case_change", "credentials-Provider/v1"),
11861            ("leading_zero", "credentials-provider/v01"),
11862            ("trailing_hyphen", "credentials-provider-/v1"),
11863            ("consecutive_hyphens", "credentials--provider/v1"),
11864            ("uppercase", "Credentials-provider/v1"),
11865            ("missing_v", "credentials-provider/1"),
11866            ("whitespace", "credentials provider/v1"),
11867            ("zero_version", "credentials-provider/v0"),
11868            ("out_of_range_version", "credentials-provider/v4294967296"),
11869            (
11870                "overlength_name",
11871                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11872            ),
11873        ];
11874        let mut cases = invalid_identifiers
11875            .into_iter()
11876            .map(|(name, identifier)| {
11877                (
11878                    format!("identifier_{name}"),
11879                    "capabilities.provides[0]".to_string(),
11880                    identifier.to_string(),
11881                    json!({ "provides": [identifier] }),
11882                    None,
11883                )
11884            })
11885            .collect::<Vec<_>>();
11886        cases.extend([
11887            (
11888                "unknown_need".to_string(),
11889                "capabilities.requires[0].need".to_string(),
11890                "deferred".to_string(),
11891                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11892                None,
11893            ),
11894            (
11895                "duplicate_provides".to_string(),
11896                "capabilities.provides[1]".to_string(),
11897                "credentials-provider/v1".to_string(),
11898                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11899                None,
11900            ),
11901            (
11902                "duplicate_must_never_reach".to_string(),
11903                "capabilities.must_never_reach[1]".to_string(),
11904                "credentials-provider/v1".to_string(),
11905                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11906                None,
11907            ),
11908            (
11909                "duplicate_requires_same_need".to_string(),
11910                "capabilities.requires[1]".to_string(),
11911                "credentials-provider/v1".to_string(),
11912                json!({ "requires": [
11913                    { "capability": "credentials-provider/v1", "need": "required" },
11914                    { "capability": "credentials-provider/v1", "need": "required" }
11915                ] }),
11916                None,
11917            ),
11918            (
11919                "duplicate_requires_conflicting_need".to_string(),
11920                "capabilities.requires[1]".to_string(),
11921                "credentials-provider/v1".to_string(),
11922                json!({ "requires": [
11923                    { "capability": "credentials-provider/v1", "need": "required" },
11924                    { "capability": "credentials-provider/v1", "need": "optional" }
11925                ] }),
11926                None,
11927            ),
11928            (
11929                "capabilities_root_pointer".to_string(),
11930                "runtime_computed[0]".to_string(),
11931                "/capabilities".to_string(),
11932                json!({}),
11933                Some(json!(["/capabilities"])),
11934            ),
11935            (
11936                "capabilities_descendant_pointer".to_string(),
11937                "runtime_computed[0]".to_string(),
11938                "/capabilities/provides".to_string(),
11939                json!({}),
11940                Some(json!(["/capabilities/provides"])),
11941            ),
11942            (
11943                "malformed_pointer_without_leading_slash".to_string(),
11944                "runtime_computed[0]".to_string(),
11945                "capabilities".to_string(),
11946                json!({}),
11947                Some(json!(["capabilities"])),
11948            ),
11949            (
11950                "malformed_pointer_escape".to_string(),
11951                "runtime_computed[0]".to_string(),
11952                "/roles/~2/tools".to_string(),
11953                json!({}),
11954                Some(json!(["/roles/~2/tools"])),
11955            ),
11956            (
11957                "unknown_capabilities_field".to_string(),
11958                "capabilities.future".to_string(),
11959                "<array>".to_string(),
11960                json!({ "future": [] }),
11961                None,
11962            ),
11963        ]);
11964
11965        for (index, (name, field, value, capabilities, runtime_computed)) in
11966            cases.into_iter().enumerate()
11967        {
11968            let registry = Arc::new(Registry::default());
11969            let handler = ControlHandler::new(Arc::clone(&registry));
11970            let response = handler
11971                .handle_control(
11972                    ConnectionId::new((index + 1) as u64),
11973                    capability_grammar_hello_frame(
11974                        capabilities,
11975                        runtime_computed,
11976                        index as u64 + 1,
11977                    ),
11978                )
11979                .expect("invalid HELLO returns a refusal");
11980
11981            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11982            let error = parse_error(&response[0]);
11983            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11984            let message = error["message"]
11985                .as_str()
11986                .expect("error message is a string");
11987            assert!(
11988                message.contains(&field),
11989                "{name}: field missing from {message}"
11990            );
11991            assert!(
11992                message.contains(&value),
11993                "{name}: value missing from {message}"
11994            );
11995            assert_eq!(
11996                registry
11997                    .active_registration_count()
11998                    .expect("registry reads"),
11999                0,
12000                "{name}: refused HELLO must not create a catalog entry"
12001            );
12002        }
12003    }
12004
12005    #[test]
12006    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
12007        let registry = Arc::new(Registry::default());
12008        let handler = ControlHandler::new(Arc::clone(&registry));
12009        let capabilities = json!({
12010            "provides": ["credentials-provider/v1"],
12011            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
12012            "must_never_reach": ["federation-transport/v1"]
12013        });
12014        let response = handler
12015            .handle_control(
12016                ConnectionId::new(99),
12017                capability_grammar_hello_frame(
12018                    capabilities.clone(),
12019                    Some(json!(["/roles/0/tools"])),
12020                    99,
12021                ),
12022            )
12023            .expect("valid HELLO registers");
12024        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12025
12026        let request = Frame::build(
12027            FrameType::Request,
12028            control_flags(),
12029            0,
12030            0,
12031            100,
12032            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12033                .expect("catalog request serializes"),
12034        )
12035        .expect("catalog request frame builds");
12036        let response = handler
12037            .handle_catalog_list(request, None)
12038            .expect("catalog list succeeds");
12039        let ClientControlResponse::CatalogList { modules, .. } =
12040            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
12041        else {
12042            panic!("catalog request must return catalog.list");
12043        };
12044        assert_eq!(modules.len(), 1);
12045        assert_eq!(
12046            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
12047            capabilities
12048        );
12049    }
12050
12051    #[test]
12052    fn catalog_list_mirrors_management_operation_description() {
12053        let registry = Arc::new(Registry::default());
12054        let handler = ControlHandler::new(Arc::clone(&registry));
12055        let description = "List managed records and return their identifiers and metadata.";
12056        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
12057        manifest.provides = vec![ProviderRole::ManagementSurface {
12058            operations: vec![ManagementOperation {
12059                name: "records.list".to_string(),
12060                kind: ManagementOperationKind::Query,
12061                description: Some(description.to_string()),
12062            }],
12063            config_schema: json!({"type": "object"}),
12064            observability: vec![ObservabilitySurface {
12065                name: "records.stats".to_string(),
12066                kind: ObservabilityKind::Snapshot,
12067            }],
12068            identity_scope: vec![IdentityScope::Project],
12069            concurrency: Concurrency::ModuleManaged,
12070        }];
12071        registry
12072            .register_with_control_ops(
12073                manifest,
12074                PROTOCOL_VERSION,
12075                ConnectionId::new(99),
12076                Vec::new(),
12077            )
12078            .expect("described management manifest registers");
12079
12080        let request = Frame::build(
12081            FrameType::Request,
12082            control_flags(),
12083            0,
12084            0,
12085            100,
12086            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12087                .expect("catalog request serializes"),
12088        )
12089        .expect("catalog request frame builds");
12090        let response = handler
12091            .handle_catalog_list(request, None)
12092            .expect("catalog list succeeds");
12093        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12094        assert_eq!(
12095            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12096            "catalog.list must preserve the declared operation description verbatim"
12097        );
12098    }
12099
12100    #[test]
12101    fn catalog_list_mirrors_registered_operation_delivery() {
12102        let registry = Arc::new(Registry::default());
12103        let handler = ControlHandler::new(Arc::clone(&registry));
12104        let delivery =
12105            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12106        let mut body = serde_json::to_value(ModuleHelloBody {
12107            manifest: manifest("watch-management", PROTOCOL_VERSION),
12108            protocol_ver: PROTOCOL_VERSION,
12109            control_ops: None,
12110            launch_nonce: None,
12111        })
12112        .unwrap();
12113        body["manifest"]["provides"] = json!([{
12114            "role": "management_surface",
12115            "operations": [
12116                {"name": "status", "kind": "query"},
12117                {"name": "future", "kind": "query"},
12118                {"name": "reset", "kind": "mutate"}
12119            ],
12120            "config_schema": {}, "observability": [], "identity_scope": []
12121        }]);
12122        body["manifest"]["operation_delivery"] = delivery.clone();
12123        let hello = Frame::build(
12124            FrameType::Hello,
12125            control_flags(),
12126            0,
12127            0,
12128            99,
12129            serde_json::to_vec(&body).unwrap(),
12130        )
12131        .unwrap();
12132        let response = handler
12133            .handle_control(ConnectionId::new(99), hello)
12134            .unwrap();
12135        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12136
12137        let (_, registrations) = registry.list_modules().unwrap();
12138        let registered = &registrations[0].manifest;
12139        assert!(registered.is_watch_operation("status"));
12140        assert!(!registered.is_watch_operation("future"));
12141        assert!(!registered.is_watch_operation("reset"));
12142        assert!(!registered.is_watch_operation("missing"));
12143
12144        let request = Frame::build(
12145            FrameType::Request,
12146            control_flags(),
12147            0,
12148            0,
12149            100,
12150            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12151        )
12152        .unwrap();
12153        let response = handler.handle_catalog_list(request, None).unwrap();
12154        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12155        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12156        let ClientControlResponse::CatalogList { modules, .. } =
12157            serde_json::from_slice(&response[0].body).unwrap()
12158        else {
12159            panic!("expected catalog.list");
12160        };
12161        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12162    }
12163
12164    #[test]
12165    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12166        let registry = Arc::new(Registry::default());
12167        let supervisor = SupervisorHandle::new();
12168        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12169        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12170        let descriptor = json!({
12171            "schema": "ckios.richui.manifest/1",
12172            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12173            "bytes": 4096,
12174            "chunks": 4
12175        });
12176        let connection = ConnectionId::new(201);
12177        let hello = handler
12178            .handle_control(
12179                connection,
12180                hello_frame_with_rich_ui(
12181                    "vault",
12182                    PROTOCOL_VERSION,
12183                    201,
12184                    Some("the-real-nonce"),
12185                    descriptor.clone(),
12186                ),
12187            )
12188            .unwrap();
12189        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12190
12191        let request =
12192            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12193        let provides = registry
12194            .get_module_by_connection(connection)
12195            .unwrap()
12196            .unwrap()
12197            .manifest
12198            .provides;
12199        handler
12200            .handle_catalog_update(connection, request, provides, None, Some(false))
12201            .unwrap();
12202
12203        let request = Frame::build(
12204            FrameType::Request,
12205            control_flags(),
12206            0,
12207            0,
12208            203,
12209            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12210        )
12211        .unwrap();
12212        let response = handler.handle_catalog_list(request, None).unwrap();
12213        let ClientControlResponse::CatalogList { modules, .. } =
12214            serde_json::from_slice(&response[0].body).unwrap()
12215        else {
12216            panic!("expected catalog.list");
12217        };
12218        assert_eq!(
12219            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12220            descriptor
12221        );
12222        assert!(modules[0].nonce_verified);
12223    }
12224
12225    fn hello_with_role_declarations(declarations: Value) -> Frame {
12226        let mut body = serde_json::to_value(ModuleHelloBody {
12227            manifest: manifest("role-test", PROTOCOL_VERSION),
12228            protocol_ver: PROTOCOL_VERSION,
12229            control_ops: None,
12230            launch_nonce: None,
12231        })
12232        .unwrap();
12233        body["manifest"]["role_declarations"] = declarations;
12234        Frame::build(
12235            FrameType::Hello,
12236            control_flags(),
12237            0,
12238            0,
12239            301,
12240            serde_json::to_vec(&body).unwrap(),
12241        )
12242        .unwrap()
12243    }
12244
12245    fn update_role_declarations_frame(declarations: Value) -> Frame {
12246        Frame::build(
12247            FrameType::Request,
12248            control_flags(),
12249            0,
12250            0,
12251            303,
12252            serde_json::to_vec(&json!({
12253                "op": "catalog.update_role_declarations",
12254                "role_declarations": declarations,
12255            }))
12256            .unwrap(),
12257        )
12258        .unwrap()
12259    }
12260
12261    #[tokio::test]
12262    async fn role_declarations_update_replaces_then_clears_catalog() {
12263        let registry = Arc::new(Registry::default());
12264        let handler = ControlHandler::new(Arc::clone(&registry));
12265        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12266        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12267        hello_via_sink(
12268            &handler,
12269            &ctx,
12270            &mut rx,
12271            hello_with_role_declarations(initial.clone()),
12272        )
12273        .await;
12274        assert_eq!(
12275            role_declarations_catalog(&handler).0["role_declarations"],
12276            initial
12277        );
12278        let before = registry.get_module("role-test").unwrap().unwrap();
12279        for declarations in [
12280            json!({"media-provider/v1": {"engines": ["new"]}}),
12281            json!({}),
12282        ] {
12283            let response = handler
12284                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12285                .await
12286                .unwrap();
12287            assert_eq!(response[0].header.ty, FrameType::Response);
12288            assert_eq!(
12289                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12290                json!({"op": "catalog.update_role_declarations"})
12291            );
12292            let (raw, entry) = role_declarations_catalog(&handler);
12293            assert_eq!(
12294                serde_json::to_value(entry.role_declarations).unwrap(),
12295                declarations
12296            );
12297            if declarations.as_object().unwrap().is_empty() {
12298                assert!(raw.get("role_declarations").is_none());
12299            } else {
12300                assert_eq!(raw["role_declarations"], declarations);
12301            }
12302            let after = registry.get_module("role-test").unwrap().unwrap();
12303            let mut expected = before.manifest.clone();
12304            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12305            assert_eq!(after.manifest, expected);
12306            assert_eq!(after.ready, before.ready);
12307        }
12308    }
12309
12310    #[tokio::test]
12311    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12312        let registry = Arc::new(Registry::default());
12313        let handler = ControlHandler::new(registry);
12314        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12315        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12316        hello_via_sink(
12317            &handler,
12318            &ctx,
12319            &mut rx,
12320            hello_with_role_declarations(initial.clone()),
12321        )
12322        .await;
12323        for (invalid, reason) in [
12324            (json!(null), "role_declarations must be an object"),
12325            (json!([]), "role_declarations must be an object"),
12326            (
12327                json!({"bad key": {}}),
12328                "role_declarations key must use capability-name grammar",
12329            ),
12330            (
12331                json!({"media-provider/v1": []}),
12332                "role_declarations values must be objects",
12333            ),
12334            (
12335                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12336                "role_declarations exceeds 16384 compact JSON bytes",
12337            ),
12338        ] {
12339            let response = handler
12340                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12341                .await
12342                .unwrap();
12343            let error = parse_error(&response[0]);
12344            assert_eq!(error["code"], "invalid_role_declarations");
12345            assert_eq!(error["message"], reason);
12346            assert_eq!(
12347                role_declarations_catalog(&handler).0["role_declarations"],
12348                initial
12349            );
12350        }
12351    }
12352
12353    #[tokio::test]
12354    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12355        let registry = Arc::new(Registry::default());
12356        let handler = ControlHandler::new(Arc::clone(&registry));
12357        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12358        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12359        hello_via_sink(
12360            &handler,
12361            &owner,
12362            &mut owner_rx,
12363            hello_with_role_declarations(initial.clone()),
12364        )
12365        .await;
12366        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12367        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12368        let response = handler
12369            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12370            .await
12371            .unwrap();
12372        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12373        hello_via_sink(
12374            &handler,
12375            &other,
12376            &mut other_rx,
12377            hello_frame("other", PROTOCOL_VERSION, 304),
12378        )
12379        .await;
12380        let response = handler
12381            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12382            .await
12383            .unwrap();
12384        assert_eq!(response[0].header.ty, FrameType::Response);
12385        assert_eq!(
12386            serde_json::to_value(
12387                registry
12388                    .get_module("role-test")
12389                    .unwrap()
12390                    .unwrap()
12391                    .manifest
12392                    .role_declarations
12393            )
12394            .unwrap(),
12395            initial
12396        );
12397        assert_eq!(
12398            serde_json::to_value(
12399                registry
12400                    .get_module("other")
12401                    .unwrap()
12402                    .unwrap()
12403                    .manifest
12404                    .role_declarations
12405            )
12406            .unwrap(),
12407            replacement
12408        );
12409    }
12410
12411    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12412        let request = Frame::build(
12413            FrameType::Request,
12414            control_flags(),
12415            0,
12416            0,
12417            302,
12418            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12419        )
12420        .unwrap();
12421        let response = handler.handle_catalog_list(request, None).unwrap();
12422        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12423        let ClientControlResponse::CatalogList { mut modules, .. } =
12424            serde_json::from_slice(&response[0].body).unwrap()
12425        else {
12426            panic!("expected catalog.list");
12427        };
12428        (raw["modules"][0].clone(), modules.remove(0))
12429    }
12430
12431    #[test]
12432    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12433        let registry = Arc::new(Registry::default());
12434        let handler = ControlHandler::new(Arc::clone(&registry));
12435        let declarations = json!({
12436            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12437            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12438        });
12439        let connection = ConnectionId::new(301);
12440        let response = handler
12441            .handle_control(
12442                connection,
12443                hello_with_role_declarations(declarations.clone()),
12444            )
12445            .unwrap();
12446        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12447        let registered = registry
12448            .get_module_by_connection(connection)
12449            .unwrap()
12450            .unwrap()
12451            .manifest;
12452        // Compared as JSON values, not bytes: object key order is not part of
12453        // the relay's promise, and workspace builds unify serde_json's
12454        // preserve_order feature, which changes the order a literal keeps.
12455        assert_eq!(
12456            serde_json::to_value(&registered.role_declarations).unwrap(),
12457            declarations
12458        );
12459        let (raw, entry) = role_declarations_catalog(&handler);
12460        assert_eq!(raw["role_declarations"], declarations);
12461        assert_eq!(entry.role_declarations, registered.role_declarations);
12462
12463        let request =
12464            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12465        handler
12466            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12467            .unwrap();
12468        let (raw, entry) = role_declarations_catalog(&handler);
12469        assert_eq!(raw["role_declarations"], declarations);
12470        assert_eq!(entry.role_declarations, registered.role_declarations);
12471    }
12472
12473    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12474        let registry = Arc::new(Registry::default());
12475        let handler = ControlHandler::new(Arc::clone(&registry));
12476        let capture = EventCapture::default();
12477        let _subscriber =
12478            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12479        let response = handler
12480            .handle_control(
12481                ConnectionId::new(301),
12482                hello_with_role_declarations(declarations),
12483            )
12484            .unwrap();
12485        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12486        assert!(registry
12487            .get_module_by_connection(ConnectionId::new(301))
12488            .unwrap()
12489            .unwrap()
12490            .manifest
12491            .role_declarations
12492            .is_empty());
12493        let (raw, entry) = role_declarations_catalog(&handler);
12494        assert!(raw.get("role_declarations").is_none());
12495        assert!(entry.role_declarations.is_empty());
12496        let warnings: Vec<_> = capture
12497            .events()
12498            .into_iter()
12499            .filter(|event| {
12500                event.fields.get("message").map(String::as_str)
12501                    == Some("dropping whole role_declarations map from HELLO")
12502            })
12503            .collect();
12504        assert_eq!(warnings.len(), 1);
12505        assert_eq!(warnings[0].level, tracing::Level::WARN);
12506        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12507        assert_eq!(warnings[0].fields["reason"], reason);
12508    }
12509
12510    #[test]
12511    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12512        for value in [
12513            json!(null),
12514            json!(false),
12515            json!(0),
12516            json!("opaque"),
12517            json!([]),
12518        ] {
12519            assert_hello_drops_role_declarations_with_warning(
12520                json!({"routing/v1": {}, "broken/v1": value}),
12521                "role_declarations values must be objects",
12522            );
12523        }
12524        assert_hello_drops_role_declarations_with_warning(
12525            json!([]),
12526            "role_declarations must be an object",
12527        );
12528    }
12529
12530    #[test]
12531    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12532        assert_hello_drops_role_declarations_with_warning(
12533            json!({"routing/v1": {}, "bad key": {}}),
12534            "role_declarations key must use capability-name grammar",
12535        );
12536    }
12537
12538    #[test]
12539    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12540        assert_hello_drops_role_declarations_with_warning(
12541            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12542            "role_declarations exceeds 16384 compact JSON bytes",
12543        );
12544    }
12545
12546    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12547        let mut body = serde_json::to_value(ModuleHelloBody {
12548            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12549            protocol_ver: PROTOCOL_VERSION,
12550            control_ops: None,
12551            launch_nonce: None,
12552        })
12553        .unwrap();
12554        body["manifest"]["provides"] = json!([{
12555            "role": "management_surface",
12556            "operations": [
12557                {"name": "diagnostics.findings", "kind": "query"},
12558                {"name": "reset", "kind": "mutate"}
12559            ],
12560            "config_schema": {}, "observability": [], "identity_scope": []
12561        }]);
12562        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12563        if let Some(flow_operations) = flow_operations {
12564            body["manifest"]["flow_operations"] = flow_operations;
12565        }
12566        Frame::build(
12567            FrameType::Hello,
12568            control_flags(),
12569            0,
12570            0,
12571            401,
12572            serde_json::to_vec(&body).unwrap(),
12573        )
12574        .unwrap()
12575    }
12576
12577    #[test]
12578    fn catalog_list_mirrors_flow_operations_unchanged() {
12579        // Order is kept as declared (not sorted) and an empty list stays an
12580        // affirmative "none", distinct from an absent declaration.
12581        for (capability, flow_operations) in [
12582            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12583            ("call-modes/v1", json!(["diagnostics.findings"])),
12584            ("flow-scopes/v1", json!([])),
12585        ] {
12586            let registry = Arc::new(Registry::default());
12587            let handler = ControlHandler::new(Arc::clone(&registry));
12588            let connection = ConnectionId::new(401);
12589            let response = handler
12590                .handle_control(
12591                    connection,
12592                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12593                )
12594                .unwrap();
12595            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12596            let registered = registry
12597                .get_module_by_connection(connection)
12598                .unwrap()
12599                .unwrap()
12600                .manifest;
12601            assert_eq!(
12602                serde_json::to_value(&registered.flow_operations).unwrap(),
12603                flow_operations
12604            );
12605            let (raw, entry) = role_declarations_catalog(&handler);
12606            assert_eq!(raw["flow_operations"], flow_operations);
12607            assert_eq!(entry.flow_operations, registered.flow_operations);
12608        }
12609
12610        let registry = Arc::new(Registry::default());
12611        let handler = ControlHandler::new(Arc::clone(&registry));
12612        let response = handler
12613            .handle_control(
12614                ConnectionId::new(401),
12615                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12616            )
12617            .unwrap();
12618        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12619        let (raw, entry) = role_declarations_catalog(&handler);
12620        assert!(raw.get("flow_operations").is_none());
12621        assert_eq!(entry.flow_operations, None);
12622    }
12623
12624    #[test]
12625    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12626        let oversized: serde_json::Map<String, Value> = (0..257)
12627            .map(|n| (format!("tool:t{n}"), json!(true)))
12628            .collect();
12629        for (capabilities, map, valid) in [
12630            (
12631                json!(["scope-federated/v1"]),
12632                json!({"tool:read":true,"management:reset":true}),
12633                true,
12634            ),
12635            (json!(["scope-federated/v1"]), json!({}), true),
12636            (json!([]), json!({"tool:read":true}), false),
12637            (
12638                json!(["scope-federated/v1"]),
12639                json!({"tool:valid":true,"tool:bad":false}),
12640                false,
12641            ),
12642            (
12643                json!(["scope-federated/v1"]),
12644                json!({"tool:valid":true,"management:missing":true}),
12645                false,
12646            ),
12647            (
12648                json!(["scope-federated/v1"]),
12649                Value::Object(oversized),
12650                false,
12651            ),
12652        ] {
12653            let capture = EventCapture::default();
12654            let _subscriber = tracing::subscriber::set_default(
12655                tracing_subscriber::registry().with(capture.clone()),
12656            );
12657            let registry = Arc::new(Registry::default());
12658            let handler = ControlHandler::new(Arc::clone(&registry));
12659            let hello = hello_with_flow_operations(capabilities, None);
12660            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12661            body["manifest"]["operation_deferral"] = map.clone();
12662            let hello = Frame::build(
12663                FrameType::Hello,
12664                control_flags(),
12665                0,
12666                0,
12667                401,
12668                serde_json::to_vec(&body).unwrap(),
12669            )
12670            .unwrap();
12671            let response = handler
12672                .handle_control(ConnectionId::new(401), hello)
12673                .unwrap();
12674            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12675            let (raw, entry) = role_declarations_catalog(&handler);
12676            if valid {
12677                assert_eq!(raw["operation_deferral"], map);
12678                assert_eq!(
12679                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12680                    map
12681                );
12682            } else {
12683                assert!(entry.operation_deferral.is_none());
12684                assert!(raw.get("operation_deferral").is_none());
12685                assert_eq!(
12686                    capture
12687                        .events()
12688                        .iter()
12689                        .filter(|event| event.fields.get("message").map(String::as_str)
12690                            == Some("dropping operation_deferral from HELLO"))
12691                        .count(),
12692                    1
12693                );
12694            }
12695        }
12696    }
12697
12698    fn assert_hello_drops_flow_operations_with_warning(
12699        capabilities: Value,
12700        flow_operations: Value,
12701        reason: &str,
12702    ) {
12703        let registry = Arc::new(Registry::default());
12704        let handler = ControlHandler::new(Arc::clone(&registry));
12705        let capture = EventCapture::default();
12706        let _subscriber =
12707            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12708        let response = handler
12709            .handle_control(
12710                ConnectionId::new(401),
12711                hello_with_flow_operations(capabilities, Some(flow_operations)),
12712            )
12713            .unwrap();
12714        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12715        let registered = registry
12716            .get_module_by_connection(ConnectionId::new(401))
12717            .unwrap()
12718            .expect("the module still registers")
12719            .manifest;
12720        assert_eq!(registered.module_id, "flow-ops");
12721        assert_eq!(registered.flow_operations, None);
12722        let (raw, entry) = role_declarations_catalog(&handler);
12723        assert_eq!(raw["module_id"], "flow-ops");
12724        assert!(raw.get("flow_operations").is_none());
12725        assert_eq!(entry.flow_operations, None);
12726        let warnings: Vec<_> = capture
12727            .events()
12728            .into_iter()
12729            .filter(|event| {
12730                event.fields.get("message").map(String::as_str)
12731                    == Some("dropping flow_operations from HELLO")
12732            })
12733            .collect();
12734        assert_eq!(warnings.len(), 1);
12735        assert_eq!(warnings[0].level, tracing::Level::WARN);
12736        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12737        assert_eq!(warnings[0].fields["reason"], reason);
12738    }
12739
12740    #[test]
12741    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12742        assert_hello_drops_flow_operations_with_warning(
12743            json!(["flow-scopes/v1"]),
12744            json!(["diagnostics.findings", "missing"]),
12745            "flow_operations names 'missing', which is not a declared management operation",
12746        );
12747    }
12748
12749    #[test]
12750    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12751        assert_hello_drops_flow_operations_with_warning(
12752            json!([]),
12753            json!(["diagnostics.findings"]),
12754            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12755        );
12756        // A run-only capability does not admit flows either.
12757        assert_hello_drops_flow_operations_with_warning(
12758            json!(["agent-run-scopes/v1"]),
12759            json!([]),
12760            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12761        );
12762    }
12763
12764    #[test]
12765    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12766        assert_hello_drops_flow_operations_with_warning(
12767            json!(["flow-scopes/v1"]),
12768            json!(["reset", "reset"]),
12769            "flow_operations names 'reset' more than once",
12770        );
12771        assert_hello_drops_flow_operations_with_warning(
12772            json!(["flow-scopes/v1"]),
12773            json!(vec!["reset"; 257]),
12774            "flow_operations lists 257 names, more than 256",
12775        );
12776        assert_hello_drops_flow_operations_with_warning(
12777            json!(["flow-scopes/v1"]),
12778            json!("reset"),
12779            "flow_operations must be an array of operation names",
12780        );
12781    }
12782
12783    #[test]
12784    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12785        let registry = Arc::new(Registry::default());
12786        let handler = ControlHandler::new(registry.clone());
12787        let descriptor = json!({
12788            "schema": "ckios.richui.manifest/1",
12789            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12790            "bytes": 128,
12791            "chunks": 2
12792        });
12793        let malformed = [
12794            ("schema", json!("")),
12795            ("schema", json!("a".repeat(65))),
12796            ("schema", json!("Bad schema")),
12797            (
12798                "manifest_digest",
12799                json!(format!("sha256:{}", "A".repeat(64))),
12800            ),
12801            ("manifest_digest", json!("sha256:abc")),
12802            ("bytes", json!(0)),
12803            ("bytes", json!(16_777_217)),
12804            ("bytes", json!("128")),
12805            ("chunks", json!(0)),
12806            ("chunks", json!(1025)),
12807            ("chunks", json!("2")),
12808        ];
12809        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12810            let mut invalid = descriptor.clone();
12811            invalid[field] = invalid_value;
12812            let response = handler
12813                .handle_control(
12814                    ConnectionId::new(210 + index as u64),
12815                    hello_frame_with_rich_ui(
12816                        &format!("bad-rich-ui-{index}"),
12817                        PROTOCOL_VERSION,
12818                        210 + index as u64,
12819                        None,
12820                        invalid,
12821                    ),
12822                )
12823                .unwrap();
12824            assert_eq!(response[0].header.ty, FrameType::Error);
12825            let error = parse_error(&response[0]);
12826            assert_eq!(error["code"], "invalid_manifest");
12827            assert!(error["message"]
12828                .as_str()
12829                .unwrap()
12830                .contains(&format!("rich_ui.{field}")));
12831            assert!(registry
12832                .get_module(&format!("bad-rich-ui-{index}"))
12833                .unwrap()
12834                .is_none());
12835        }
12836    }
12837
12838    #[test]
12839    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12840        let registry = Arc::new(Registry::default());
12841        let handler = ControlHandler::new(Arc::clone(&registry));
12842        let connection = ConnectionId::new(219);
12843        registry
12844            .register_with_control_ops(
12845                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12846                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12847                        "bad schema",
12848                        format!("sha256:{}", "a".repeat(64)),
12849                        128,
12850                        2,
12851                    )))
12852                    .build(),
12853                PROTOCOL_VERSION,
12854                connection,
12855                Vec::new(),
12856            )
12857            .unwrap();
12858        let request =
12859            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12860        let response = handler
12861            .handle_catalog_update(connection, request, Vec::new(), None, None)
12862            .unwrap();
12863        assert_eq!(response[0].header.ty, FrameType::Error);
12864        let error = parse_error(&response[0]);
12865        assert_eq!(error["code"], "invalid_manifest");
12866        assert!(error["message"]
12867            .as_str()
12868            .unwrap()
12869            .contains("rich_ui.schema"));
12870    }
12871
12872    #[test]
12873    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12874        let registry = Arc::new(Registry::default());
12875        let supervisor = SupervisorHandle::new();
12876        supervisor.open_swap("provider", "candidate-nonce".to_string());
12877        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12878        let connection = ConnectionId::new(218);
12879        let hello = handler
12880            .handle_control(
12881                connection,
12882                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12883            )
12884            .unwrap();
12885        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12886        assert!(registry.list_modules().unwrap().1.is_empty());
12887
12888        registry.promote_candidate("provider").unwrap().unwrap();
12889        let request = Frame::build(
12890            FrameType::Request,
12891            control_flags(),
12892            0,
12893            0,
12894            219,
12895            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12896        )
12897        .unwrap();
12898        let response = handler.handle_catalog_list(request, None).unwrap();
12899        let ClientControlResponse::CatalogList { modules, .. } =
12900            serde_json::from_slice(&response[0].body).unwrap()
12901        else {
12902            panic!("expected catalog.list");
12903        };
12904        assert_eq!(modules.len(), 1);
12905        assert!(modules[0].nonce_verified);
12906    }
12907
12908    #[test]
12909    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12910        for provenance_json in [
12911            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12912            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12913        ] {
12914            let registry = Arc::new(Registry::default());
12915            let handler = ControlHandler::new(registry);
12916            let hello = Frame::build(
12917                FrameType::Hello,
12918                control_flags(),
12919                0,
12920                0,
12921                220,
12922                serde_json::to_vec(&ModuleHelloBody {
12923                    manifest: ModuleManifest::builder("built", "0.1.0")
12924                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12925                        .build(),
12926                    protocol_ver: PROTOCOL_VERSION,
12927                    control_ops: None,
12928                    launch_nonce: None,
12929                })
12930                .unwrap(),
12931            )
12932            .unwrap();
12933            assert_eq!(
12934                handler
12935                    .handle_control(ConnectionId::new(220), hello)
12936                    .unwrap()[0]
12937                    .header
12938                    .ty,
12939                FrameType::HelloAck
12940            );
12941            let request = Frame::build(
12942                FrameType::Request,
12943                control_flags(),
12944                0,
12945                0,
12946                221,
12947                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12948            )
12949            .unwrap();
12950            let response = handler.handle_catalog_list(request, None).unwrap();
12951            let ClientControlResponse::CatalogList { modules, .. } =
12952                serde_json::from_slice(&response[0].body).unwrap()
12953            else {
12954                panic!("expected catalog.list");
12955            };
12956            assert_eq!(modules.len(), 1);
12957            assert_eq!(
12958                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12959                format!(
12960                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12961                )
12962                .as_bytes()
12963            );
12964        }
12965    }
12966
12967    #[test]
12968    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12969        let registry = Arc::new(Registry::default());
12970        let handler = ControlHandler::new(Arc::clone(&registry));
12971        let hello = Frame::build(
12972            FrameType::Hello,
12973            control_flags(),
12974            0,
12975            0,
12976            220,
12977            serde_json::to_vec(&ModuleHelloBody {
12978                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12979                protocol_ver: PROTOCOL_VERSION,
12980                control_ops: None,
12981                launch_nonce: Some("unverified".to_string()),
12982            })
12983            .unwrap(),
12984        )
12985        .unwrap();
12986        assert_eq!(
12987            handler
12988                .handle_control(ConnectionId::new(220), hello)
12989                .unwrap()[0]
12990                .header
12991                .ty,
12992            FrameType::HelloAck
12993        );
12994        let request = Frame::build(
12995            FrameType::Request,
12996            control_flags(),
12997            0,
12998            0,
12999            221,
13000            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13001        )
13002        .unwrap();
13003        let response = handler.handle_catalog_list(request, None).unwrap();
13004        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
13005        assert!(wire["modules"][0].get("provenance").is_none());
13006        let ClientControlResponse::CatalogList { modules, .. } =
13007            serde_json::from_slice(&response[0].body).unwrap()
13008        else {
13009            panic!("expected catalog.list");
13010        };
13011        assert_eq!(
13012            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
13013            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
13014        );
13015        assert!(!modules[0].nonce_verified);
13016        assert!(modules[0].provenance.is_none());
13017    }
13018
13019    // Preserve the legacy-field byte pins while discovery adds optional facts.
13020    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
13021        assert_eq!(entry.first_party, Some(false));
13022        entry.incarnation = None;
13023        entry.spawn = None;
13024        entry.first_party = None;
13025        entry.origin = None;
13026        entry.requested_declarations_digest = None;
13027        entry.approved_declarations_digest = None;
13028        entry
13029    }
13030
13031    #[test]
13032    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
13033        let registry = Arc::new(Registry::default());
13034        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13035            [("vault".to_string(), true), ("squatter".to_string(), true)],
13036            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13037        );
13038        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
13039        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13040            provides: vec!["credentials-provider/v1".to_string()],
13041            requires: Vec::new(),
13042            must_never_reach: Vec::new(),
13043        });
13044        let frame = Frame::build(
13045            FrameType::Hello,
13046            control_flags(),
13047            0,
13048            0,
13049            77,
13050            serde_json::to_vec(&ModuleHelloBody {
13051                manifest: squatter,
13052                protocol_ver: PROTOCOL_VERSION,
13053                control_ops: None,
13054                launch_nonce: None,
13055            })
13056            .expect("HELLO serializes"),
13057        )
13058        .expect("HELLO frame builds");
13059        let response = handler
13060            .handle_control(ConnectionId::new(77), frame)
13061            .expect("reserved claim receives a typed refusal");
13062        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13063        assert_eq!(
13064            registry
13065                .active_registration_count()
13066                .expect("registry reads"),
13067            0,
13068            "a reserved capability refusal must not leave a catalog entry"
13069        );
13070    }
13071
13072    #[test]
13073    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
13074        for settlement in ["timeout", "inconclusive", "drop"] {
13075            let breakers = RouteBindBreakers::default();
13076            let RouteBindAdmission::Admitted {
13077                guard: mut old,
13078                probe: false,
13079            } = breakers.admit("prov")
13080            else {
13081                panic!("ordinary relay admitted")
13082            };
13083            let RouteBindAdmission::Admitted {
13084                guard: mut opener, ..
13085            } = breakers.admit("prov")
13086            else {
13087                panic!("second relay admitted")
13088            };
13089            assert!(
13090                !opener
13091                    .record_timeout(1, Duration::ZERO)
13092                    .unwrap()
13093                    .reopened_after_probe
13094            );
13095            let RouteBindAdmission::Admitted {
13096                guard: mut probe,
13097                probe: true,
13098            } = breakers.admit("prov")
13099            else {
13100                panic!("one cooldown probe admitted")
13101            };
13102            match settlement {
13103                "timeout" => assert!(
13104                    !old.record_timeout(1, Duration::ZERO)
13105                        .unwrap()
13106                        .reopened_after_probe
13107                ),
13108                "inconclusive" => old.record_inconclusive(),
13109                "drop" => drop(old),
13110                _ => unreachable!(),
13111            }
13112            assert!(
13113                matches!(
13114                    breakers.admit("prov"),
13115                    RouteBindAdmission::Refused {
13116                        probe_in_flight: true,
13117                        ..
13118                    }
13119                ),
13120                "{settlement} of a pre-open relay cannot release the real probe"
13121            );
13122            assert!(
13123                probe
13124                    .record_timeout(1, Duration::ZERO)
13125                    .unwrap()
13126                    .reopened_after_probe
13127            );
13128            assert!(matches!(
13129                breakers.admit("prov"),
13130                RouteBindAdmission::Admitted { probe: true, .. }
13131            ));
13132        }
13133        let breakers = RouteBindBreakers::default();
13134        let admit = || match breakers.admit("prov") {
13135            RouteBindAdmission::Admitted { guard, .. } => guard,
13136            _ => panic!("relay admitted"),
13137        };
13138        admit().record_timeout(1, Duration::ZERO);
13139        let mut old_probe = admit();
13140        breakers.reset_for_new_module_connection("prov");
13141        admit().record_timeout(1, Duration::ZERO);
13142        let _new_probe = admit();
13143        old_probe.record_inconclusive();
13144        assert!(matches!(
13145            breakers.admit("prov"),
13146            RouteBindAdmission::Refused {
13147                probe_in_flight: true,
13148                ..
13149            }
13150        ));
13151    }
13152
13153    #[tokio::test]
13154    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13155        for candidate in [false, true] {
13156            let registry = Arc::new(Registry::default());
13157            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13158                [("vault".to_string(), true), ("squatter".to_string(), true)],
13159                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13160            );
13161            let conn = ConnectionId::new(77);
13162            let (ctx, mut rx) = route_ctx(conn);
13163            let initial = capability_manifest("squatter", &[], &[]);
13164            if candidate {
13165                registry
13166                    .register_candidate_with_control_ops(
13167                        initial.clone(),
13168                        PROTOCOL_VERSION,
13169                        conn,
13170                        module_baseline_control_ops(),
13171                    )
13172                    .unwrap();
13173                handler
13174                    .forwarding
13175                    .register_candidate_module_connection(
13176                        conn,
13177                        "squatter".to_string(),
13178                        PROTOCOL_VERSION,
13179                        manifest_concurrency(&initial),
13180                        ctx.egress.clone(),
13181                    )
13182                    .unwrap();
13183            } else {
13184                hello_via_sink(
13185                    &handler,
13186                    &ctx,
13187                    &mut rx,
13188                    hello_frame_with_manifest(initial.clone(), 1),
13189                )
13190                .await;
13191            }
13192            let response = handler
13193                .handle_control_frame(
13194                    &ctx,
13195                    catalog_update_with_capabilities_frame(
13196                        2,
13197                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13198                            .capabilities
13199                            .unwrap(),
13200                    ),
13201                )
13202                .await
13203                .unwrap();
13204            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13205            assert_eq!(
13206                registry
13207                    .get_module_by_connection(conn)
13208                    .unwrap()
13209                    .unwrap()
13210                    .manifest,
13211                initial
13212            );
13213        }
13214    }
13215
13216    #[test]
13217    #[cfg(not(feature = "dev-desktop-approval"))]
13218    fn server_describe_default_build_advertises_no_config_capability() {
13219        let assert_default = |handler: &ControlHandler| {
13220            let request = Frame::build(
13221                FrameType::Request,
13222                control_flags(),
13223                0,
13224                0,
13225                79,
13226                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13227            )
13228            .unwrap();
13229            let responses = handler.handle_server_describe(request).unwrap();
13230            assert_eq!(responses.len(), 1);
13231            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13232            assert_eq!(response["op"], "server.describe");
13233            let capabilities = response["capabilities"]
13234                .as_array()
13235                .expect("capability array");
13236            assert!(
13237                !capabilities.is_empty(),
13238                "exercise an actual describe response, not an empty fixture"
13239            );
13240            assert!(
13241                capabilities
13242                    .iter()
13243                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13244                "a default build must not announce configuration authority: {capabilities:?}"
13245            );
13246        };
13247        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13248        #[cfg(unix)]
13249        {
13250            // A local store does not prove that project-membership validation,
13251            // active-scope usage tracking and approved-program launch selection
13252            // are connected. Defaults must not advertise that authority.
13253            let (_rig, _owner, _supervisor, handler, _spec) =
13254                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13255                );
13256            assert_default(&handler);
13257        }
13258    }
13259
13260    #[test]
13261    fn server_describe_surfaces_required_capability_verdict_fields() {
13262        let registry = Arc::new(Registry::default());
13263        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13264            [
13265                ("consumer".to_string(), true),
13266                ("provider".to_string(), false),
13267            ],
13268            BTreeMap::new(),
13269        );
13270        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13271        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13272            provides: Vec::new(),
13273            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13274                capability: "credentials-provider/v1".to_string(),
13275                need: subc_protocol::manifest::CapabilityNeed::Required,
13276            }],
13277            must_never_reach: Vec::new(),
13278        });
13279        let hello = Frame::build(
13280            FrameType::Hello,
13281            control_flags(),
13282            0,
13283            0,
13284            78,
13285            serde_json::to_vec(&ModuleHelloBody {
13286                manifest: consumer,
13287                protocol_ver: PROTOCOL_VERSION,
13288                control_ops: None,
13289                launch_nonce: None,
13290            })
13291            .expect("HELLO serializes"),
13292        )
13293        .expect("HELLO frame builds");
13294        handler
13295            .handle_control(ConnectionId::new(78), hello)
13296            .expect("consumer registers");
13297        let describe = Frame::build(
13298            FrameType::Request,
13299            control_flags(),
13300            0,
13301            0,
13302            79,
13303            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13304                .expect("request serializes"),
13305        )
13306        .expect("describe frame builds");
13307        let response = handler
13308            .handle_server_describe(describe)
13309            .expect("server.describe succeeds");
13310        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13311        let requirement = &rendered["capability_requirements"][0];
13312        assert_eq!(requirement["consumer"], "consumer");
13313        assert_eq!(requirement["verdict"], "never_provided");
13314        assert_eq!(requirement["episode_seq"], 1);
13315        assert_eq!(requirement["config_satisfiable"], false);
13316        assert_eq!(requirement["runtime_available"], false);
13317        assert!(requirement["detail"]
13318            .as_str()
13319            .expect("detail string")
13320            .contains("credentials-provider/v1"));
13321    }
13322
13323    /// Register a consumer that requires `project-identity/v1` and the provider
13324    /// of it, optionally mark daemon shutdown as begun, then deregister the
13325    /// provider as its connection closes. Returns the `capability.requirement`
13326    /// events that deregistration logged and the verdict the evaluator then
13327    /// holds for the requirement (the one `route.open` refusals read).
13328    fn deregister_required_provider(
13329        daemon_shutdown_begun: bool,
13330    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13331        const CAPABILITY: &str = "project-identity/v1";
13332        let registry = Arc::new(Registry::default());
13333        let daemon_shutdown = DaemonShutdownFlag::default();
13334        let handler = ControlHandler::new(Arc::clone(&registry))
13335            .with_capability_config(
13336                [
13337                    ("consumer".to_string(), true),
13338                    ("provider".to_string(), true),
13339                ],
13340                BTreeMap::new(),
13341            )
13342            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13343        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13344        consumer.capabilities = Some(CapabilityDeclarations {
13345            provides: Vec::new(),
13346            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13347                capability: CAPABILITY.to_string(),
13348                need: subc_protocol::manifest::CapabilityNeed::Required,
13349            }],
13350            must_never_reach: Vec::new(),
13351        });
13352        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13353        let provider_conn = ConnectionId::new(182);
13354        for (conn, manifest, corr) in [
13355            (ConnectionId::new(181), consumer, 181),
13356            (provider_conn, provider, 182),
13357        ] {
13358            let hello = handler
13359                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13360                .expect("module registers");
13361            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13362        }
13363        assert_eq!(
13364            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13365            Some(CapabilityVerdict::Provided),
13366            "the registered provider must satisfy the requirement first"
13367        );
13368        if daemon_shutdown_begun {
13369            daemon_shutdown.set_for_test();
13370        }
13371
13372        let capture = EventCapture::default();
13373        let _subscriber =
13374            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13375        handler
13376            .cleanup_connection(provider_conn)
13377            .expect("provider deregisters");
13378        let events = capture
13379            .events()
13380            .into_iter()
13381            .filter(|event| {
13382                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13383            })
13384            .collect();
13385        (
13386            events,
13387            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13388        )
13389    }
13390
13391    #[test]
13392    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13393        let (events, verdict) = deregister_required_provider(true);
13394        assert_eq!(
13395            verdict,
13396            Some(CapabilityVerdict::NeverProvided),
13397            "shutdown must not change the verdict route.open refusals read"
13398        );
13399        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13400        let event = &events[0];
13401        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13402        assert_eq!(
13403            event.fields.get("cause").map(String::as_str),
13404            Some("\"daemon_shutdown\""),
13405            "{event:?}"
13406        );
13407        assert_eq!(
13408            event.fields.get("verdict").map(String::as_str),
13409            Some("\"never_provided\""),
13410            "{event:?}"
13411        );
13412    }
13413
13414    #[test]
13415    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13416        let (events, verdict) = deregister_required_provider(false);
13417        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13418        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13419        let event = &events[0];
13420        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13421        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13422        assert_eq!(
13423            event.fields.get("verdict").map(String::as_str),
13424            Some("\"never_provided\""),
13425            "{event:?}"
13426        );
13427    }
13428
13429    #[test]
13430    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13431        let registry = Arc::new(Registry::default());
13432        let handler = ControlHandler::new(Arc::clone(&registry));
13433        let hello = handler
13434            .handle_control(
13435                ConnectionId::new(101),
13436                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13437            )
13438            .expect("legacy HELLO registers");
13439        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13440
13441        let request = Frame::build(
13442            FrameType::Request,
13443            control_flags(),
13444            0,
13445            0,
13446            102,
13447            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13448                .expect("catalog request serializes"),
13449        )
13450        .expect("catalog request frame builds");
13451        let response = handler
13452            .handle_catalog_list(request, None)
13453            .expect("catalog list succeeds");
13454        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13455        assert!(
13456            body["modules"][0].get("capabilities").is_none(),
13457            "legacy manifest must retain an absent capabilities field on catalog.list"
13458        );
13459    }
13460
13461    #[test]
13462    fn hello_ack_omits_storage_when_no_storage_config() {
13463        let registry = Arc::new(Registry::default());
13464        let handler = ControlHandler::new(Arc::clone(&registry));
13465        let responses = handler
13466            .handle_control(
13467                ConnectionId::new(1),
13468                hello_frame("aft", PROTOCOL_VERSION, 7),
13469            )
13470            .unwrap();
13471        let ack = parse_ack(&responses[0]);
13472        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13473        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13474    }
13475
13476    #[tokio::test]
13477    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13478        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13479        let registry = Arc::new(Registry::default());
13480        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13481        let responses = handler
13482            .handle_control(
13483                ConnectionId::new(1),
13484                hello_frame("aft", PROTOCOL_VERSION, 7),
13485            )
13486            .unwrap();
13487        let ack = parse_ack(&responses[0]);
13488        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13489
13490        let described = handler
13491            .handle_control_frame(
13492                &route_ctx(ConnectionId::new(2)).0,
13493                Frame::build(
13494                    FrameType::Request,
13495                    control_flags(),
13496                    0,
13497                    0,
13498                    9,
13499                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13500                )
13501                .unwrap(),
13502            )
13503            .await
13504            .unwrap();
13505        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13506            serde_json::from_slice(&described[0].body).unwrap()
13507        else {
13508            panic!("server.describe answered with another shape");
13509        };
13510        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13511    }
13512
13513    #[test]
13514    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13515        // With a central sqlite storage policy, each registering module gets its
13516        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13517        let registry = Arc::new(Registry::default());
13518        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13519            crate::daemon_config::StorageConfig::Sqlite {
13520                data_home: std::path::PathBuf::from("/data"),
13521            },
13522        ));
13523
13524        let responses = handler
13525            .handle_control(
13526                ConnectionId::new(1),
13527                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13528            )
13529            .unwrap();
13530        let ack = parse_ack(&responses[0]);
13531        assert_eq!(
13532            ack.storage,
13533            Some(serde_json::json!({
13534                "module_id": "alfonso-routing",
13535                "storage_namespace": "default",
13536                "isolation": { "kind": "module" },
13537                "backend": {
13538                    "backend": "sqlite",
13539                    "path": "/data/cortexkit/alfonso-routing/store.db"
13540                }
13541            })),
13542            "the delivered descriptor is the module's own sqlite store path"
13543        );
13544    }
13545
13546    #[test]
13547    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13548        let registry = Arc::new(Registry::default());
13549        let handler = ControlHandler::new(Arc::clone(&registry));
13550        let conn = ConnectionId::new(1);
13551        let responses = handler
13552            .handle_control(
13553                conn,
13554                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13555            )
13556            .unwrap();
13557        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13558        let registration = registry.get_module("aft").unwrap().unwrap();
13559        assert_eq!(registration.control_ops, module_baseline_control_ops());
13560
13561        let frame =
13562            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13563        assert!(handler
13564            .guard_module_control_op(&frame, "aft", "route.bind")
13565            .unwrap()
13566            .is_none());
13567        let error = handler
13568            .guard_module_control_op(&frame, "aft", "test.synthetic")
13569            .unwrap()
13570            .expect("synthetic ungranted op should be rejected");
13571        assert_eq!(error.header.ty, FrameType::Error);
13572        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13573    }
13574
13575    #[test]
13576    fn hello_control_ops_some_adds_optional_grants() {
13577        let registry = Arc::new(Registry::default());
13578        let handler = ControlHandler::new(Arc::clone(&registry));
13579        handler
13580            .handle_control(
13581                ConnectionId::new(1),
13582                hello_frame_with_control_ops(
13583                    "aft",
13584                    PROTOCOL_VERSION,
13585                    7,
13586                    Some(vec![
13587                        "future.synthetic".to_string(),
13588                        "route.bind".to_string(),
13589                    ]),
13590                ),
13591            )
13592            .unwrap();
13593        let registration = registry.get_module("aft").unwrap().unwrap();
13594        assert_eq!(
13595            registration.control_ops,
13596            vec![
13597                "route.bind".to_string(),
13598                "route.status".to_string(),
13599                "future.synthetic".to_string(),
13600            ]
13601        );
13602        let frame =
13603            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13604        assert!(handler
13605            .guard_module_control_op(&frame, "aft", "future.synthetic")
13606            .unwrap()
13607            .is_none());
13608    }
13609
13610    #[tokio::test]
13611    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13612        let registry = Arc::new(Registry::default());
13613        let forwarding = Arc::new(ForwardingTable::default());
13614        let handler =
13615            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13616        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13617        hello_via_sink(
13618            &handler,
13619            &module_ctx,
13620            &mut module_rx,
13621            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13622        )
13623        .await;
13624
13625        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13626        let responses = handler
13627            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13628            .await
13629            .unwrap();
13630        assert_eq!(responses.len(), 1);
13631        assert_eq!(responses[0].header.ty, FrameType::Error);
13632        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13633        assert!(module_rx.try_recv().is_err());
13634    }
13635
13636    #[tokio::test]
13637    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13638        let registry = Arc::new(Registry::default());
13639        let forwarding = Arc::new(ForwardingTable::default());
13640        let handler =
13641            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13642        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13643        hello_via_sink(
13644            &handler,
13645            &module_ctx,
13646            &mut module_rx,
13647            hello_frame_with_control_ops(
13648                "aft",
13649                PROTOCOL_VERSION,
13650                7,
13651                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13652            ),
13653        )
13654        .await;
13655
13656        let project_root = unique_project_root("demux");
13657        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13658        let route_handler = handler.clone();
13659        let route_task = tokio::spawn(async move {
13660            route_handler
13661                .handle_control_frame(
13662                    &route_client_ctx,
13663                    route_open_frame(100, "aft", project_root),
13664                )
13665                .await
13666                .unwrap()
13667        });
13668        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13669            .await
13670            .unwrap()
13671            .unwrap();
13672        assert!(matches!(
13673            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13674            ModuleControlRequest::RouteBind { .. }
13675        ));
13676
13677        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13678        let health_handler = handler.clone();
13679        let health_task = tokio::spawn(async move {
13680            health_handler
13681                .handle_control_frame(
13682                    &health_client_ctx,
13683                    supervisor_health_probe_frame(101, "aft"),
13684                )
13685                .await
13686                .unwrap()
13687        });
13688        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13689            .await
13690            .unwrap()
13691            .unwrap();
13692        assert_eq!(
13693            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13694            ModuleControlRequest::HealthCheck {}
13695        );
13696
13697        handler
13698            .handle_control_frame(
13699                &module_ctx,
13700                health_response(health_frame.header.corr, HealthStatus::Degraded),
13701            )
13702            .await
13703            .unwrap();
13704        let health_response = health_task.await.unwrap();
13705        assert_eq!(health_response.len(), 1);
13706        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13707            ClientControlResponse::SupervisorHealthProbe {
13708                module_id,
13709                status,
13710                detail,
13711                metrics,
13712            } => {
13713                assert_eq!(module_id, "aft");
13714                assert_eq!(status, HealthStatus::Degraded);
13715                assert_eq!(detail.as_deref(), Some("warming"));
13716                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13717            }
13718            other => panic!("unexpected health response: {other:?}"),
13719        }
13720
13721        handler
13722            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13723            .await
13724            .unwrap();
13725        let route_response = route_task.await.unwrap();
13726        assert!(route_response.is_empty());
13727        let published = route_client_rx.recv().await.unwrap();
13728        assert!(matches!(
13729            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13730            ClientControlResponse::RouteOpen { .. }
13731        ));
13732    }
13733
13734    /// Start one `route.open` on `client_connection` and return its still-running
13735    /// handler task together with the `route.bind` the module received for it.
13736    /// The handler blocks until the module answers, so it has to run as a task
13737    /// while the test drives the module side.
13738    async fn relay_route_open(
13739        handler: &ControlHandler,
13740        client_connection: ConnectionId,
13741        client_egress: &FrameSink,
13742        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13743        corr: u64,
13744        module_id: &str,
13745        project_root_label: &str,
13746    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13747        let ctx = RouteCtx {
13748            connection_id: client_connection,
13749            egress: client_egress.clone(),
13750        };
13751        let handler = handler.clone();
13752        let project_root = unique_project_root(project_root_label);
13753        let module_id = module_id.to_string();
13754        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13755        let task = tokio::spawn(async move {
13756            let _guard = tracing::dispatcher::set_default(&dispatch);
13757            handler
13758                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13759                .await
13760                .unwrap()
13761        });
13762        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13763            .await
13764            .expect("module receives the relayed route.bind")
13765            .expect("module egress is open");
13766        (task, bind.frame)
13767    }
13768
13769    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13770        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13771            ModuleControlRequest::RouteBind {
13772                route_channel,
13773                epoch,
13774                ..
13775            } => (route_channel, epoch),
13776            other => panic!("expected a route.bind request, got {other:?}"),
13777        }
13778    }
13779
13780    fn published_route(frame: &Frame) -> (u16, u32) {
13781        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13782            ClientControlResponse::RouteOpen {
13783                route_channel,
13784                route_epoch,
13785                ..
13786            } => (route_channel, route_epoch),
13787            other => panic!("expected a route.open response, got {other:?}"),
13788        }
13789    }
13790
13791    /// Reproduction of a production outage. A client had `route.open`s in
13792    /// flight to a module and was already marked closing -- its egress had refused a
13793    /// module frame, so the daemon asked its connection to end -- while its sink
13794    /// was still open. When the module acked those binds, the daemon refused to
13795    /// commit a route for a closing client, and that refusal was returned from
13796    /// the MODULE connection's frame handler, where a router error that has no
13797    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13798    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13799    /// its tools for hours -- one client's teardown took down a connection
13800    /// carrying ~170 other routes.
13801    ///
13802    /// The window is opened here by calling the production path that opens it
13803    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13804    /// state that matters is "in `closing_connections`, sink still open, relay
13805    /// still pending", and it lasts only from the close request until the
13806    /// connection loop reacts to it; a socket-level test can flood a client into
13807    /// that escalation but cannot pin the module's ack inside the window. Closing
13808    /// the socket instead takes the other path entirely -- connection teardown
13809    /// removes the pending relay under the same lock, so the ack finds nothing.
13810    #[tokio::test]
13811    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13812        let registry = Arc::new(Registry::default());
13813        let forwarding = Arc::new(ForwardingTable::default());
13814        let handler =
13815            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13816
13817        let module_connection = ConnectionId::new(30);
13818        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13819        hello_via_sink(
13820            &handler,
13821            &module_ctx,
13822            &mut module_rx,
13823            hello_frame("aft", PROTOCOL_VERSION, 7),
13824        )
13825        .await;
13826
13827        let dying_client = ConnectionId::new(31);
13828        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13829
13830        // A published route on the dying client. The escalation below only marks
13831        // a connection closing for a route it has already published.
13832        let (first_task, first_bind) = relay_route_open(
13833            &handler,
13834            dying_client,
13835            &dying_ctx.egress,
13836            &mut module_rx,
13837            100,
13838            "aft",
13839            "closing-first",
13840        )
13841        .await;
13842        handler
13843            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13844            .await
13845            .unwrap();
13846        assert!(first_task.await.unwrap().is_empty());
13847        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13848
13849        // A second route.open from the same client, relayed and awaiting its ack.
13850        let (second_task, second_bind) = relay_route_open(
13851            &handler,
13852            dying_client,
13853            &dying_ctx.egress,
13854            &mut module_rx,
13855            101,
13856            "aft",
13857            "closing-second",
13858        )
13859        .await;
13860        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13861
13862        // The window: the client is closing, its sink is still open, and its
13863        // second bind is still pending.
13864        assert!(forwarding
13865            .escalate_client_delivery_failure(
13866                dying_client,
13867                first_channel,
13868                first_epoch,
13869                CloseReason::new(
13870                    "module_to_client_delivery_failed",
13871                    "client egress refused a module frame",
13872                ),
13873                crate::forwarding::UndeliveredFrame {
13874                    module_id: None,
13875                    sink: &dying_ctx.egress,
13876                },
13877            )
13878            .unwrap());
13879        assert!(!dying_ctx.egress.is_closed());
13880
13881        // The frame that used to end the module connection.
13882        let ack = handler
13883            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13884            .await;
13885        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13886        if module_loop_error.is_some() {
13887            // What the server's connection loop does with a router error that has
13888            // no ERROR-frame translation: end the connection, which releases the
13889            // module's registration and every route on it.
13890            handler.cleanup_connection(module_connection).unwrap();
13891        }
13892        // Read the module's next frame before opening the co-tenant's route, so
13893        // the GOODBYE assertion below is about THIS ack and not about later
13894        // traffic. `None` means the module was told nothing.
13895        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13896            .await
13897            .ok()
13898            .flatten();
13899
13900        // 1. The module connection is still registered.
13901        assert!(
13902            registry
13903                .get_module_by_connection(module_connection)
13904                .unwrap()
13905                .is_some(),
13906            "one client's closing connection ended the shared module connection: \
13907             {module_loop_error:?}"
13908        );
13909        // ...and still serving: another client can open and use a route on it.
13910        let cotenant = ConnectionId::new(32);
13911        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13912        let (cotenant_task, cotenant_bind) = relay_route_open(
13913            &handler,
13914            cotenant,
13915            &cotenant_ctx.egress,
13916            &mut module_rx,
13917            102,
13918            "aft",
13919            "closing-cotenant",
13920        )
13921        .await;
13922        handler
13923            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13924            .await
13925            .unwrap();
13926        assert!(cotenant_task.await.unwrap().is_empty());
13927        let (cotenant_channel, cotenant_epoch) =
13928            published_route(&cotenant_rx.recv().await.unwrap());
13929        assert!(matches!(
13930            forwarding
13931                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13932                .unwrap(),
13933            DataRoute::Client(DataRouteState::Bound(_))
13934        ));
13935
13936        // 2. The module was told to drop the binding it created for the route
13937        //    that will never be published.
13938        let goodbye = post_ack_module_frame
13939            .expect("module receives a GOODBYE for the abandoned route channel");
13940        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13941        assert_eq!(goodbye.header.channel, abandoned_channel);
13942        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13943
13944        // 3. The dying client received nothing: no route was ever published to
13945        //    it. Its route.open is answered as unavailable, which the connection
13946        //    loop would write to a socket that is already going away.
13947        assert!(dying_rx.try_recv().is_err());
13948        let second_response = second_task.await.unwrap();
13949        assert_eq!(second_response.len(), 1);
13950        assert_eq!(
13951            parse_error(&second_response[0])["code"],
13952            "target_unavailable"
13953        );
13954    }
13955
13956    /// One `catalog.list` as a client sees it: the generation and the listed
13957    /// module ids with their readiness.
13958    async fn catalog_snapshot(
13959        handler: &ControlHandler,
13960        client_ctx: &RouteCtx,
13961        corr: u64,
13962    ) -> (u64, Vec<(String, bool)>) {
13963        let body =
13964            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13965        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13966        let reply = handler
13967            .handle_control_frame(client_ctx, request)
13968            .await
13969            .unwrap()
13970            .pop()
13971            .unwrap();
13972        let ClientControlResponse::CatalogList {
13973            generation,
13974            modules,
13975            ..
13976        } = serde_json::from_slice(&reply.body).unwrap()
13977        else {
13978            panic!("not a catalog.list reply");
13979        };
13980        (
13981            generation,
13982            modules
13983                .into_iter()
13984                .map(|entry| (entry.module_id, entry.ready))
13985                .collect(),
13986        )
13987    }
13988
13989    /// A handler whose HELLO for module "aft" on connection 40 is parked
13990    /// between reserving its registry entry and installing its forwarding
13991    /// endpoint. Returns the handler, the two-party barrier (wait once to know
13992    /// the HELLO is parked, once more to release it), the HELLO's thread, and
13993    /// the module's context and receiver.
13994    fn hello_held_before_forwarding() -> (
13995        ControlHandler,
13996        Arc<std::sync::Barrier>,
13997        std::thread::JoinHandle<Vec<Frame>>,
13998        RouteCtx,
13999        mpsc::Receiver<crate::router::OutboundFrame>,
14000    ) {
14001        let hold = Arc::new(std::sync::Barrier::new(2));
14002        let handler = ControlHandler::with_forwarding(
14003            Arc::new(Registry::default()),
14004            Arc::new(ForwardingTable::default()),
14005        )
14006        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
14007        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14008        let hello = {
14009            let handler = handler.clone();
14010            let module_ctx = module_ctx.clone();
14011            std::thread::spawn(move || {
14012                handler
14013                    .handle_hello(
14014                        module_ctx.connection_id,
14015                        Some(module_ctx.egress.clone()),
14016                        hello_frame("aft", PROTOCOL_VERSION, 7),
14017                    )
14018                    .unwrap()
14019            })
14020        };
14021        (handler, hold, hello, module_ctx, module_rx)
14022    }
14023
14024    /// If a lookup can acquire the registry while publication is parked, let
14025    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
14026    /// after the lookup has tried the lock. Both schedules avoid timing guesses
14027    /// and return the actual lookup result, including an unpublished snapshot
14028    /// when the publication lock is missing.
14029    fn lookup_during_hello_publication<T: Send + 'static>(
14030        registry: &Registry,
14031        hold: &std::sync::Barrier,
14032        lookup: impl FnOnce() -> T + Send + 'static,
14033    ) -> T {
14034        let attempted = registry.observe_next_lock_attempt();
14035        let reader = std::thread::spawn(lookup);
14036        if attempted.recv().unwrap() {
14037            let result = reader.join().unwrap();
14038            hold.wait();
14039            result
14040        } else {
14041            hold.wait();
14042            reader.join().unwrap()
14043        }
14044    }
14045
14046    #[test]
14047    fn catalog_read_after_hello_ack_waits_for_publication() {
14048        let registry = Arc::new(Registry::default());
14049        let hold = Arc::new(std::sync::Barrier::new(2));
14050        let mut handler = ControlHandler::with_forwarding(
14051            Arc::clone(&registry),
14052            Arc::new(ForwardingTable::default()),
14053        );
14054        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
14055        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14056        let hello = {
14057            let handler = handler.clone();
14058            std::thread::spawn(move || {
14059                handler
14060                    .handle_hello(
14061                        module_ctx.connection_id,
14062                        Some(module_ctx.egress),
14063                        hello_frame("aft", PROTOCOL_VERSION, 7),
14064                    )
14065                    .unwrap()
14066            })
14067        };
14068        hold.wait();
14069        assert_eq!(
14070            module_rx.try_recv().unwrap().frame.header.ty,
14071            FrameType::HelloAck
14072        );
14073        let replies = lookup_during_hello_publication(&registry, &hold, move || {
14074            // A different connection can issue catalog.list as soon as the
14075            // module has read its ACK, even while HELLO has not returned.
14076            let request = Frame::build(
14077                FrameType::Request,
14078                control_flags(),
14079                0,
14080                0,
14081                300,
14082                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
14083            )
14084            .unwrap();
14085            handler.handle_catalog_list(request, None).unwrap()
14086        });
14087        assert!(hello.join().unwrap().is_empty());
14088        let ClientControlResponse::CatalogList {
14089            generation,
14090            modules,
14091            ..
14092        } = serde_json::from_slice(&replies[0].body).unwrap()
14093        else {
14094            panic!("not a catalog.list reply");
14095        };
14096        assert_eq!(
14097            modules
14098                .iter()
14099                .map(|entry| entry.module_id.as_str())
14100                .collect::<Vec<_>>(),
14101            vec!["aft"]
14102        );
14103        assert_eq!(generation, 1);
14104    }
14105
14106    /// While a HELLO has reserved its registry entry but its forwarding
14107    /// endpoint is not installed yet, `route.open` to the module can only be
14108    /// refused. `catalog.list` must not list the module in that window: a
14109    /// client that opens a route as soon as it sees a module listed and ready
14110    /// would be refused for a module the daemon had just advertised. The
14111    /// refusal in the window stays the retryable `target_unavailable`, never
14112    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14113    /// Once the HELLO completes, the module is listed and a route to it opens.
14114    #[tokio::test]
14115    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14116        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14117        let client = ConnectionId::new(41);
14118        let (client_ctx, mut client_rx) = route_ctx(client);
14119
14120        hold.wait();
14121        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14122        assert!(handler.registry.get_module("aft").unwrap().is_some());
14123        assert!(!handler
14124            .forwarding
14125            .has_live_module_connection("aft")
14126            .unwrap());
14127        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14128        assert!(
14129            listed.is_empty(),
14130            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14131        );
14132        let refused = handler
14133            .handle_control_frame(
14134                &client_ctx,
14135                route_open_frame(301, "aft", unique_project_root("listed-window")),
14136            )
14137            .await
14138            .unwrap();
14139        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14140        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14141        let duplicate = handler
14142            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14143            .await
14144            .unwrap();
14145        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14146
14147        hold.wait();
14148        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14149        let ack = module_rx.try_recv().unwrap().frame;
14150        assert_eq!(ack.header.ty, FrameType::HelloAck);
14151        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14152        assert_eq!(listed, vec![("aft".to_string(), true)]);
14153
14154        let (open_task, bind) = relay_route_open(
14155            &handler,
14156            client,
14157            &client_ctx.egress,
14158            &mut module_rx,
14159            303,
14160            "aft",
14161            "listed-after",
14162        )
14163        .await;
14164        assert!(handler
14165            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14166            .await
14167            .unwrap()
14168            .is_empty());
14169        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14170        published_route(&client_rx.try_recv().unwrap().frame);
14171    }
14172
14173    /// A catalog watcher keys on the generation: when it changes, it re-reads
14174    /// the listing. So the generation must advance exactly when the module
14175    /// appears. If it advanced while the module was still hidden, a watcher
14176    /// would read the new generation without the module, and the module would
14177    /// later appear under that same generation with nothing telling the
14178    /// watcher to look again.
14179    #[tokio::test]
14180    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14181        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14182        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14183        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14184
14185        hold.wait();
14186        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14187        assert!(listed.is_empty());
14188        assert_eq!(
14189            during, before,
14190            "the generation moved while the module was not listed"
14191        );
14192
14193        hold.wait();
14194        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14195        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14196        assert_eq!(listed, vec![("aft".to_string(), true)]);
14197        assert_eq!(
14198            after,
14199            before + 1,
14200            "the module appeared without exactly one generation bump"
14201        );
14202    }
14203
14204    /// A HELLO whose forwarding endpoint cannot be installed (here the
14205    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14206    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14207    /// and the catalog generation where it was.
14208    #[tokio::test]
14209    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14210        let registry = Arc::new(Registry::default());
14211        let handler = ControlHandler::with_forwarding(
14212            Arc::clone(&registry),
14213            Arc::new(ForwardingTable::default()),
14214        );
14215        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14216        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14217        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14218        drop(module_rx);
14219
14220        let replies = handler
14221            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14222            .await
14223            .unwrap();
14224        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14225        assert!(registry.get_module("aft").unwrap().is_none());
14226        assert!(registry
14227            .get_module_by_connection(module_ctx.connection_id)
14228            .unwrap()
14229            .is_none());
14230        assert_eq!(
14231            catalog_snapshot(&handler, &client_ctx, 301).await,
14232            (before, Vec::new())
14233        );
14234    }
14235
14236    /// A handler whose `route.open` parks after queueing the route.bind and
14237    /// before marking it enqueued, with module "aft" registered on connection
14238    /// 40. Returns the two-party barrier that parks and releases it.
14239    async fn route_open_held_after_bind_send() -> (
14240        ControlHandler,
14241        Arc<tokio::sync::Barrier>,
14242        RouteCtx,
14243        mpsc::Receiver<crate::router::OutboundFrame>,
14244    ) {
14245        let hold = Arc::new(tokio::sync::Barrier::new(2));
14246        let handler = ControlHandler::with_forwarding(
14247            Arc::new(Registry::default()),
14248            Arc::new(ForwardingTable::default()),
14249        )
14250        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14251        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14252        hello_via_sink(
14253            &handler,
14254            &module_ctx,
14255            &mut module_rx,
14256            hello_frame("aft", PROTOCOL_VERSION, 7),
14257        )
14258        .await;
14259        (handler, hold, module_ctx, module_rx)
14260    }
14261
14262    /// A fast module acks the route.bind, and the reader commits the route,
14263    /// before `route.open` has marked the relay enqueued. The daemon used to
14264    /// read the missing relay as an abandoned bind and send the module a
14265    /// GOODBYE for the route it had just committed: the client was told its
14266    /// route was open, the module unbound the channel, and the client's first
14267    /// request was dropped on the module side as unbound.
14268    #[tokio::test]
14269    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14270        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14271        let client = ConnectionId::new(41);
14272        let (client_ctx, mut client_rx) = route_ctx(client);
14273
14274        let (open_task, bind) = relay_route_open(
14275            &handler,
14276            client,
14277            &client_ctx.egress,
14278            &mut module_rx,
14279            200,
14280            "aft",
14281            "acked-before-mark",
14282        )
14283        .await;
14284        let (module_channel, module_epoch) = route_bind_channel(&bind);
14285        // route.open is now parked between queueing the bind and marking it.
14286        hold.wait().await;
14287
14288        // The module answers inside that window, and the route commits.
14289        assert!(handler
14290            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14291            .await
14292            .unwrap()
14293            .is_empty());
14294        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14295
14296        hold.wait().await;
14297        assert!(
14298            open_task.await.unwrap().is_empty(),
14299            "route.open answers accepted"
14300        );
14301
14302        // Every frame route.open could have sent is already queued, because it
14303        // has returned; the module must have been sent nothing.
14304        match module_rx.try_recv() {
14305            Err(mpsc::error::TryRecvError::Empty) => {}
14306            Ok(outbound) => panic!(
14307                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14308                outbound.frame.header.ty,
14309                outbound.frame.header.channel,
14310                outbound.frame.header.epoch
14311            ),
14312            Err(err) => panic!("module egress closed: {err}"),
14313        }
14314
14315        // The client's first request on the route is the next thing the module
14316        // reads, on the binding it just created.
14317        let router = Router::with_control_handler(Arc::new(handler.clone()));
14318        let request = Frame::build(
14319            FrameType::Request,
14320            Flags::new(true, Priority::Interactive, false),
14321            client_channel,
14322            client_epoch,
14323            201,
14324            b"first request".to_vec(),
14325        )
14326        .unwrap();
14327        router
14328            .route_for_connection(&client_ctx, request)
14329            .await
14330            .unwrap();
14331        let delivered = module_rx.try_recv().unwrap().frame;
14332        assert_eq!(delivered.header.ty, FrameType::Request);
14333        assert_eq!(
14334            (delivered.header.channel, delivered.header.epoch),
14335            (module_channel, module_epoch)
14336        );
14337        assert_eq!(delivered.body, b"first request");
14338    }
14339
14340    /// The client goes away while `route.open` is still queueing the bind, so
14341    /// the relay is dropped with no module reply. The teardown cannot send the
14342    /// GOODBYE itself (it could reach the module ahead of the bind), so
14343    /// `route.open` must send it once the bind is queued; otherwise the module
14344    /// keeps a binding the daemon will never commit.
14345    #[tokio::test]
14346    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14347        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14348        let client = ConnectionId::new(42);
14349        let (client_ctx, _client_rx) = route_ctx(client);
14350
14351        let (open_task, bind) = relay_route_open(
14352            &handler,
14353            client,
14354            &client_ctx.egress,
14355            &mut module_rx,
14356            300,
14357            "aft",
14358            "released-before-mark",
14359        )
14360        .await;
14361        let (module_channel, module_epoch) = route_bind_channel(&bind);
14362        hold.wait().await;
14363
14364        handler.cleanup_connection(client).unwrap();
14365        assert!(
14366            module_rx.try_recv().is_err(),
14367            "client teardown must not GOODBYE a bind route.open is still queueing"
14368        );
14369
14370        hold.wait().await;
14371        let response = open_task.await.unwrap();
14372        assert_eq!(response.len(), 1);
14373        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14374
14375        let goodbye = module_rx
14376            .try_recv()
14377            .expect("module is told to drop the binding the daemon abandoned")
14378            .frame;
14379        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14380        assert_eq!(
14381            (goodbye.header.channel, goodbye.header.epoch),
14382            (module_channel, module_epoch)
14383        );
14384        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14385    }
14386
14387    /// The module acks inside the same window, but the client's egress closed
14388    /// first, so the reader refuses to commit. The ack proves the module holds
14389    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14390    /// send a second one.
14391    #[tokio::test]
14392    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14393        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14394        let client = ConnectionId::new(43);
14395        let (client_ctx, client_rx) = route_ctx(client);
14396
14397        let (open_task, bind) = relay_route_open(
14398            &handler,
14399            client,
14400            &client_ctx.egress,
14401            &mut module_rx,
14402            400,
14403            "aft",
14404            "gone-client-before-mark",
14405        )
14406        .await;
14407        let (module_channel, module_epoch) = route_bind_channel(&bind);
14408        hold.wait().await;
14409
14410        drop(client_rx);
14411        assert!(client_ctx.egress.is_closed());
14412        handler
14413            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14414            .await
14415            .unwrap();
14416
14417        hold.wait().await;
14418        let response = open_task.await.unwrap();
14419        assert_eq!(response.len(), 1);
14420        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14421
14422        let goodbye = module_rx
14423            .try_recv()
14424            .expect("module is told to drop the binding it acked")
14425            .frame;
14426        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14427        assert_eq!(
14428            (goodbye.header.channel, goodbye.header.epoch),
14429            (module_channel, module_epoch)
14430        );
14431        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14432        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14433    }
14434
14435    /// The fence at the module-loop boundary, stated as its own contract: which
14436    /// forwarding failures are allowed to end the module connection that is being
14437    /// served. A `ConnectionClosing` naming some client is about that client, and
14438    /// a module connection is shared; the same error naming the module's own
14439    /// connection is about this connection and must stay fatal, as must failures
14440    /// that are about the forwarding table itself.
14441    #[test]
14442    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14443        let handler = ControlHandler::default();
14444        let module_connection = ConnectionId::new(30);
14445        let client_connection = ConnectionId::new(31);
14446
14447        handler
14448            .refuse_to_end_module_connection_for_a_client(
14449                module_connection,
14450                77,
14451                ForwardingError::ConnectionClosing {
14452                    connection_id: client_connection,
14453                },
14454            )
14455            .expect("a closing client must never end the module connection");
14456
14457        assert!(matches!(
14458            handler.refuse_to_end_module_connection_for_a_client(
14459                module_connection,
14460                78,
14461                ForwardingError::ConnectionClosing {
14462                    connection_id: module_connection,
14463                },
14464            ),
14465            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14466                connection_id
14467            })) if connection_id == module_connection
14468        ));
14469        assert!(matches!(
14470            handler.refuse_to_end_module_connection_for_a_client(
14471                module_connection,
14472                79,
14473                ForwardingError::Poisoned,
14474            ),
14475            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14476        ));
14477        assert!(matches!(
14478            handler.refuse_to_end_module_connection_for_a_client(
14479                module_connection,
14480                80,
14481                ForwardingError::StaleModuleEndpoint,
14482            ),
14483            Err(RouterError::Forwarding(
14484                ForwardingError::StaleModuleEndpoint
14485            ))
14486        ));
14487    }
14488
14489    /// The spawn-attestation guard is what stops a connected module from claiming
14490    /// another module's identity and being stamped `Reserved` for it. Every other
14491    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14492    /// correct one is what the rest of the flow needs -- so the guard's rejection
14493    /// branch was never the subject of an assertion, only its acceptance branch.
14494    ///
14495    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14496    /// whole subc-core library suite green; only the forwarding integration tests
14497    /// notice, and they notice for unrelated reasons. This test exists so the
14498    /// refusal itself is asserted where the guard lives: it fails if the identity
14499    /// check stops refusing, which is the direction that matters, since a guard
14500    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14501    #[tokio::test]
14502    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14503        let registry = Arc::new(Registry::default());
14504        let forwarding = Arc::new(ForwardingTable::default());
14505        let supervisor = SupervisorHandle::new();
14506        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14507        let handler =
14508            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14509                .with_supervisor(supervisor);
14510
14511        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14512        hello_via_sink(
14513            &handler,
14514            &target_ctx,
14515            &mut target_rx,
14516            hello_frame("target", PROTOCOL_VERSION, 1),
14517        )
14518        .await;
14519
14520        // A real supervised module id presenting the wrong nonce. This is the
14521        // impersonation case: the attacker knows a privileged module_id, which is
14522        // public, and guesses at the nonce, which is not.
14523        let wrong_nonce = handler
14524            .handle_control_frame(
14525                &route_ctx(ConnectionId::new(91)).0,
14526                route_open_frame_with_admission_facts(
14527                    20,
14528                    "target",
14529                    unique_project_root("admission-facts"),
14530                    Some(subc_control::ConsumerIdentity {
14531                        module_id: "fed".to_string(),
14532                        launch_nonce: "not-the-real-nonce".to_string(),
14533                    }),
14534                    None,
14535                ),
14536            )
14537            .await
14538            .unwrap();
14539        assert_eq!(
14540            parse_error(&wrong_nonce[0])["code"],
14541            "bad_consumer_identity",
14542            "a mismatched launch nonce must be refused, not stamped Reserved"
14543        );
14544
14545        // A module id the supervisor never spawned at all, so no nonce exists to
14546        // compare against. An implementation that treats "no record" as "nothing
14547        // to check" fails open here while passing the case above.
14548        let never_spawned = handler
14549            .handle_control_frame(
14550                &route_ctx(ConnectionId::new(92)).0,
14551                route_open_frame_with_admission_facts(
14552                    21,
14553                    "target",
14554                    unique_project_root("admission-facts"),
14555                    Some(subc_control::ConsumerIdentity {
14556                        module_id: "never-spawned".to_string(),
14557                        launch_nonce: "any-nonce".to_string(),
14558                    }),
14559                    None,
14560                ),
14561            )
14562            .await
14563            .unwrap();
14564        assert_eq!(
14565            parse_error(&never_spawned[0])["code"],
14566            "bad_consumer_identity",
14567            "an unspawned module_id must be refused rather than accepted for lack of a record"
14568        );
14569    }
14570
14571    /// The refusal test above proves the guard says NO. Nothing proved it can say
14572    /// YES, and the difference is not academic: replacing the whole authorization
14573    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14574    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14575    /// library tests GREEN. The one that notices does so by HANGING, because it
14576    /// waits for a bind that can no longer happen.
14577    ///
14578    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14579    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14580    /// hangs too and gets blamed on the runner. So a total revocation of the
14581    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14582    /// to code.
14583    ///
14584    /// The bias is structural rather than accidental. A REFUSAL looks like a
14585    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14586    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14587    /// suite for that reason, and this one is the purest case in the daemon.
14588    ///
14589    /// This test asserts the EFFECT rather than the absence of an error: the module
14590    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14591    /// A guard that admitted nobody would produce no bind at all; one that admitted
14592    /// everybody would stamp the wrong principal, which the refusal test catches.
14593    #[tokio::test]
14594    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14595        let registry = Arc::new(Registry::default());
14596        let forwarding = Arc::new(ForwardingTable::default());
14597        let supervisor = SupervisorHandle::new();
14598        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14599        let handler =
14600            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14601                .with_supervisor(supervisor);
14602
14603        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14604        hello_via_sink(
14605            &handler,
14606            &target_ctx,
14607            &mut target_rx,
14608            hello_frame("target", PROTOCOL_VERSION, 1),
14609        )
14610        .await;
14611
14612        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14613        let route_handler = handler.clone();
14614        let route_task = tokio::spawn(async move {
14615            route_handler
14616                .handle_control_frame(
14617                    &client_ctx,
14618                    route_open_frame_with_admission_facts(
14619                        30,
14620                        "target",
14621                        unique_project_root("admission-facts"),
14622                        Some(subc_control::ConsumerIdentity {
14623                            module_id: "fed".to_string(),
14624                            launch_nonce: "fed-nonce".to_string(),
14625                        }),
14626                        None,
14627                    ),
14628                )
14629                .await
14630                .unwrap()
14631        });
14632
14633        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14634        // the very mutation it exists to catch -- a guard that admits nobody -- no
14635        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14636        // exact defect being fixed: a total revocation detected only as a stalled
14637        // suite, which reads as flakiness and invites a retry. An acceptance test
14638        // that waits for an effect must bound the wait, or a red becomes a hang.
14639        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14640            .await
14641            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14642            .expect("module control channel closed before route.bind");
14643        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14644        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14645            panic!("expected route.bind")
14646        };
14647        assert_eq!(
14648            principal,
14649            Some(Principal::Reserved {
14650                module_id: "fed".to_string()
14651            }),
14652            "a correctly attested consumer must be stamped Reserved for its own id"
14653        );
14654
14655        handler
14656            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14657            .await
14658            .unwrap();
14659        assert!(route_task.await.unwrap().is_empty());
14660        assert!(
14661            matches!(
14662                serde_json::from_slice::<ClientControlResponse>(
14663                    &client_rx.recv().await.unwrap().body
14664                )
14665                .unwrap(),
14666                ClientControlResponse::RouteOpen { .. }
14667            ),
14668            "the route must actually open, not merely avoid an error"
14669        );
14670    }
14671
14672    #[tokio::test(start_paused = true)]
14673    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14674        let registry = Arc::new(Registry::default());
14675        let forwarding = Arc::new(ForwardingTable::default());
14676        let supervisor = SupervisorHandle::new();
14677        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14678        let handler =
14679            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14680                .with_supervisor(supervisor);
14681
14682        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14683        hello_via_sink(
14684            &handler,
14685            &target_ctx,
14686            &mut target_rx,
14687            hello_frame("target", PROTOCOL_VERSION, 1),
14688        )
14689        .await;
14690
14691        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14692        let direct_handler = handler.clone();
14693        let direct_open = tokio::spawn(async move {
14694            direct_handler
14695                .handle_control_frame(
14696                    &direct_ctx,
14697                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14698                )
14699                .await
14700                .unwrap()
14701        });
14702        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14703            .await
14704            .expect("no direct route.bind within 5s")
14705            .expect("target control channel closed before direct route.bind");
14706        handler
14707            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14708            .await
14709            .unwrap();
14710        assert!(direct_open.await.unwrap().is_empty());
14711        let _ = direct_rx.recv().await.unwrap();
14712
14713        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14714        let reserved_handler = handler.clone();
14715        let reserved_open = tokio::spawn(async move {
14716            reserved_handler
14717                .handle_control_frame(
14718                    &reserved_ctx,
14719                    route_open_frame_with_admission_facts(
14720                        3,
14721                        "target",
14722                        unique_project_root("admission-facts"),
14723                        Some(ConsumerIdentity {
14724                            module_id: "fed".to_string(),
14725                            launch_nonce: "fed-nonce".to_string(),
14726                        }),
14727                        None,
14728                    ),
14729                )
14730                .await
14731                .unwrap()
14732        });
14733        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14734            .await
14735            .expect("no reserved route.bind within 5s")
14736            .expect("target control channel closed before reserved route.bind");
14737        handler
14738            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14739            .await
14740            .unwrap();
14741        assert!(reserved_open.await.unwrap().is_empty());
14742        let _ = reserved_rx.recv().await.unwrap();
14743
14744        forwarding
14745            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14746            .unwrap();
14747        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14748        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14749            module_id: Some("target".to_string()),
14750        })
14751        .unwrap();
14752        let census_frame =
14753            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14754        let response = handler
14755            .handle_control_frame(&census_ctx, census_frame)
14756            .await
14757            .unwrap()
14758            .pop()
14759            .unwrap();
14760        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14761        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14762        assert!(matches!(
14763            decoded,
14764            ClientControlResponse::SupervisorRoutes { .. }
14765        ));
14766        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14767        assert_eq!(routes.len(), 2);
14768        assert!(routes.iter().all(|route| route["draining"] == true));
14769        // The census carries WHY: the reason the drain was begun with, in the
14770        // route.closing vocabulary, on every draining route this drain marked.
14771        assert!(
14772            routes.iter().all(|route| route["drain_reason"] == "reload"),
14773            "draining routes must name the drain's reason: {routes:?}"
14774        );
14775        assert!(routes.iter().any(|route| {
14776            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14777        }));
14778        assert!(routes.iter().any(|route| {
14779            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14780        }));
14781
14782        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14783            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14784        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14785            std::fs::write(
14786                &golden_path,
14787                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14788            )
14789            .unwrap();
14790        }
14791        let expected: Value =
14792            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14793        assert_eq!(actual, expected);
14794    }
14795
14796    async fn query_live_roots(
14797        handler: &ControlHandler,
14798        module_ctx: &RouteCtx,
14799    ) -> ModuleControlResponseToModule {
14800        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14801        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14802        let response = handler
14803            .handle_control_frame(module_ctx, frame)
14804            .await
14805            .unwrap()
14806            .pop()
14807            .unwrap();
14808        serde_json::from_slice(&response.body).unwrap()
14809    }
14810
14811    #[tokio::test(start_paused = true)]
14812    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14813        let registry = Arc::new(Registry::default());
14814        let forwarding = Arc::new(ForwardingTable::default());
14815        let handler = ControlHandler::with_forwarding(registry, forwarding);
14816        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14817        hello_via_sink(
14818            &handler,
14819            &target_ctx,
14820            &mut target_rx,
14821            hello_frame("target", PROTOCOL_VERSION, 1),
14822        )
14823        .await;
14824        let root = unique_project_root("live-roots-known");
14825        let path = ProjectRootId::from_path_allowing_missing(root.path())
14826            .unwrap()
14827            .as_path()
14828            .to_path_buf();
14829        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14830        let open_handler = handler.clone();
14831        let opened = tokio::spawn(async move {
14832            open_handler
14833                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14834                .await
14835                .unwrap()
14836        });
14837        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14838            .await
14839            .unwrap()
14840            .unwrap();
14841        handler
14842            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14843            .await
14844            .unwrap();
14845        assert!(opened.await.unwrap().is_empty());
14846        let _ = client_rx.recv().await.unwrap();
14847
14848        let root = unique_project_root("live-roots-pending");
14849        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14850            .unwrap()
14851            .as_path()
14852            .to_path_buf();
14853        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14854        let open_handler = handler.clone();
14855        let pending = tokio::spawn(async move {
14856            open_handler
14857                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14858                .await
14859                .unwrap()
14860        });
14861        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14862            .await
14863            .unwrap()
14864            .unwrap();
14865        let actual = query_live_roots(&handler, &target_ctx).await;
14866        let ModuleControlResponseToModule::LiveRoots {
14867            roots,
14868            unknown_root_bindings,
14869            total_bindings,
14870        } = actual
14871        else {
14872            panic!("expected live roots")
14873        };
14874        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14875        assert_eq!(unknown_root_bindings, 0);
14876        assert_eq!(
14877            roots.len(),
14878            2,
14879            "root-known arm must retain each canonical root"
14880        );
14881        assert_eq!(
14882            total_bindings,
14883            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14884        );
14885        let counts = roots
14886            .iter()
14887            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14888            .collect::<Vec<_>>();
14889        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14890        expected.sort_by(|a, b| a.0.cmp(&b.0));
14891        assert_eq!(
14892            counts, expected,
14893            "roots must sort by path and count pending separately"
14894        );
14895        handler
14896            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14897            .await
14898            .unwrap();
14899        assert!(pending.await.unwrap().is_empty());
14900    }
14901
14902    #[tokio::test(start_paused = true)]
14903    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14904        let forwarding = Arc::new(ForwardingTable::default());
14905        let handler =
14906            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14907        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14908        hello_via_sink(
14909            &handler,
14910            &target_ctx,
14911            &mut target_rx,
14912            hello_frame("target", PROTOCOL_VERSION, 1),
14913        )
14914        .await;
14915        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14916        let pending = forwarding
14917            .begin_route_bind_relay_for_test(
14918                client_ctx.connection_id,
14919                client_ctx.egress.clone(),
14920                2,
14921                "target",
14922            )
14923            .unwrap();
14924        forwarding
14925            .complete_pending_relay(
14926                target_ctx.connection_id,
14927                pending.corr,
14928                RouteBindRelayOutcome::Accepted,
14929            )
14930            .unwrap();
14931        let actual = query_live_roots(&handler, &target_ctx).await;
14932        let ModuleControlResponseToModule::LiveRoots {
14933            roots,
14934            unknown_root_bindings,
14935            total_bindings,
14936        } = actual
14937        else {
14938            panic!("expected live roots")
14939        };
14940        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14941        assert_eq!(
14942            unknown_root_bindings, 1,
14943            "unknown-root arm must not read as no bindings"
14944        );
14945        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14946        assert_eq!(
14947            total_bindings,
14948            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14949        );
14950    }
14951
14952    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14953    /// so the ack has to be on its outbound queue before the module is
14954    /// routable. The connection loop writes a handler's replies only after the
14955    /// handler returns; this test stops in exactly that gap, runs a real
14956    /// route.open from another connection, and only then writes whatever the
14957    /// HELLO handler returned, the way the loop would. If the ack were still a
14958    /// reply, the route.bind request would reach the module first.
14959    #[tokio::test(start_paused = true)]
14960    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14961        let forwarding = Arc::new(ForwardingTable::default());
14962        let handler =
14963            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14964        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14965        let replies = handler
14966            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14967            .await
14968            .unwrap();
14969        let queued_by_hello = module_rx.len();
14970
14971        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14972        let open_handler = handler.clone();
14973        let open = tokio::spawn(async move {
14974            open_handler
14975                .handle_control_frame(
14976                    &client_ctx,
14977                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14978                )
14979                .await
14980                .unwrap()
14981        });
14982        // Let the route.open run until its route.bind is on the module's queue.
14983        let mut spins = 0;
14984        while module_rx.len() == queued_by_hello {
14985            spins += 1;
14986            assert!(spins < 10_000, "route.open never queued a route.bind");
14987            tokio::task::yield_now().await;
14988        }
14989
14990        // Now the connection loop's half: write the HELLO handler's replies.
14991        for reply in replies {
14992            module_ctx.egress.send(reply).await.unwrap();
14993        }
14994
14995        let first = module_rx.recv().await.unwrap().frame;
14996        assert_eq!(
14997            first.header.ty,
14998            FrameType::HelloAck,
14999            "the first frame a registering module reads must be its HELLO_ACK"
15000        );
15001        assert_eq!(first.header.corr, 7);
15002        let second = module_rx.recv().await.unwrap().frame;
15003        assert_eq!(second.header.ty, FrameType::Request);
15004        assert!(
15005            matches!(
15006                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
15007                ModuleControlRequest::RouteBind { .. }
15008            ),
15009            "the route.bind follows the ack"
15010        );
15011        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
15012
15013        handler
15014            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
15015            .await
15016            .unwrap();
15017        assert!(open.await.unwrap().is_empty());
15018        let _ = client_rx.recv().await.unwrap();
15019    }
15020
15021    #[tokio::test(start_paused = true)]
15022    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
15023        let handler = ControlHandler::with_forwarding(
15024            Arc::new(Registry::default()),
15025            Arc::new(ForwardingTable::default()),
15026        );
15027        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
15028        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
15029        hello_via_sink(
15030            &handler,
15031            &first_ctx,
15032            &mut first_rx,
15033            hello_frame("first", PROTOCOL_VERSION, 1),
15034        )
15035        .await;
15036        hello_via_sink(
15037            &handler,
15038            &second_ctx,
15039            &mut second_rx,
15040            hello_frame("second", PROTOCOL_VERSION, 2),
15041        )
15042        .await;
15043        let root = unique_project_root("second-only");
15044        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
15045        let cloned = handler.clone();
15046        let open = tokio::spawn(async move {
15047            cloned
15048                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
15049                .await
15050                .unwrap()
15051        });
15052        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
15053            .await
15054            .unwrap()
15055            .unwrap();
15056        let first = query_live_roots(&handler, &first_ctx).await;
15057        let second = query_live_roots(&handler, &second_ctx).await;
15058        assert!(
15059            matches!(
15060                first,
15061                ModuleControlResponseToModule::LiveRoots {
15062                    total_bindings: 0,
15063                    ..
15064                }
15065            ),
15066            "cross-module scope must not expose another module's roots"
15067        );
15068        assert!(
15069            matches!(
15070                second,
15071                ModuleControlResponseToModule::LiveRoots {
15072                    total_bindings: 1,
15073                    ..
15074                }
15075            ),
15076            "second module must see its pending route"
15077        );
15078        handler
15079            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
15080            .await
15081            .unwrap();
15082        assert!(open.await.unwrap().is_empty());
15083    }
15084
15085    #[tokio::test(start_paused = true)]
15086    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
15087        let handler = ControlHandler::with_forwarding(
15088            Arc::new(Registry::default()),
15089            Arc::new(ForwardingTable::default()),
15090        );
15091        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15092        hello_via_sink(
15093            &handler,
15094            &target_ctx,
15095            &mut target_rx,
15096            hello_frame("target", PROTOCOL_VERSION, 1),
15097        )
15098        .await;
15099        let actual = query_live_roots(&handler, &target_ctx).await;
15100        let ModuleControlResponseToModule::LiveRoots {
15101            roots,
15102            unknown_root_bindings,
15103            total_bindings,
15104        } = actual
15105        else {
15106            panic!("expected live roots")
15107        };
15108        assert!(roots.is_empty());
15109        assert_eq!(unknown_root_bindings, 0);
15110        assert_eq!(total_bindings, 0);
15111        assert_eq!(
15112            total_bindings,
15113            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15114        );
15115    }
15116
15117    /// Read the vendored fed corpus rather than hand-building a package.
15118    ///
15119    /// A hand-built object encodes what the test author believed the carrier
15120    /// emits. These vectors are what it actually emits, and one of them exists
15121    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15122    /// ignores additive unknown fields at the traversal emit terminus."
15123    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15124        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15125            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15126        let text = std::fs::read_to_string(&path)
15127            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15128        let vectors: Vec<(String, Value)> = text
15129            .lines()
15130            .filter(|line| !line.trim().is_empty())
15131            .map(|line| {
15132                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15133                let id = entry["corpus_id"]
15134                    .as_str()
15135                    .expect("every vector carries a corpus_id")
15136                    .to_string();
15137                (id, entry["package"].clone())
15138            })
15139            .collect();
15140        // Pin the count: a corpus that silently shrinks would take its coverage
15141        // with it, and a suite reading N-1 vectors reports the same clean pass
15142        // as one reading N.
15143        assert_eq!(
15144            vectors.len(),
15145            3,
15146            "vendored fed corpus changed size; re-sync from subc-federation"
15147        );
15148
15149        // Pin what makes the corpus DISCRIMINATING, not just present.
15150        //
15151        // The relay test below takes its expected value from the corpus, so the
15152        // corpus supplies the test's power to detect a lossy relay rather than
15153        // its correctness. A relay that dropped unrecognised fields would still
15154        // be caught -- but only by a package carrying fields it does not know.
15155        // Shrink every package to the handful of keys any implementation would
15156        // recognise and the test keeps passing over an input that can no longer
15157        // fail, which is the same clean green as a corpus that shrank away.
15158        //
15159        // So assert the precondition rather than duplicating the packages here:
15160        // at least one vector must carry a field beyond the small common set.
15161        // That is one claim to maintain instead of nine, and it fails loudly if
15162        // a re-sync ever flattens the corpus.
15163        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15164        let richest = vectors
15165            .iter()
15166            .filter_map(|(_, package)| package.as_object())
15167            .map(|object| {
15168                object
15169                    .keys()
15170                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15171                    .count()
15172            })
15173            .max()
15174            .unwrap_or(0);
15175        assert!(
15176            richest >= 2,
15177            "vendored corpus no longer carries a package with unmodelled fields, \
15178             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15179        );
15180
15181        vectors
15182    }
15183
15184    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15185    ///
15186    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15187    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15188    /// three-key object, so a relay that quietly dropped fields it did not
15189    /// recognise would satisfy it. These vectors carry nine keys including ones
15190    /// this crate has no type for, so a typed relay fails here and only here.
15191    #[tokio::test]
15192    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15193        for (corpus_id, package) in fed_admission_facts_vectors() {
15194            let registry = Arc::new(Registry::default());
15195            let forwarding = Arc::new(ForwardingTable::default());
15196            let supervisor = SupervisorHandle::new();
15197            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15198            let handler =
15199                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15200                    .with_supervisor(supervisor)
15201                    .with_admission_facts_config(
15202                        Some("fed".to_string()),
15203                        Some(vec!["target".to_string()]),
15204                    );
15205
15206            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15207            hello_via_sink(
15208                &handler,
15209                &target_ctx,
15210                &mut target_rx,
15211                hello_frame("target", PROTOCOL_VERSION, 1),
15212            )
15213            .await;
15214
15215            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15216            let route_handler = handler.clone();
15217            let expected = package.clone();
15218            let route_task = tokio::spawn(async move {
15219                route_handler
15220                    .handle_control_frame(
15221                        &client_ctx,
15222                        route_open_frame_with_admission_facts(
15223                            20,
15224                            "target",
15225                            unique_project_root("admission-facts"),
15226                            Some(subc_control::ConsumerIdentity {
15227                                module_id: "fed".to_string(),
15228                                launch_nonce: "fed-nonce".to_string(),
15229                            }),
15230                            Some(package),
15231                        ),
15232                    )
15233                    .await
15234                    .unwrap()
15235            });
15236
15237            let bind_frame = target_rx.recv().await.unwrap();
15238            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15239            let ModuleControlRequest::RouteBind {
15240                admission_facts, ..
15241            } = bind
15242            else {
15243                panic!("{corpus_id}: expected route.bind")
15244            };
15245            assert_eq!(
15246                admission_facts,
15247                Some(expected),
15248                "{corpus_id}: relay must not add, drop or reshape any field"
15249            );
15250
15251            handler
15252                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15253                .await
15254                .unwrap();
15255            route_task.await.unwrap();
15256        }
15257    }
15258
15259    #[tokio::test]
15260    async fn route_bind_never_relays_the_openers_build_class() {
15261        let registry = Arc::new(Registry::default());
15262        let forwarding = Arc::new(ForwardingTable::default());
15263        let handler =
15264            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15265        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15266        hello_via_sink(
15267            &handler,
15268            &target_ctx,
15269            &mut target_rx,
15270            hello_frame("target", PROTOCOL_VERSION, 1),
15271        )
15272        .await;
15273
15274        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15275        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15276        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15277            busy_refusals: None,
15278            target: RouteTarget::ToolProvider {
15279                module_id: "target".to_string(),
15280            },
15281            identity,
15282            consumer_identity: None,
15283            consumer_capabilities: None,
15284            role_versions: None,
15285            admission_facts: None,
15286            scope: None,
15287        })
15288        .unwrap();
15289        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15290
15291        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15292        let route_handler = handler.clone();
15293        let route_task = tokio::spawn(async move {
15294            route_handler
15295                .handle_control_frame(&client_ctx, open)
15296                .await
15297                .unwrap()
15298        });
15299        let bind_frame = target_rx.recv().await.unwrap();
15300        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15301        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15302            panic!("expected route.bind")
15303        };
15304        assert_eq!(
15305            identity.build_class, None,
15306            "route.bind carried the build class"
15307        );
15308        assert!(
15309            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15310            "the route.bind bytes still name build_class"
15311        );
15312        handler
15313            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15314            .await
15315            .unwrap();
15316        route_task.await.unwrap();
15317    }
15318
15319    #[tokio::test]
15320    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15321        let registry = Arc::new(Registry::default());
15322        let forwarding = Arc::new(ForwardingTable::default());
15323        let supervisor = SupervisorHandle::new();
15324        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15325        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15326        let handler =
15327            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15328                .with_supervisor(supervisor)
15329                .with_admission_facts_config(
15330                    Some("fed".to_string()),
15331                    Some(vec!["target".to_string()]),
15332                );
15333
15334        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15335        hello_via_sink(
15336            &handler,
15337            &target_ctx,
15338            &mut target_rx,
15339            hello_frame("target", PROTOCOL_VERSION, 1),
15340        )
15341        .await;
15342        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15343        hello_via_sink(
15344            &handler,
15345            &other_ctx,
15346            &mut other_rx,
15347            hello_frame("other", PROTOCOL_VERSION, 2),
15348        )
15349        .await;
15350
15351        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15352        let expected_facts = facts.clone();
15353        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15354        let route_handler = handler.clone();
15355        let route_task = tokio::spawn(async move {
15356            route_handler
15357                .handle_control_frame(
15358                    &client_ctx,
15359                    route_open_frame_with_admission_facts(
15360                        10,
15361                        "target",
15362                        unique_project_root("admission-facts"),
15363                        Some(subc_control::ConsumerIdentity {
15364                            module_id: "fed".to_string(),
15365                            launch_nonce: "fed-nonce".to_string(),
15366                        }),
15367                        Some(facts.clone()),
15368                    ),
15369                )
15370                .await
15371                .unwrap()
15372        });
15373        let bind_frame = target_rx.recv().await.unwrap();
15374        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15375        let ModuleControlRequest::RouteBind {
15376            admission_facts, ..
15377        } = bind
15378        else {
15379            panic!("expected route.bind")
15380        };
15381        assert_eq!(admission_facts, Some(expected_facts));
15382        handler
15383            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15384            .await
15385            .unwrap();
15386        assert!(route_task.await.unwrap().is_empty());
15387        assert!(matches!(
15388            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15389                .unwrap(),
15390            ClientControlResponse::RouteOpen { .. }
15391        ));
15392
15393        let direct = handler
15394            .handle_control_frame(
15395                &route_ctx(ConnectionId::new(73)).0,
15396                route_open_frame_with_admission_facts(
15397                    11,
15398                    "target",
15399                    unique_project_root("admission-facts"),
15400                    None,
15401                    Some(json!({"x": 1})),
15402                ),
15403            )
15404            .await
15405            .unwrap();
15406        assert_eq!(
15407            parse_error(&direct[0])["code"],
15408            "admission_facts_not_permitted"
15409        );
15410
15411        let different_reserved = handler
15412            .handle_control_frame(
15413                &route_ctx(ConnectionId::new(77)).0,
15414                route_open_frame_with_admission_facts(
15415                    15,
15416                    "target",
15417                    unique_project_root("admission-facts"),
15418                    Some(subc_control::ConsumerIdentity {
15419                        module_id: "other".to_string(),
15420                        launch_nonce: "other-nonce".to_string(),
15421                    }),
15422                    Some(json!({"x": 1})),
15423                ),
15424            )
15425            .await
15426            .unwrap();
15427        assert_eq!(
15428            parse_error(&different_reserved[0])["code"],
15429            "admission_facts_not_permitted"
15430        );
15431
15432        let other_target = handler
15433            .handle_control_frame(
15434                &route_ctx(ConnectionId::new(74)).0,
15435                route_open_frame_with_admission_facts(
15436                    12,
15437                    "other",
15438                    unique_project_root("admission-facts"),
15439                    Some(subc_control::ConsumerIdentity {
15440                        module_id: "fed".to_string(),
15441                        launch_nonce: "fed-nonce".to_string(),
15442                    }),
15443                    Some(json!({"x": 1})),
15444                ),
15445            )
15446            .await
15447            .unwrap();
15448        assert_eq!(
15449            parse_error(&other_target[0])["code"],
15450            "admission_facts_target_not_allowed"
15451        );
15452
15453        let nonexistent = handler
15454            .handle_control_frame(
15455                &route_ctx(ConnectionId::new(75)).0,
15456                route_open_frame_with_admission_facts(
15457                    13,
15458                    "missing",
15459                    unique_project_root("admission-facts"),
15460                    None,
15461                    Some(json!({"x": 1})),
15462                ),
15463            )
15464            .await
15465            .unwrap();
15466        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15467
15468        let described = handler
15469            .handle_control_frame(
15470                &route_ctx(ConnectionId::new(76)).0,
15471                Frame::build(
15472                    FrameType::Request,
15473                    control_flags(),
15474                    0,
15475                    0,
15476                    14,
15477                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15478                )
15479                .unwrap(),
15480            )
15481            .await
15482            .unwrap();
15483        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15484            serde_json::from_slice(&described[0].body).unwrap()
15485        else {
15486            panic!("expected server.describe response")
15487        };
15488        assert!(capabilities
15489            .iter()
15490            .any(|cap| cap == "admission_facts_relay_v1"));
15491    }
15492
15493    #[tokio::test]
15494    async fn admission_facts_without_configured_carrier_are_rejected() {
15495        let registry = Arc::new(Registry::default());
15496        let forwarding = Arc::new(ForwardingTable::default());
15497        let handler = ControlHandler::with_forwarding(registry, forwarding);
15498        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15499        hello_via_sink(
15500            &handler,
15501            &target_ctx,
15502            &mut target_rx,
15503            hello_frame("target", PROTOCOL_VERSION, 1),
15504        )
15505        .await;
15506
15507        let responses = handler
15508            .handle_control_frame(
15509                &route_ctx(ConnectionId::new(79)).0,
15510                route_open_frame_with_admission_facts(
15511                    16,
15512                    "target",
15513                    unique_project_root("admission-facts"),
15514                    None,
15515                    Some(json!({"x": 1})),
15516                ),
15517            )
15518            .await
15519            .unwrap();
15520        assert_eq!(
15521            parse_error(&responses[0])["code"],
15522            "admission_facts_not_permitted"
15523        );
15524    }
15525
15526    #[tokio::test]
15527    async fn route_open_relays_consumer_capabilities_verbatim() {
15528        let registry = Arc::new(Registry::default());
15529        let forwarding = Arc::new(ForwardingTable::default());
15530        let handler =
15531            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15532        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15533        hello_via_sink(
15534            &handler,
15535            &module_ctx,
15536            &mut module_rx,
15537            hello_frame("aft", PROTOCOL_VERSION, 7),
15538        )
15539        .await;
15540
15541        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15542        let expected_for_request = expected.clone();
15543        let project_root = unique_project_root("consumer-capabilities-present");
15544        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15545        let route_handler = handler.clone();
15546        let route_task = tokio::spawn(async move {
15547            route_handler
15548                .handle_control_frame(
15549                    &client_ctx,
15550                    route_open_frame_with_consumer_capabilities(
15551                        401,
15552                        "aft",
15553                        project_root,
15554                        Some(expected_for_request),
15555                    ),
15556                )
15557                .await
15558                .unwrap()
15559        });
15560        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15561            .await
15562            .unwrap()
15563            .unwrap();
15564        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15565        let ModuleControlRequest::RouteBind {
15566            consumer_capabilities,
15567            ..
15568        } = bind
15569        else {
15570            panic!("expected route.bind request, got {bind:?}");
15571        };
15572        assert_eq!(consumer_capabilities, Some(expected.clone()));
15573
15574        handler
15575            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15576            .await
15577            .unwrap();
15578        let route_response = route_task.await.unwrap();
15579        assert!(route_response.is_empty());
15580        let published = client_rx.recv().await.unwrap();
15581        assert!(matches!(
15582            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15583            ClientControlResponse::RouteOpen { .. }
15584        ));
15585    }
15586
15587    #[tokio::test]
15588    async fn route_open_without_consumer_capabilities_relays_none() {
15589        let registry = Arc::new(Registry::default());
15590        let forwarding = Arc::new(ForwardingTable::default());
15591        let handler =
15592            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15593        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15594        hello_via_sink(
15595            &handler,
15596            &module_ctx,
15597            &mut module_rx,
15598            hello_frame("aft", PROTOCOL_VERSION, 7),
15599        )
15600        .await;
15601
15602        let project_root = unique_project_root("consumer-capabilities-absent");
15603        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15604        let route_handler = handler.clone();
15605        let route_task = tokio::spawn(async move {
15606            route_handler
15607                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15608                .await
15609                .unwrap()
15610        });
15611        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15612            .await
15613            .unwrap()
15614            .unwrap();
15615        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15616        let ModuleControlRequest::RouteBind {
15617            consumer_capabilities,
15618            ..
15619        } = bind
15620        else {
15621            panic!("expected route.bind request, got {bind:?}");
15622        };
15623        assert_eq!(consumer_capabilities, None);
15624
15625        handler
15626            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15627            .await
15628            .unwrap();
15629        let route_response = route_task.await.unwrap();
15630        assert!(route_response.is_empty());
15631        let published = client_rx.recv().await.unwrap();
15632        assert!(matches!(
15633            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15634            ClientControlResponse::RouteOpen { .. }
15635        ));
15636    }
15637
15638    /// Opens a route to a freshly registered `aft` with `sent` as the
15639    /// route.open's role_versions, acks the bind, and returns the role_versions
15640    /// the module's bind carried.
15641    async fn bind_role_versions_for(
15642        sent: Option<BTreeMap<String, String>>,
15643        connection: u64,
15644    ) -> Option<BTreeMap<String, String>> {
15645        let registry = Arc::new(Registry::default());
15646        let forwarding = Arc::new(ForwardingTable::default());
15647        let handler =
15648            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15649        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15650        hello_via_sink(
15651            &handler,
15652            &module_ctx,
15653            &mut module_rx,
15654            hello_frame("aft", PROTOCOL_VERSION, 7),
15655        )
15656        .await;
15657        let project_root = unique_project_root("role-versions");
15658        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15659        let route_handler = handler.clone();
15660        let route_task = tokio::spawn(async move {
15661            route_handler
15662                .handle_control_frame(
15663                    &client_ctx,
15664                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15665                )
15666                .await
15667                .unwrap()
15668        });
15669        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15670            .await
15671            .expect("a well-formed route.open reaches the module as a bind")
15672            .unwrap();
15673        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15674        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15675            panic!("expected route.bind request, got {bind:?}");
15676        };
15677        handler
15678            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15679            .await
15680            .unwrap();
15681        assert!(route_task.await.unwrap().is_empty());
15682        let published = client_rx.recv().await.unwrap();
15683        assert!(matches!(
15684            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15685            ClientControlResponse::RouteOpen { .. }
15686        ));
15687        role_versions
15688    }
15689
15690    #[tokio::test]
15691    async fn route_open_relays_role_versions_verbatim() {
15692        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15693        assert_eq!(
15694            bind_role_versions_for(Some(sent.clone()), 141).await,
15695            Some(sent)
15696        );
15697    }
15698
15699    /// An empty map declares nothing, so the provider sees no field rather
15700    /// than an empty object it would have to treat as a second "none".
15701    #[tokio::test]
15702    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15703        assert_eq!(bind_role_versions_for(None, 143).await, None);
15704        assert_eq!(
15705            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15706            None
15707        );
15708    }
15709
15710    #[tokio::test]
15711    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15712        let registry = Arc::new(Registry::default());
15713        let forwarding = Arc::new(ForwardingTable::default());
15714        let handler =
15715            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15716        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15717        hello_via_sink(
15718            &handler,
15719            &module_ctx,
15720            &mut module_rx,
15721            hello_frame("aft", PROTOCOL_VERSION, 7),
15722        )
15723        .await;
15724
15725        let nine: BTreeMap<String, String> = (0..9)
15726            .map(|index| (format!("role-{index}"), "v1".to_string()))
15727            .collect();
15728        for (label, malformed) in [
15729            (
15730                "invalid role name",
15731                role_versions(&[("Tool_Provider", "v1")]),
15732            ),
15733            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15734            ("nine entries", nine),
15735        ] {
15736            // A refused open answers at once; one that reached the module
15737            // would wait for its bind ack and trip this timeout.
15738            let responses = tokio::time::timeout(
15739                Duration::from_secs(1),
15740                handler.handle_control_frame(
15741                    &route_ctx(ConnectionId::new(148)).0,
15742                    route_open_frame_with_role_versions(
15743                        404,
15744                        "aft",
15745                        unique_project_root("role-versions-malformed"),
15746                        Some(malformed),
15747                    ),
15748                ),
15749            )
15750            .await
15751            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15752            .unwrap();
15753            assert_eq!(responses.len(), 1, "{label}");
15754            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15755            let error = parse_error(&responses[0]);
15756            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15757            assert_eq!(
15758                error["detail"]["field"], "role_versions",
15759                "{label}: {error}"
15760            );
15761            assert!(
15762                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15763                "{label}: a malformed declaration is terminal"
15764            );
15765            assert!(
15766                module_rx.try_recv().is_err(),
15767                "{label}: the module must never see a bind"
15768            );
15769        }
15770    }
15771
15772    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15773    /// consumer can tell this daemon forwards the field from one that would
15774    /// drop it.
15775    #[tokio::test]
15776    async fn route_role_versions_capability_is_advertised() {
15777        let handler = ControlHandler::new(Arc::new(Registry::default()));
15778        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15779        let ack = hello_via_sink(
15780            &handler,
15781            &ctx,
15782            &mut rx,
15783            hello_frame("m", PROTOCOL_VERSION, 1),
15784        )
15785        .await;
15786        let ack = parse_ack(&ack);
15787        assert!(
15788            ack.subc_capabilities
15789                .iter()
15790                .any(|c| c == "route-role-versions/v1"),
15791            "{:?}",
15792            ack.subc_capabilities
15793        );
15794
15795        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15796        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15797        let reply = handler
15798            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15799            .await
15800            .unwrap()
15801            .pop()
15802            .unwrap();
15803        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15804            serde_json::from_slice(&reply.body).unwrap()
15805        else {
15806            panic!("not a server.describe reply");
15807        };
15808        assert!(
15809            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15810            "{capabilities:?}"
15811        );
15812    }
15813
15814    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15815    /// catalog entry without `events` (the module declares none) from a daemon
15816    /// that never reports declared events.
15817    #[tokio::test]
15818    async fn catalog_events_capability_is_advertised() {
15819        let handler = ControlHandler::new(Arc::new(Registry::default()));
15820        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15821        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15822        let reply = handler
15823            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
15824            .await
15825            .unwrap()
15826            .pop()
15827            .unwrap();
15828        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15829            serde_json::from_slice(&reply.body).unwrap()
15830        else {
15831            panic!("not a server.describe reply");
15832        };
15833        assert!(
15834            capabilities
15835                .iter()
15836                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
15837            "{capabilities:?}"
15838        );
15839    }
15840
15841    #[tokio::test]
15842    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15843        let handler = ControlHandler::new(Arc::new(Registry::default()));
15844        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15845        let ack = hello_via_sink(
15846            &handler,
15847            &module,
15848            &mut module_rx,
15849            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15850        )
15851        .await;
15852        let ack = parse_ack(&ack);
15853        assert!(
15854            ack.subc_capabilities
15855                .iter()
15856                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15857            "{:?}",
15858            ack.subc_capabilities
15859        );
15860        assert!(ack
15861            .subc_capabilities
15862            .iter()
15863            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15864
15865        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15866        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15867        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15868        let reply = handler
15869            .handle_control_frame(&client, frame)
15870            .await
15871            .unwrap()
15872            .pop()
15873            .unwrap();
15874        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15875            serde_json::from_slice(&reply.body).unwrap()
15876        else {
15877            panic!("not a server.describe reply");
15878        };
15879        assert!(
15880            capabilities
15881                .iter()
15882                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15883            "{capabilities:?}"
15884        );
15885        assert!(capabilities
15886            .iter()
15887            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15888    }
15889
15890    #[tokio::test]
15891    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15892        let handler = ControlHandler::new(Arc::new(Registry::default()));
15893        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15894        let ack = hello_via_sink(
15895            &handler,
15896            &module,
15897            &mut rx,
15898            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15899        )
15900        .await;
15901        assert!(parse_ack(&ack)
15902            .subc_capabilities
15903            .iter()
15904            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15905        assert!(parse_ack(&ack)
15906            .subc_capabilities
15907            .iter()
15908            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15909        assert!(parse_ack(&ack)
15910            .subc_capabilities
15911            .iter()
15912            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15913        let (client, _rx) = route_ctx(ConnectionId::new(157));
15914        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15915        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15916        let reply = handler
15917            .handle_control_frame(&client, frame)
15918            .await
15919            .unwrap()
15920            .pop()
15921            .unwrap();
15922        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15923            serde_json::from_slice(&reply.body).unwrap()
15924        else {
15925            panic!("server.describe reply")
15926        };
15927        assert!(capabilities
15928            .iter()
15929            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15930        assert!(capabilities
15931            .iter()
15932            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15933        assert!(capabilities
15934            .iter()
15935            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15936    }
15937
15938    #[tokio::test]
15939    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15940        let handler = ControlHandler::new(Arc::new(Registry::default()));
15941        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15942        let ack = hello_via_sink(
15943            &handler,
15944            &module,
15945            &mut rx,
15946            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15947        )
15948        .await;
15949        assert!(parse_ack(&ack)
15950            .subc_capabilities
15951            .iter()
15952            .any(|cap| cap == "scope-workdir/v1"));
15953        let (client, _rx) = route_ctx(ConnectionId::new(159));
15954        let frame = Frame::build(
15955            FrameType::Request,
15956            control_flags(),
15957            0,
15958            0,
15959            5,
15960            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15961        )
15962        .unwrap();
15963        let reply = handler
15964            .handle_control_frame(&client, frame)
15965            .await
15966            .unwrap()
15967            .remove(0);
15968        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15969            serde_json::from_slice(&reply.body).unwrap()
15970        else {
15971            panic!("server.describe reply")
15972        };
15973        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15974    }
15975
15976    #[tokio::test]
15977    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15978        let handler = ControlHandler::new(Arc::new(Registry::default()));
15979        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15980        let ack = hello_via_sink(
15981            &handler,
15982            &module,
15983            &mut rx,
15984            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15985        )
15986        .await;
15987        assert!(parse_ack(&ack)
15988            .subc_capabilities
15989            .iter()
15990            .any(|cap| cap == "worker-runs/v1"));
15991        let (client, _rx) = route_ctx(ConnectionId::new(161));
15992        let frame = Frame::build(
15993            FrameType::Request,
15994            control_flags(),
15995            0,
15996            0,
15997            5,
15998            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15999        )
16000        .unwrap();
16001        let reply = handler
16002            .handle_control_frame(&client, frame)
16003            .await
16004            .unwrap()
16005            .remove(0);
16006        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16007            serde_json::from_slice(&reply.body).unwrap()
16008        else {
16009            panic!("server.describe reply")
16010        };
16011        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
16012    }
16013
16014    #[tokio::test]
16015    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
16016        let handler = ControlHandler::new(Arc::new(Registry::default()));
16017        let (module, mut rx) = route_ctx(ConnectionId::new(154));
16018        let ack = hello_via_sink(
16019            &handler,
16020            &module,
16021            &mut rx,
16022            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
16023        )
16024        .await;
16025        assert!(parse_ack(&ack)
16026            .subc_capabilities
16027            .iter()
16028            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16029        let (client, _rx) = route_ctx(ConnectionId::new(155));
16030        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16031        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16032        let reply = handler
16033            .handle_control_frame(&client, frame)
16034            .await
16035            .unwrap()
16036            .pop()
16037            .unwrap();
16038        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16039            serde_json::from_slice(&reply.body).unwrap()
16040        else {
16041            panic!("not a server.describe reply")
16042        };
16043        assert!(capabilities
16044            .iter()
16045            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16046    }
16047
16048    #[tokio::test]
16049    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
16050        let registry = Arc::new(Registry::default());
16051        let forwarding = Arc::new(ForwardingTable::default());
16052        let handler =
16053            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
16054                .with_health_probe_timeout(Duration::from_secs(5));
16055        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
16056        hello_via_sink(
16057            &handler,
16058            &module_ctx,
16059            &mut module_rx,
16060            non_routable_hello_frame_with_control_ops(
16061                "mcp",
16062                300,
16063                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
16064            ),
16065        )
16066        .await;
16067        assert!(registry
16068            .get_module("mcp")
16069            .unwrap()
16070            .unwrap()
16071            .manifest
16072            .provides
16073            .is_empty());
16074
16075        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
16076        let route_response = handler
16077            .handle_control_frame(
16078                &route_client_ctx,
16079                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
16080            )
16081            .await
16082            .unwrap();
16083        assert_eq!(route_response[0].header.ty, FrameType::Error);
16084        assert_eq!(
16085            parse_error(&route_response[0])["code"],
16086            "target_unavailable"
16087        );
16088        assert!(parse_error(&route_response[0])["message"]
16089            .as_str()
16090            .unwrap()
16091            .contains("does not provide the requested target"));
16092        assert!(module_rx.try_recv().is_err());
16093
16094        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16095        let health_handler = handler.clone();
16096        let health_task = tokio::spawn(async move {
16097            health_handler
16098                .handle_control_frame(
16099                    &health_client_ctx,
16100                    supervisor_health_probe_frame(302, "mcp"),
16101                )
16102                .await
16103                .unwrap()
16104        });
16105        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16106            .await
16107            .unwrap()
16108            .unwrap();
16109        assert_eq!(
16110            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16111            ModuleControlRequest::HealthCheck {}
16112        );
16113        handler
16114            .handle_control_frame(
16115                &module_ctx,
16116                health_response(health_frame.header.corr, HealthStatus::Ok),
16117            )
16118            .await
16119            .unwrap();
16120        let health_response = health_task.await.unwrap();
16121        assert_eq!(health_response[0].header.ty, FrameType::Response);
16122        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16123            ClientControlResponse::SupervisorHealthProbe {
16124                module_id, status, ..
16125            } => {
16126                assert_eq!(module_id, "mcp");
16127                assert_eq!(status, HealthStatus::Ok);
16128            }
16129            other => panic!("unexpected health response: {other:?}"),
16130        }
16131
16132        // Exercise the forwarding cleanup path directly while leaving the registry
16133        // advertisement in place. If cleanup leaves a stale control sink behind,
16134        // the next probe will enqueue onto it and wait for the long probe timeout
16135        // instead of returning an immediate no-connection error.
16136        forwarding
16137            .cleanup_connection(module_ctx.connection_id)
16138            .unwrap();
16139        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16140        let cleanup_response = tokio::time::timeout(
16141            Duration::from_millis(200),
16142            handler.handle_control_frame(
16143                &cleanup_probe_ctx,
16144                supervisor_health_probe_frame(303, "mcp"),
16145            ),
16146        )
16147        .await
16148        .expect("probe should fail immediately when the control lane is gone")
16149        .unwrap();
16150        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16151        assert_eq!(
16152            parse_error(&cleanup_response[0])["code"],
16153            "target_unavailable"
16154        );
16155        assert!(parse_error(&cleanup_response[0])["message"]
16156            .as_str()
16157            .unwrap()
16158            .contains("no module connection"));
16159
16160        handler
16161            .cleanup_connection(module_ctx.connection_id)
16162            .unwrap();
16163    }
16164
16165    #[tokio::test]
16166    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16167        let registry = Arc::new(Registry::default());
16168        let supervisor_handle = SupervisorHandle::new();
16169        let supervisor =
16170            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16171                .with_handle(supervisor_handle.clone())
16172                .with_connection_file_path(
16173                    std::env::temp_dir()
16174                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16175                );
16176        let module = supervisor
16177            .supervise_configured(
16178                ModuleSpec {
16179                    script: None,
16180                    carry_containment: false,
16181                    module_id: "warming".to_string(),
16182                    program: fake_aft_stub_path(),
16183                    args: Vec::new(),
16184                    env: Vec::new(),
16185                    reserved: false,
16186                    reserved_prefixes: Vec::new(),
16187                    protocol: ModuleProtocol::Subc,
16188                    overlap: Default::default(),
16189                },
16190                true,
16191            )
16192            .unwrap();
16193        assert_eq!(module.state().unwrap(), ModuleState::Running);
16194
16195        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16196        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16197        let response = handler
16198            .handle_control_frame(
16199                &ctx,
16200                route_open_frame(304, "warming", unique_project_root("warming")),
16201            )
16202            .await
16203            .unwrap();
16204        module.stop().await.unwrap();
16205
16206        assert_eq!(response[0].header.ty, FrameType::Error);
16207        let error = parse_error(&response[0]);
16208        assert_eq!(error["code"], "module_warming");
16209        assert!(error["message"]
16210            .as_str()
16211            .unwrap()
16212            .contains("state=running, enabled=true, live=false"));
16213    }
16214
16215    #[test]
16216    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16217        let handler = ControlHandler::new(Arc::new(Registry::default()));
16218        let capture = EventCapture::default();
16219        let _subscriber =
16220            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16221        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16222        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16223        let pending = (0..limit).collect::<Vec<_>>();
16224        let response = handler
16225            .route_open_capacity_refusal(
16226                &ctx,
16227                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16228                "busy",
16229                pending.len(),
16230                limit,
16231            )
16232            .unwrap();
16233        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16234        let event = capture
16235            .events()
16236            .into_iter()
16237            .find(|event| {
16238                event.target == "control"
16239                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16240            })
16241            .expect("connection admission refusal event");
16242        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16243        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16244        // Refused before `handle_route_open` parses the request, so the caller
16245        // fields are read from the frame itself.
16246        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16247        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16248    }
16249
16250    #[test]
16251    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16252        let handler = ControlHandler::new(Arc::new(Registry::default()));
16253        let capture = EventCapture::default();
16254        let _subscriber =
16255            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16256        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16257        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16258        let guards = (0..limit)
16259            .map(|_| {
16260                handler
16261                    .route_bind_concurrency
16262                    .try_admit("busy", limit)
16263                    .unwrap()
16264            })
16265            .collect::<Vec<_>>();
16266        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16267            Err(in_flight) => in_flight,
16268            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16269        };
16270        let response = handler
16271            .route_open_target_capacity_refusal(
16272                &ctx,
16273                &RouteOpenCaller::unknown(),
16274                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16275                "busy",
16276                in_flight,
16277            )
16278            .unwrap();
16279        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16280        let event = capture
16281            .events()
16282            .into_iter()
16283            .find(|event| {
16284                event.target == "control"
16285                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16286            })
16287            .expect("target admission refusal event");
16288        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16289        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16290        drop(guards);
16291    }
16292
16293    #[cfg(unix)]
16294    #[tokio::test(start_paused = true)]
16295    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16296        let registry = Arc::new(Registry::default());
16297        let handle = SupervisorHandle::new();
16298        let supervisor =
16299            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16300                .with_handle(handle.clone());
16301        let module = supervisor
16302            .spawn(crate::ModuleSpec {
16303                script: None,
16304                carry_containment: false,
16305                module_id: "retry-list".into(),
16306                program: PathBuf::from("/bin/sh"),
16307                args: vec!["-c".into(), "exit 17".into()],
16308                env: vec![],
16309                reserved: false,
16310                reserved_prefixes: vec![],
16311                protocol: ModuleProtocol::None,
16312                overlap: Default::default(),
16313            })
16314            .unwrap();
16315        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16316        while module.state().unwrap() != crate::ModuleState::Failed {
16317            assert!(
16318                std::time::Instant::now() < deadline,
16319                "waiting for budget failure"
16320            );
16321            tokio::task::yield_now().await;
16322        }
16323        let handler = ControlHandler::new(registry).with_supervisor(handle);
16324        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16325        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16326        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16327        assert_eq!(body["modules"][0]["state"], "failed");
16328        let retry = body["modules"][0]["next_retry_at_ms"]
16329            .as_u64()
16330            .expect("scheduled retry on the wire");
16331        let now = std::time::SystemTime::now()
16332            .duration_since(std::time::UNIX_EPOCH)
16333            .unwrap()
16334            .as_millis() as u64;
16335        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16336        module.set_enabled(false).await.unwrap();
16337        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16338        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16339        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16340        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16341    }
16342
16343    #[tokio::test]
16344    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16345        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16346        let supervisor =
16347            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16348        let module = supervisor
16349            .spawn(crate::ModuleSpec {
16350                script: None,
16351                carry_containment: false,
16352                module_id: "pid-read-budget".into(),
16353                program: std::env::current_exe().unwrap(),
16354                args: vec![
16355                    "--exact".into(),
16356                    "control::tests::pid_resource_read_fixture".into(),
16357                ],
16358                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16359                    .into_iter()
16360                    .map(|key| (key.into(), dir.display().to_string()))
16361                    .chain(std::iter::once((
16362                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16363                        "1".into(),
16364                    )))
16365                    .collect(),
16366                reserved: false,
16367                reserved_prefixes: Vec::new(),
16368                protocol: ModuleProtocol::None,
16369                overlap: Default::default(),
16370            })
16371            .unwrap();
16372        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16373        while !matches!(
16374            module.child_resource_usage(),
16375            subc_control::ChildResourceUsage::Measured(_)
16376        ) {
16377            assert!(
16378                tokio::time::Instant::now() < ready_deadline,
16379                "fixture process was not measurable"
16380            );
16381            tokio::time::sleep(Duration::from_millis(10)).await;
16382        }
16383        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16384        let reading = {
16385            let _guard = crate::subtree_resources::fault_read_guard().await;
16386            crate::subtree_resources::read_process(module.clone()).await
16387        };
16388        stop_resource_fixture(&module, &dir).await;
16389        assert!(
16390            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16391            "{reading:?}"
16392        );
16393    }
16394
16395    #[test]
16396    fn pid_resource_read_fixture() {
16397        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16398            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16399            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16400            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16401                std::thread::sleep(Duration::from_millis(5));
16402            }
16403            std::fs::write(dir.join("module-stopped"), "").unwrap();
16404        }
16405    }
16406
16407    async fn stop_resource_fixture(
16408        module: &crate::supervise::SupervisedModule,
16409        dir: &std::path::Path,
16410    ) {
16411        let stopping = module.stop();
16412        tokio::pin!(stopping);
16413        tokio::select! {
16414            result = &mut stopping => result.unwrap(),
16415            () = async {
16416                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16417                    tokio::time::sleep(Duration::from_millis(5)).await;
16418                }
16419                std::fs::write(dir.join("stop-module"), "").unwrap();
16420            } => stopping.await.unwrap(),
16421        }
16422        #[cfg(windows)]
16423        assert!(
16424            dir.join("module-stopped").exists(),
16425            "the resource fixture must exit cooperatively, not wait for the drain kill"
16426        );
16427        assert_eq!(
16428            module.state().unwrap(),
16429            crate::supervise::ModuleState::Stopped
16430        );
16431    }
16432
16433    #[tokio::test]
16434    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16435        let registry = Arc::new(Registry::default());
16436        let handle = SupervisorHandle::new();
16437        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16438            .with_handle(handle.clone());
16439        supervisor
16440            .supervise_configured(
16441                crate::ModuleSpec {
16442                    script: None,
16443                    module_id: "disabled-resource-reading".into(),
16444                    program: std::env::current_exe().unwrap(),
16445                    args: Vec::new(),
16446                    env: Vec::new(),
16447                    reserved: false,
16448                    reserved_prefixes: Vec::new(),
16449                    protocol: ModuleProtocol::None,
16450                    overlap: Default::default(),
16451                    carry_containment: false,
16452                },
16453                false,
16454            )
16455            .unwrap();
16456        let handler = ControlHandler::new(registry).with_supervisor(handle);
16457        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16458        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16459        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16460        assert!(body["modules"][0].get("tree").is_none());
16461        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16462    }
16463
16464    #[tokio::test]
16465    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16466        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16467        let registry = Arc::new(Registry::default());
16468        let handle = SupervisorHandle::new();
16469        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16470            .with_handle(handle.clone());
16471        let module = supervisor
16472            .spawn(crate::ModuleSpec {
16473                script: None,
16474                carry_containment: false,
16475                module_id: "list-process-priority".into(),
16476                program: std::env::current_exe().unwrap(),
16477                args: vec![
16478                    "--exact".into(),
16479                    "control::tests::pid_resource_read_fixture".into(),
16480                ],
16481                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16482                    .into_iter()
16483                    .map(|key| (key.into(), dir.display().to_string()))
16484                    .chain(std::iter::once((
16485                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16486                        "1".into(),
16487                    )))
16488                    .collect(),
16489                reserved: false,
16490                reserved_prefixes: Vec::new(),
16491                protocol: ModuleProtocol::None,
16492                overlap: Default::default(),
16493            })
16494            .unwrap();
16495        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16496        loop {
16497            let image = module.running_image_agreement().await;
16498            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16499                break;
16500            }
16501            assert!(
16502                tokio::time::Instant::now() < ready_deadline,
16503                "the fixture process never became observable: {image:?}"
16504            );
16505            tokio::time::sleep(Duration::from_millis(10)).await;
16506        }
16507        let guard = crate::subtree_resources::fault_read_guard().await;
16508        let (target, release, _) = crate::subtree_resources::held();
16509        module.set_subtree_target_for_test(target);
16510        let handler = ControlHandler::new(registry).with_supervisor(handle);
16511        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16512        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16513        drop(release);
16514        drop(guard);
16515        stop_resource_fixture(&module, &dir).await;
16516        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16517        assert_eq!(
16518            body["modules"][0]["resources"]["status"], "measured",
16519            "the optional tree timeout must not discard the process reading: {body}"
16520        );
16521        assert!(body["modules"][0].get("tree").is_none());
16522        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16523        assert_eq!(
16524            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16525            "the tree timeout must not hide a completed image observation"
16526        );
16527    }
16528
16529    #[cfg(any(target_os = "linux", target_os = "macos"))]
16530    #[tokio::test]
16531    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16532        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16533            .with_daemon_provenance(
16534                std::process::id(),
16535                0,
16536                Some(std::env::current_exe().unwrap()),
16537                None,
16538                None,
16539            );
16540        let (probe, release, began) = ExecutableIdentityProbe::held();
16541        handler.daemon_provenance.probe = probe;
16542        let observe = |handler: ControlHandler, corr| {
16543            tokio::spawn(async move {
16544                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16545                let frame =
16546                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16547                        .unwrap();
16548                handler
16549                    .handle_supervisor_provenance(&ctx, frame, None)
16550                    .await
16551                    .unwrap()
16552            })
16553        };
16554        let explicit = observe(handler.clone(), 114);
16555        began.await.unwrap();
16556        let concurrent = observe(handler.clone(), 115);
16557        // Keep explicit provenance waiting on its first image observation beyond
16558        // the list deadline; release it only after the concurrent list replies.
16559        tokio::time::sleep(Duration::from_millis(300)).await;
16560        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16561        let list = tokio::time::timeout(
16562            Duration::from_secs(1),
16563            handler.handle_supervisor_list(frame),
16564        )
16565        .await;
16566        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16567        drop(release);
16568        let replies = explicit.await.unwrap();
16569        let concurrent_replies = concurrent.await.unwrap();
16570        assert!(
16571            explicit_was_pending,
16572            "explicit provenance must await the full observation"
16573        );
16574        let list = list
16575            .expect("a concurrent explicit probe must not stall list")
16576            .unwrap();
16577        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16578        assert_eq!(list_body["op"], "supervisor.list");
16579        for replies in [replies, concurrent_replies] {
16580            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16581            assert_eq!(
16582                body["daemon"]["daemon_observed"]["running_image"]["status"],
16583                "match"
16584            );
16585        }
16586    }
16587
16588    #[tokio::test]
16589    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16590        let registry = Arc::new(Registry::default());
16591        let handle = SupervisorHandle::new();
16592        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16593            .with_handle(handle.clone());
16594        let module = supervisor
16595            .supervise_configured(
16596                crate::ModuleSpec {
16597                    script: None,
16598                    carry_containment: false,
16599                    module_id: "memory-read".into(),
16600                    program: PathBuf::from("disabled-module"),
16601                    args: Vec::new(),
16602                    env: Vec::new(),
16603                    reserved: false,
16604                    reserved_prefixes: Vec::new(),
16605                    protocol: ModuleProtocol::Subc,
16606                    overlap: Default::default(),
16607                },
16608                true,
16609            )
16610            .unwrap();
16611        let _guard = crate::subtree_resources::fault_read_guard().await;
16612        let (target, release, began) = crate::subtree_resources::held();
16613        // Optional list work may be skipped when its deadline is already spent.
16614        // Establish the stalled fixture before asking the list to observe it.
16615        let stalled_target = target.clone();
16616        let stalled = tokio::task::spawn_blocking(move || {
16617            stalled_target.tree(&subc_os::ProcessTable::default())
16618        });
16619        began.await.unwrap();
16620        module.set_subtree_target_for_test(target);
16621        let handler = ControlHandler::new(registry).with_supervisor(handle);
16622        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16623        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16624        let replies = handler
16625            .handle_client_control_request(
16626                &ctx,
16627                frame,
16628                ClientControlRequest::SupervisorList {},
16629                &mut None,
16630            )
16631            .await
16632            .unwrap();
16633        assert!(
16634            replies.is_empty(),
16635            "list reply must be detached from the connection reader"
16636        );
16637        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16638        let replies = handler
16639            .handle_client_control_request(
16640                &ctx,
16641                frame,
16642                ClientControlRequest::SupervisorSpawnSnapshot {},
16643                &mut None,
16644            )
16645            .await
16646            .unwrap();
16647        assert_eq!(
16648            replies.len(),
16649            1,
16650            "another request must complete while the subtree read stalls"
16651        );
16652        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16653            .await
16654            .unwrap()
16655            .unwrap();
16656        release.send(()).unwrap();
16657        drop(release);
16658        stalled.await.unwrap();
16659        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16660        assert!(
16661            body["modules"][0].get("tree").is_none(),
16662            "an unknown tree reading must be omitted after the bounded read expires"
16663        );
16664        // Lists export completed work rather than measuring synchronously.
16665        // Complete a refresh after the fixture is released before asserting
16666        // that a later list contains its measured tree.
16667        handler
16668            .resource_tracker
16669            .read(handler.supervisor.list(), false, "released_tree_fixture")
16670            .await;
16671        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16672        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16673        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16674        assert_eq!(
16675            body["modules"][0]["tree"]["source"], "process_tree",
16676            "the next request must export the completed refresh"
16677        );
16678        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16679    }
16680
16681    #[tokio::test]
16682    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16683        use subc_control::{
16684            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16685            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16686            TreeReading, TreeSource,
16687        };
16688        let registry = Arc::new(Registry::default());
16689        let handle = SupervisorHandle::new();
16690        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16691            .with_handle(handle.clone());
16692        supervisor
16693            .supervise_configured(
16694                crate::ModuleSpec {
16695                    script: None,
16696                    carry_containment: false,
16697                    module_id: "budget-worker".into(),
16698                    program: PathBuf::from("disabled-module"),
16699                    args: Vec::new(),
16700                    env: Vec::new(),
16701                    reserved: false,
16702                    reserved_prefixes: Vec::new(),
16703                    protocol: ModuleProtocol::Subc,
16704                    overlap: Default::default(),
16705                },
16706                true,
16707            )
16708            .unwrap();
16709        let handler = ControlHandler::new(registry).with_supervisor(handle);
16710        let now = u64::try_from(
16711            std::time::SystemTime::now()
16712                .duration_since(std::time::UNIX_EPOCH)
16713                .unwrap()
16714                .as_millis(),
16715        )
16716        .unwrap();
16717        let measured = now - 1_000;
16718        let hour = CpuLastHour::new(100, 60_000);
16719        let daemon = DaemonResources::new(7, 1, "test")
16720            .with_measured_at_ms(Some(measured))
16721            .with_resources(Some(ChildResourceUsage::Measured(
16722                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16723            )))
16724            .with_cpu_last_hour(Some(hour.clone()));
16725        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16726            .with_measured_at_ms(Some(measured))
16727            .with_cpu_last_hour(Some(hour.clone()));
16728        let tree = TreeReading::new(
16729            150,
16730            50,
16731            ChildMemoryKind::ResidentSet,
16732            1,
16733            TreeSource::ProcessTree,
16734        )
16735        .with_measured_at_ms(Some(measured));
16736        handler.resource_tracker.seed_committed_for_test(
16737            &handler.supervisor.list(),
16738            crate::resource_totals::Readings {
16739                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16740                daemon: Some(daemon),
16741                agent_commands: Some(vec![agents]),
16742                ..Default::default()
16743            },
16744            now,
16745        );
16746        list_diagnostics::scope(async {
16747            tokio::time::sleep(Duration::from_millis(110)).await;
16748            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16749            let request =
16750                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16751            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16752            let ClientControlResponse::SupervisorList {
16753                modules,
16754                daemon,
16755                agent_commands,
16756                ..
16757            } = serde_json::from_slice(&replies[0].body).unwrap()
16758            else {
16759                panic!("expected a list response")
16760            };
16761            assert!(matches!(
16762                modules[0].resources,
16763                Some(ChildResourceUsage::Unavailable {
16764                    reason: ChildResourceUnavailableReason::Unreadable
16765                })
16766            ));
16767            assert_eq!(
16768                (
16769                    modules[0].tree.as_ref().unwrap().cpu_ms,
16770                    modules[0].tree.as_ref().unwrap().measured_at_ms
16771                ),
16772                (150, Some(measured))
16773            );
16774            let daemon = daemon.unwrap();
16775            let agents = agent_commands.unwrap();
16776            assert_eq!(daemon.measured_at_ms, Some(measured));
16777            assert_eq!(
16778                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16779                (1, 50, Some(measured))
16780            );
16781            for hour in [
16782                modules[0].cpu_last_hour.as_ref(),
16783                daemon.cpu_last_hour.as_ref(),
16784                agents[0].cpu_last_hour.as_ref(),
16785            ] {
16786                let hour = hour.unwrap();
16787                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16788            }
16789        })
16790        .await;
16791    }
16792
16793    #[tokio::test]
16794    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16795        let registry = Arc::new(Registry::default());
16796        let handle = SupervisorHandle::new();
16797        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16798            .with_handle(handle.clone());
16799        supervisor
16800            .supervise_configured(
16801                crate::ModuleSpec {
16802                    script: None,
16803                    carry_containment: false,
16804                    module_id: "drift".into(),
16805                    program: PathBuf::from("disabled-module"),
16806                    args: Vec::new(),
16807                    env: Vec::new(),
16808                    reserved: false,
16809                    reserved_prefixes: Vec::new(),
16810                    protocol: ModuleProtocol::Subc,
16811                    overlap: Default::default(),
16812                },
16813                false,
16814            )
16815            .unwrap();
16816        let handler = ControlHandler::new(registry).with_supervisor(handle);
16817        for configured in [None, Some(false), Some(true)] {
16818            handler.capability_evaluator.configure(
16819                configured.map(|enabled| ("drift".to_string(), enabled)),
16820                BTreeMap::new(),
16821            );
16822            let frame =
16823                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16824            let replies = handler
16825                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16826                .await
16827                .unwrap();
16828            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16829            assert!(body.get("configured_enabled").is_none());
16830            assert_eq!(body["op"], "supervisor.ack");
16831            let frame =
16832                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16833            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16834            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16835            assert_eq!(
16836                body["modules"][0].get("configured_enabled"),
16837                configured.map(Value::Bool).as_ref()
16838            );
16839            assert!(body["modules"][0].get("tree").is_none());
16840            assert!(body["modules"][0].get("subtree").is_none());
16841        }
16842    }
16843
16844    #[tokio::test(flavor = "current_thread")]
16845    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16846        let handler = ControlHandler::new(Arc::new(Registry::default()));
16847        let capture = EventCapture::default();
16848        let _subscriber =
16849            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16850        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16851        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16852
16853        let _ = handler
16854            .handle_client_control_request(
16855                &ctx,
16856                frame,
16857                ClientControlRequest::SupervisorSetEnabled {
16858                    module_id: "broca".to_string(),
16859                    enabled: false,
16860                },
16861                &mut None,
16862            )
16863            .await
16864            .unwrap();
16865
16866        let events = capture
16867            .events()
16868            .into_iter()
16869            .filter(|event| {
16870                event.target == "control"
16871                    && event.fields.get("message").map(String::as_str)
16872                        == Some("supervisor request received")
16873            })
16874            .collect::<Vec<_>>();
16875        assert_eq!(events.len(), 1, "one supervisor request log line");
16876        let event = &events[0];
16877        assert_eq!(event.level, tracing::Level::INFO);
16878        assert_eq!(
16879            event.fields.get("op"),
16880            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16881        );
16882        assert_eq!(
16883            event.fields.get("module_id"),
16884            Some(&"\"broca\"".to_string())
16885        );
16886        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16887        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16888        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16889    }
16890
16891    #[tokio::test(flavor = "current_thread")]
16892    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16893        let registry = Arc::new(Registry::default());
16894        let module_connection = ConnectionId::new(303);
16895        registry
16896            .register_with_control_ops(
16897                manifest("aft", PROTOCOL_VERSION),
16898                PROTOCOL_VERSION,
16899                module_connection,
16900                module_baseline_control_ops(),
16901            )
16902            .unwrap();
16903        let handler = ControlHandler::new(registry);
16904        let capture = EventCapture::default();
16905        let _subscriber =
16906            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16907        let (ctx, _rx) = route_ctx(module_connection);
16908        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16909
16910        let _ = handler
16911            .handle_client_control_request(
16912                &ctx,
16913                frame,
16914                ClientControlRequest::SupervisorSetEnabled {
16915                    module_id: "broca".to_string(),
16916                    enabled: false,
16917                },
16918                &mut None,
16919            )
16920            .await
16921            .unwrap();
16922
16923        let callers = capture
16924            .events()
16925            .into_iter()
16926            .filter(|event| {
16927                event.fields.get("message").map(String::as_str)
16928                    == Some("supervisor request received")
16929            })
16930            .map(|event| event.fields.get("caller").cloned())
16931            .collect::<Vec<_>>();
16932        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16933    }
16934
16935    #[tokio::test(flavor = "current_thread")]
16936    async fn supervisor_list_does_not_log_request_received() {
16937        let handler = ControlHandler::new(Arc::new(Registry::default()));
16938        let capture = EventCapture::default();
16939        let _subscriber =
16940            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16941        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16942        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16943
16944        handler
16945            .handle_client_control_request(
16946                &ctx,
16947                frame,
16948                ClientControlRequest::SupervisorList {},
16949                &mut None,
16950            )
16951            .await
16952            .unwrap();
16953
16954        assert!(capture.events().into_iter().all(|event| {
16955            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16956        }));
16957    }
16958
16959    #[tokio::test(flavor = "current_thread")]
16960    async fn supervisor_rescan_preview_does_not_log_request_received() {
16961        let handler = ControlHandler::new(Arc::new(Registry::default()));
16962        let capture = EventCapture::default();
16963        let _subscriber =
16964            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16965        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16966        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16967
16968        handler
16969            .handle_client_control_request(
16970                &ctx,
16971                frame,
16972                ClientControlRequest::SupervisorRescan { preview: true },
16973                &mut None,
16974            )
16975            .await
16976            .unwrap();
16977
16978        assert!(capture.events().into_iter().all(|event| {
16979            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16980        }));
16981    }
16982
16983    struct ApproveOperator;
16984    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16985        fn prompt(
16986            &self,
16987            _: &str,
16988            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16989        ) -> crate::operator_confirm::ProviderResult {
16990            crate::operator_confirm::ProviderResult::Approved
16991        }
16992    }
16993
16994    #[tokio::test]
16995    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
16996        assert_eq!(
16997            ControlHandler::default().privileged_operator_prompt,
16998            PrivilegedOperatorPrompt::Log
16999        );
17000        for (initial, changed, running) in [
17001            ("log", "enforce", PrivilegedOperatorPrompt::Log),
17002            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
17003        ] {
17004            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
17005            let path = dir.join("subc.jsonc");
17006            std::fs::write(
17007                &path,
17008                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
17009            )
17010            .unwrap();
17011            let config = crate::daemon_config::load(&path).unwrap().unwrap();
17012            let registry = Arc::new(Registry::default());
17013            let handle = SupervisorHandle::new();
17014            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
17015                .with_handle(handle.clone());
17016            let handler = ControlHandler::new(registry)
17017                .with_supervisor(handle)
17018                .with_privileged_operator_prompt(config.privileged_operator_prompt)
17019                .with_supervisor_rescan(supervisor, &path, config.port);
17020            handler.forwarding.operator_confirms().configure(
17021                Arc::new(ApproveOperator),
17022                crate::operator_confirm::OperatorLimits::default(),
17023            );
17024            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
17025
17026            for (disk_mode, needs_restart) in [
17027                (Some(initial), false),
17028                (Some(changed), true),
17029                (Some(changed), true),
17030                (None, running == PrivilegedOperatorPrompt::Enforce),
17031                (Some(initial), false),
17032            ] {
17033                let mut doc = json!({"version":1});
17034                if let Some(mode) = disk_mode {
17035                    doc["privileged_operator_prompt"] = json!(mode);
17036                }
17037                std::fs::write(&path, doc.to_string()).unwrap();
17038                for preview in [true, false] {
17039                    let request = ClientControlRequest::SupervisorRescan { preview };
17040                    let frame = Frame::build(
17041                        FrameType::Request,
17042                        control_flags(),
17043                        0,
17044                        0,
17045                        1,
17046                        serde_json::to_vec(&request).unwrap(),
17047                    )
17048                    .unwrap();
17049                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17050                    assert_eq!(frames.len(), 1);
17051                    let ClientControlResponse::SupervisorRescan { result } =
17052                        serde_json::from_slice(&frames[0].body).unwrap()
17053                    else {
17054                        panic!("expected a rescan response");
17055                    };
17056                    let expected = if needs_restart {
17057                        vec!["privileged_operator_prompt"]
17058                    } else {
17059                        Vec::new()
17060                    };
17061                    assert_eq!(result.restart_required, expected);
17062                    assert_eq!(handler.privileged_operator_prompt, running);
17063                    assert_eq!(
17064                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
17065                        running
17066                    );
17067                }
17068            }
17069        }
17070    }
17071
17072    #[tokio::test]
17073    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
17074        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
17075        let path = dir.join("subc.jsonc");
17076        let registry = Arc::new(Registry::default());
17077        let handle = SupervisorHandle::new();
17078        let supervisor =
17079            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
17080        let handler = ControlHandler::new(registry)
17081            .with_supervisor(handle)
17082            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
17083            .with_supervisor_rescan(supervisor, &path, None);
17084        handler.forwarding.operator_confirms().configure(
17085            Arc::new(ApproveOperator),
17086            crate::operator_confirm::OperatorLimits::default(),
17087        );
17088        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17089        for preview in [true, false] {
17090            std::fs::write(
17091                &path,
17092                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17093            )
17094            .unwrap();
17095            let request = ClientControlRequest::SupervisorRescan { preview };
17096            let frame = Frame::build(
17097                FrameType::Request,
17098                control_flags(),
17099                0,
17100                0,
17101                1,
17102                serde_json::to_vec(&request).unwrap(),
17103            )
17104            .unwrap();
17105            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17106            assert_eq!(frames.len(), 1);
17107            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17108            assert_eq!(
17109                handler.privileged_operator_prompt,
17110                PrivilegedOperatorPrompt::Enforce
17111            );
17112        }
17113    }
17114
17115    /// One wire code has several senders, so the refusal line names the check
17116    /// that refused. This drives the shared refusal path for ordinary refusals
17117    /// with an unregistered
17118    /// target and requires the branch label on the event.
17119    #[tokio::test]
17120    async fn route_open_refusal_names_the_check_that_refused() {
17121        let handler = ControlHandler::new(Arc::new(Registry::default()));
17122        let capture = EventCapture::default();
17123        let _subscriber =
17124            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17125        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17126        let response = handler
17127            .handle_control_frame(
17128                &ctx,
17129                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17130            )
17131            .await
17132            .unwrap();
17133
17134        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17135        let event = capture
17136            .events()
17137            .into_iter()
17138            .find(|event| {
17139                event.target == "control"
17140                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17141            })
17142            .expect("route.open refusal event");
17143        assert_eq!(
17144            event.fields.get("reason"),
17145            Some(&"\"not_registered\"".to_string())
17146        );
17147    }
17148
17149    #[tokio::test]
17150    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17151        let registry = Arc::new(Registry::default());
17152        let supervisor_handle = SupervisorHandle::new();
17153        let supervisor =
17154            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17155                .with_handle(supervisor_handle.clone())
17156                .with_connection_file_path(std::env::temp_dir().join(format!(
17157                    "subc-route-open-refusal-info-{}",
17158                    std::process::id()
17159                )));
17160        let module = supervisor
17161            .supervise_configured(
17162                ModuleSpec {
17163                    script: None,
17164                    carry_containment: false,
17165                    module_id: "warming".to_string(),
17166                    program: fake_aft_stub_path(),
17167                    args: Vec::new(),
17168                    env: Vec::new(),
17169                    reserved: false,
17170                    reserved_prefixes: Vec::new(),
17171                    protocol: ModuleProtocol::Subc,
17172                    overlap: Default::default(),
17173                },
17174                true,
17175            )
17176            .unwrap();
17177        assert_eq!(module.state().unwrap(), ModuleState::Running);
17178
17179        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17180        assert!(handler
17181            .counters()
17182            .snapshot()
17183            .get("route_open_refused_by_code")
17184            .is_none());
17185        let capture = EventCapture::default();
17186        let _subscriber =
17187            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17188        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17189        let response = handler
17190            .handle_control_frame(
17191                &ctx,
17192                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17193            )
17194            .await
17195            .unwrap();
17196        module.stop().await.unwrap();
17197
17198        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17199        let event = capture
17200            .events()
17201            .into_iter()
17202            .find(|event| {
17203                event.target == "control"
17204                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17205            })
17206            .expect("route.open refusal event");
17207        assert_eq!(
17208            event.fields.get("module_id"),
17209            Some(&"\"warming\"".to_string())
17210        );
17211        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17212        assert_eq!(
17213            event.fields.get("reason"),
17214            Some(&"\"supervised_not_registered\"".to_string())
17215        );
17216        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17217        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17218        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17219        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17220        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17221        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17222        assert_eq!(
17223            handler.counters().snapshot()["route_open_refused_by_code"],
17224            json!({ "module_warming": 1 })
17225        );
17226    }
17227
17228    const OUTAGE_START: &str = "route.open refusing module: not serving";
17229    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17230
17231    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17232        capture
17233            .events()
17234            .into_iter()
17235            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17236            .collect()
17237    }
17238
17239    fn supervise_stub(
17240        registry: &Arc<Registry>,
17241        module_id: &str,
17242        enabled: bool,
17243    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17244        let supervisor_handle = SupervisorHandle::new();
17245        let supervisor =
17246            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17247                .with_handle(supervisor_handle.clone())
17248                .with_connection_file_path(std::env::temp_dir().join(format!(
17249                    "subc-route-outage-{module_id}-{}",
17250                    std::process::id()
17251                )));
17252        let module = supervisor
17253            .supervise_configured(
17254                ModuleSpec {
17255                    script: None,
17256                    carry_containment: false,
17257                    module_id: module_id.to_string(),
17258                    program: fake_aft_stub_path(),
17259                    args: Vec::new(),
17260                    env: Vec::new(),
17261                    reserved: false,
17262                    reserved_prefixes: Vec::new(),
17263                    protocol: ModuleProtocol::Subc,
17264                    overlap: Default::default(),
17265                },
17266                enabled,
17267            )
17268            .unwrap();
17269        (supervisor_handle, module)
17270    }
17271
17272    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17273        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17274            module_id: module_id.to_string(),
17275            drain_timeout_ms: Some(50),
17276        })
17277        .unwrap();
17278        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17279    }
17280
17281    /// Two handlers built over one forwarding table must share one outage
17282    /// tracker; separate trackers would each log their own opening line for
17283    /// the same outage.
17284    #[test]
17285    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17286        let registry = Arc::new(Registry::default());
17287        let forwarding = Arc::new(ForwardingTable::default());
17288        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17289        let second = ControlHandler::with_forwarding(registry, forwarding);
17290        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17291    }
17292
17293    /// A client can name any module id it likes. Refusing an unknown one,
17294    /// however often, must not create outage state or outage lines, or the
17295    /// tracker would be a memory sink any client could fill.
17296    #[tokio::test(flavor = "current_thread")]
17297    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17298        let handler = ControlHandler::new(Arc::new(Registry::default()));
17299        let capture = EventCapture::default();
17300        let _subscriber =
17301            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17302        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17303        for corr in 0..8 {
17304            let response = handler
17305                .handle_control_frame(
17306                    &ctx,
17307                    route_open_frame(
17308                        380 + corr,
17309                        &format!("nobody-{corr}"),
17310                        unique_project_root("outage-unknown"),
17311                    ),
17312                )
17313                .await
17314                .unwrap();
17315            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17316        }
17317
17318        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17319        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17320        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17321    }
17322
17323    /// Drives the refusal path end to end: a supervised module that served
17324    /// before and stopped being registered with no instruction to stop is a
17325    /// WARN, and the same module refused after an operator `supervisor.restart`
17326    /// is an INFO.
17327    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17328    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17329        let registry = Arc::new(Registry::default());
17330        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17331        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17332        let capture = EventCapture::default();
17333        let _subscriber =
17334            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17335        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17336        // The stub never registers, so pretend it served once: otherwise every
17337        // refusal would fall in its startup window.
17338        handler.route_outages.record_accepted("outage-restart");
17339
17340        let response = handler
17341            .handle_control_frame(
17342                &ctx,
17343                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17344            )
17345            .await
17346            .unwrap();
17347        assert_eq!(response[0].header.ty, FrameType::Error);
17348        let starts = outage_lines(&capture, OUTAGE_START);
17349        assert_eq!(starts.len(), 1, "{starts:?}");
17350        assert_eq!(starts[0].level, tracing::Level::WARN);
17351        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17352        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17353        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17354        handler.route_outages.record_accepted("outage-restart");
17355        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17356
17357        // The missing connection file makes the stub exit immediately. Restart
17358        // is deliberately deferred while that exit is being recorded; Failed
17359        // means the zero restart budget and terminal record have been published.
17360        tokio::time::timeout(Duration::from_secs(10), async {
17361            while module.state().unwrap() != crate::ModuleState::Failed {
17362                tokio::task::yield_now().await;
17363            }
17364        })
17365        .await
17366        .expect("stub exit must be recorded before the operator restart");
17367
17368        let restart = handler
17369            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17370            .await
17371            .unwrap();
17372        assert_eq!(
17373            restart[0].header.ty,
17374            FrameType::Response,
17375            "{:?}",
17376            parse_error(&restart[0])
17377        );
17378        handler
17379            .handle_control_frame(
17380                &ctx,
17381                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17382            )
17383            .await
17384            .unwrap();
17385        module.stop().await.unwrap();
17386
17387        let starts = outage_lines(&capture, OUTAGE_START);
17388        assert_eq!(starts.len(), 2, "{starts:?}");
17389        assert_eq!(starts[1].level, tracing::Level::INFO);
17390        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17391    }
17392
17393    /// A restart refused before it touched the module (here: the module is
17394    /// disabled) must clear its operator mark, so the next real outage is
17395    /// still reported as a warning.
17396    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17397    async fn failed_operator_restart_leaves_no_operator_mark() {
17398        let registry = Arc::new(Registry::default());
17399        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17400        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17401        let capture = EventCapture::default();
17402        let _subscriber =
17403            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17404        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17405        handler.route_outages.record_accepted("outage-disabled");
17406
17407        let restart = handler
17408            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17409            .await
17410            .unwrap();
17411        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17412        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17413
17414        handler
17415            .handle_control_frame(
17416                &ctx,
17417                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17418            )
17419            .await
17420            .unwrap();
17421        let starts = outage_lines(&capture, OUTAGE_START);
17422        assert_eq!(starts.len(), 1, "{starts:?}");
17423        assert_eq!(starts[0].level, tracing::Level::WARN);
17424    }
17425
17426    #[tokio::test(flavor = "current_thread")]
17427    async fn route_open_unknown_module_escapes_target_module_id() {
17428        let handler = ControlHandler::new(Arc::new(Registry::default()));
17429        let capture = EventCapture::default();
17430        let _subscriber =
17431            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17432        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17433        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17434        let response = handler
17435            .handle_control_frame(
17436                &ctx,
17437                route_open_frame(
17438                    395,
17439                    hostile_module_id,
17440                    unique_project_root("hostile-target-module-id"),
17441                ),
17442            )
17443            .await
17444            .unwrap();
17445
17446        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17447        let event = capture
17448            .events()
17449            .into_iter()
17450            .find(|event| {
17451                event.target == "control"
17452                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17453            })
17454            .expect("route.open unknown-module refusal event");
17455        let logged = event.fields.get("module_id").expect("module_id field");
17456        assert!(!logged.bytes().any(|byte| byte < 0x20));
17457        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17458    }
17459
17460    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17461    /// the daemon-origin bit on the frame the client receives.
17462    #[tokio::test(flavor = "current_thread")]
17463    async fn route_open_refusal_carries_daemon_origin() {
17464        let handler = ControlHandler::new(Arc::new(Registry::default()));
17465        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17466        let response = handler
17467            .handle_control_frame(
17468                &ctx,
17469                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17470            )
17471            .await
17472            .unwrap();
17473
17474        assert_eq!(response.len(), 1);
17475        assert_eq!(response[0].header.ty, FrameType::Error);
17476        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17477        assert!(
17478            response[0].header.flags.is_daemon_origin(),
17479            "route.open refusal must carry daemon origin: {:?}",
17480            response[0].header.flags
17481        );
17482    }
17483
17484    /// The drain `module_reloading` refusal is daemon-synthesized for an
17485    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17486    /// frame the client receives.
17487    #[tokio::test(flavor = "current_thread")]
17488    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17489        let registry = Arc::new(Registry::default());
17490        let forwarding = Arc::new(ForwardingTable::default());
17491        let handler =
17492            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17493        let module_connection = ConnectionId::new(95);
17494        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17495        hello_via_sink(
17496            &handler,
17497            &module_ctx,
17498            &mut module_rx,
17499            hello_frame("aft", PROTOCOL_VERSION, 395),
17500        )
17501        .await;
17502        forwarding
17503            .begin_module_drain("aft", RouteCloseReason::Restart)
17504            .unwrap()
17505            .expect("the module endpoint drains");
17506
17507        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17508        let response = handler
17509            .handle_control_frame(
17510                &client_ctx,
17511                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17512            )
17513            .await
17514            .unwrap();
17515
17516        assert_eq!(response.len(), 1);
17517        assert_eq!(response[0].header.ty, FrameType::Error);
17518        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17519        assert!(
17520            response[0].header.flags.is_daemon_origin(),
17521            "drain module_reloading must carry daemon origin: {:?}",
17522            response[0].header.flags
17523        );
17524    }
17525
17526    /// A module that refuses a bind with a daemon code still cannot mint a
17527    /// daemon refusal: the relayed `module_reloading` body reaches the client
17528    /// with the daemon-origin bit clear.
17529    #[tokio::test(flavor = "current_thread")]
17530    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17531        let registry = Arc::new(Registry::default());
17532        let forwarding = Arc::new(ForwardingTable::default());
17533        let handler =
17534            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17535        let module_connection = ConnectionId::new(95);
17536        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17537        hello_via_sink(
17538            &handler,
17539            &module_ctx,
17540            &mut module_rx,
17541            hello_frame("aft", PROTOCOL_VERSION, 395),
17542        )
17543        .await;
17544
17545        let client_connection = ConnectionId::new(96);
17546        let (client_ctx, _client_rx) = route_ctx(client_connection);
17547        let (route_task, bind) = relay_route_open(
17548            &handler,
17549            client_connection,
17550            &client_ctx.egress,
17551            &mut module_rx,
17552            396,
17553            "aft",
17554            "spoofed-reloading",
17555        )
17556        .await;
17557        // The module sets the origin bit on its own rejection too: neither
17558        // the bit nor the daemon code may survive the relay as daemon-owned.
17559        let rejection = Frame::build(
17560            FrameType::Error,
17561            crate::router::daemon_error_flags(),
17562            0,
17563            0,
17564            bind.header.corr,
17565            serde_json::to_vec(&ErrorBody::new(
17566                "module_reloading",
17567                "module refused route.bind",
17568            ))
17569            .unwrap(),
17570        )
17571        .unwrap();
17572        handler
17573            .handle_control_frame(&module_ctx, rejection)
17574            .await
17575            .unwrap();
17576
17577        let response = route_task.await.unwrap();
17578        assert_eq!(response.len(), 1);
17579        assert_eq!(response[0].header.ty, FrameType::Error);
17580        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17581        assert!(
17582            !response[0].header.flags.is_daemon_origin(),
17583            "a module's own rejection must not carry daemon origin: {:?}",
17584            response[0].header.flags
17585        );
17586    }
17587
17588    #[tokio::test(flavor = "current_thread")]
17589    async fn route_open_module_rejection_uses_daemon_counter_key() {
17590        let registry = Arc::new(Registry::default());
17591        let forwarding = Arc::new(ForwardingTable::default());
17592        let handler =
17593            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17594        let module_connection = ConnectionId::new(95);
17595        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17596        hello_via_sink(
17597            &handler,
17598            &module_ctx,
17599            &mut module_rx,
17600            hello_frame("aft", PROTOCOL_VERSION, 395),
17601        )
17602        .await;
17603
17604        let client_connection = ConnectionId::new(96);
17605        let (client_ctx, _client_rx) = route_ctx(client_connection);
17606        let capture = EventCapture::default();
17607        // tracing-core decides once per callsite whether its events are enabled,
17608        // and caches the answer. If a parallel test with no subscriber reaches
17609        // this callsite first, the cached answer is "disabled" and this test's
17610        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17611        // ask every live subscriber instead, while only this test's default
17612        // receives the events.
17613        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17614        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17615        let _subscriber =
17616            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17617        let (route_task, bind) = relay_route_open(
17618            &handler,
17619            client_connection,
17620            &client_ctx.egress,
17621            &mut module_rx,
17622            396,
17623            "aft",
17624            "hostile-module-code",
17625        )
17626        .await;
17627        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17628        let rejection = Frame::build(
17629            FrameType::Error,
17630            control_flags(),
17631            0,
17632            0,
17633            bind.header.corr,
17634            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17635        )
17636        .unwrap();
17637        handler
17638            .handle_control_frame(&module_ctx, rejection)
17639            .await
17640            .unwrap();
17641
17642        let response = route_task.await.unwrap();
17643        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17644        let counters = handler.counters().snapshot();
17645        assert_eq!(
17646            counters["route_open_refused_by_code"],
17647            json!({ "module_rejected": 1 })
17648        );
17649        assert!(counters["route_open_refused_by_code"]
17650            .get(hostile_code)
17651            .is_none());
17652
17653        let event = capture
17654            .events()
17655            .into_iter()
17656            .find(|event| {
17657                event.target == "control"
17658                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17659            })
17660            .expect("route.open module-rejection refusal event");
17661        let logged = event.fields.get("module_code").expect("module_code field");
17662        assert!(!logged.bytes().any(|byte| byte < 0x20));
17663        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17664    }
17665
17666    #[tokio::test]
17667    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17668        let registry = Arc::new(Registry::default());
17669        let supervisor_handle = SupervisorHandle::new();
17670        let missing_program = std::env::temp_dir().join(format!(
17671            "subc-route-open-missing-program-{}",
17672            std::process::id()
17673        ));
17674        let supervisor =
17675            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17676                .with_handle(supervisor_handle.clone());
17677        let module = supervisor
17678            .supervise_configured(
17679                ModuleSpec {
17680                    script: None,
17681                    carry_containment: false,
17682                    module_id: "failed".to_string(),
17683                    program: missing_program,
17684                    args: Vec::new(),
17685                    env: Vec::new(),
17686                    reserved: false,
17687                    reserved_prefixes: Vec::new(),
17688                    protocol: ModuleProtocol::Subc,
17689                    overlap: Default::default(),
17690                },
17691                true,
17692            )
17693            .unwrap();
17694        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17695
17696        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17697        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17698        let response = handler
17699            .handle_control_frame(
17700                &ctx,
17701                route_open_frame(305, "failed", unique_project_root("failed")),
17702            )
17703            .await
17704            .unwrap();
17705
17706        assert_eq!(response[0].header.ty, FrameType::Error);
17707        let error = parse_error(&response[0]);
17708        assert_eq!(error["code"], "target_unavailable");
17709        assert!(error["message"]
17710            .as_str()
17711            .unwrap()
17712            .contains("state=failed, enabled=true, live=false"));
17713    }
17714
17715    #[tokio::test]
17716    async fn route_open_role_mismatch_remains_target_unavailable() {
17717        let registry = Arc::new(Registry::default());
17718        let handler = ControlHandler::new(Arc::clone(&registry));
17719        handler
17720            .handle_control(
17721                ConnectionId::new(41),
17722                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17723            )
17724            .unwrap();
17725
17726        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17727        let response = handler
17728            .handle_control_frame(
17729                &ctx,
17730                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17731            )
17732            .await
17733            .unwrap();
17734
17735        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17736        assert!(parse_error(&response[0])["message"]
17737            .as_str()
17738            .unwrap()
17739            .contains("does not provide the requested target"));
17740    }
17741
17742    #[tokio::test]
17743    async fn route_open_inactive_registration_remains_target_unavailable() {
17744        let registry = Arc::new(Registry::default());
17745        let handler = ControlHandler::new(Arc::clone(&registry));
17746        handler
17747            .handle_control(
17748                ConnectionId::new(43),
17749                hello_frame("inactive", PROTOCOL_VERSION, 308),
17750            )
17751            .unwrap();
17752        assert!(registry
17753            .set_module_state_for_test("inactive", ChannelState::Closed)
17754            .unwrap());
17755
17756        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17757        let response = handler
17758            .handle_control_frame(
17759                &ctx,
17760                route_open_frame(309, "inactive", unique_project_root("inactive")),
17761            )
17762            .await
17763            .unwrap();
17764
17765        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17766        assert!(parse_error(&response[0])["message"]
17767            .as_str()
17768            .unwrap()
17769            .contains("is not active"));
17770    }
17771
17772    #[tokio::test]
17773    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17774        let registry = Arc::new(Registry::default());
17775        let forwarding = Arc::new(ForwardingTable::default());
17776        let supervisor_handle = SupervisorHandle::new();
17777        let supervisor =
17778            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17779                .with_forwarding(Arc::clone(&forwarding))
17780                .with_handle(supervisor_handle.clone());
17781        let module = supervisor
17782            .supervise_configured(
17783                crate::ModuleSpec {
17784                    script: None,
17785                    carry_containment: false,
17786                    module_id: "late-health-response".to_string(),
17787                    program: PathBuf::from("disabled-module"),
17788                    args: Vec::new(),
17789                    env: Vec::new(),
17790                    reserved: false,
17791                    reserved_prefixes: Vec::new(),
17792                    protocol: ModuleProtocol::Subc,
17793                    overlap: Default::default(),
17794                },
17795                false,
17796            )
17797            .unwrap();
17798        let handler =
17799            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17800                .with_supervisor(supervisor_handle);
17801        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17802        handler
17803            .handle_control_frame(
17804                &module_ctx,
17805                hello_frame_with_control_ops(
17806                    "late-health-response",
17807                    PROTOCOL_VERSION,
17808                    7,
17809                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17810                ),
17811            )
17812            .await
17813            .unwrap();
17814        let probe_started_at = Instant::now() - Duration::from_millis(80);
17815        let pending = forwarding
17816            .begin_health_probe_rpc_for(
17817                "late-health-response",
17818                MODULE_CONTROL_OP_HEALTH_CHECK,
17819                probe_started_at,
17820                Instant::now() - Duration::from_millis(1),
17821            )
17822            .unwrap();
17823        assert!(forwarding
17824            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17825            .unwrap());
17826
17827        let responses = handler
17828            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17829            .await
17830            .unwrap();
17831
17832        assert!(responses.is_empty());
17833        let health = module.status().unwrap().health;
17834        assert_eq!(health.late_answer_count, 1);
17835        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17836    }
17837
17838    #[tokio::test]
17839    async fn health_probe_timeout_and_module_death_are_typed() {
17840        let registry = Arc::new(Registry::default());
17841        let forwarding = Arc::new(ForwardingTable::default());
17842        let handler =
17843            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17844                .with_health_probe_timeout(Duration::from_millis(50));
17845        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17846        hello_via_sink(
17847            &handler,
17848            &module_ctx,
17849            &mut module_rx,
17850            hello_frame_with_control_ops(
17851                "aft",
17852                PROTOCOL_VERSION,
17853                7,
17854                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17855            ),
17856        )
17857        .await;
17858
17859        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17860        let responses = handler
17861            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17862            .await
17863            .unwrap();
17864        assert_eq!(responses[0].header.ty, FrameType::Error);
17865        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17866        let _ = module_rx.try_recv();
17867
17868        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17869        let health_handler = handler.clone();
17870        let death_task = tokio::spawn(async move {
17871            health_handler
17872                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17873                .await
17874                .unwrap()
17875        });
17876        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17877            .await
17878            .unwrap()
17879            .unwrap();
17880        handler
17881            .cleanup_connection(module_ctx.connection_id)
17882            .unwrap();
17883        let responses = death_task.await.unwrap();
17884        assert_eq!(responses[0].header.ty, FrameType::Error);
17885        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17886    }
17887
17888    #[test]
17889    fn hello_requires_exact_protocol_version() {
17890        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17891            let registry = Arc::new(Registry::default());
17892            let handler = ControlHandler::new(Arc::clone(&registry));
17893            let responses = handler
17894                .handle_control(
17895                    ConnectionId::new(connection),
17896                    hello_frame("aft", offered, 9),
17897                )
17898                .unwrap();
17899
17900            assert_eq!(responses.len(), 1);
17901            assert_eq!(responses[0].header.ty, FrameType::Error);
17902            let error = parse_error(&responses[0]);
17903            assert_eq!(error["code"], "version_unsupported");
17904            assert!(registry.get_module("aft").unwrap().is_none());
17905            assert_eq!(registry.active_registration_count().unwrap(), 0);
17906        }
17907    }
17908
17909    #[test]
17910    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17911        let registry = Arc::new(Registry::default());
17912        let forwarding = Arc::new(ForwardingTable::default());
17913        let handler =
17914            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17915        let module_connection = ConnectionId::new(301);
17916        let registration = registry
17917            .register_with_control_ops(
17918                manifest("aft-push", PROTOCOL_VERSION),
17919                PROTOCOL_VERSION,
17920                module_connection,
17921                module_baseline_control_ops(),
17922            )
17923            .unwrap();
17924        let (module_tx, _module_rx) = mpsc::channel(8);
17925        let endpoint = forwarding
17926            .register_module_connection(
17927                module_connection,
17928                "aft-push".to_string(),
17929                PROTOCOL_VERSION,
17930                manifest_concurrency(&registration.manifest),
17931                FrameSink::new(module_tx),
17932            )
17933            .unwrap();
17934
17935        // A push op this version does not know is ignored (forward-compat), not errored.
17936        let unknown = Frame::build(
17937            FrameType::Push,
17938            control_flags(),
17939            0,
17940            0,
17941            5,
17942            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17943        )
17944        .unwrap();
17945        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17946        assert!(
17947            out.is_empty(),
17948            "unknown push op must be ignored, got {out:?}"
17949        );
17950
17951        // A malformed body for a KNOWN op is a real error worth surfacing.
17952        let malformed = Frame::build(
17953            FrameType::Push,
17954            control_flags(),
17955            0,
17956            0,
17957            6,
17958            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17959        )
17960        .unwrap();
17961        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17962        assert_eq!(out.len(), 1);
17963        assert_eq!(out[0].header.ty, FrameType::Error);
17964        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17965    }
17966
17967    #[test]
17968    fn hello_rejected_when_connection_already_owns_client_routes() {
17969        let registry = Arc::new(Registry::default());
17970        let forwarding = Arc::new(ForwardingTable::default());
17971        let handler =
17972            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17973        // Commits a client route on connection 202 (bound to a module on conn 101).
17974        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17975        let client_connection = ConnectionId::new(202);
17976
17977        // That same connection now tries to register as a module: rejected, so one
17978        // connection never holds both client-route and module-endpoint state.
17979        let responses = handler
17980            .handle_control(
17981                client_connection,
17982                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17983            )
17984            .unwrap();
17985        assert_eq!(responses[0].header.ty, FrameType::Error);
17986        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17987        assert!(registry.get_module("aft-second").unwrap().is_none());
17988    }
17989
17990    #[tokio::test]
17991    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17992        let registry = Arc::new(Registry::default());
17993        let forwarding = Arc::new(ForwardingTable::default());
17994        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
17995        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
17996        hello_via_sink(
17997            &handler,
17998            &module_ctx,
17999            &mut module_rx,
18000            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
18001        )
18002        .await;
18003        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
18004        let pending = forwarding
18005            .begin_route_bind_relay_for_test(
18006                client_ctx.connection_id,
18007                client_ctx.egress.clone(),
18008                2,
18009                "alpha",
18010            )
18011            .unwrap();
18012        forwarding
18013            .complete_pending_relay(
18014                module_ctx.connection_id,
18015                pending.corr,
18016                RouteBindRelayOutcome::Accepted,
18017            )
18018            .unwrap();
18019        client_rx.try_recv().unwrap();
18020        for module_id in ["beta", "alpha"] {
18021            let replies = handler
18022                .handle_control_frame(
18023                    &module_ctx,
18024                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
18025                )
18026                .await
18027                .unwrap();
18028            assert_eq!(replies.len(), 1, "second HELLO must be refused");
18029            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
18030        }
18031        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
18032        assert!(registry.get_module("beta").unwrap().is_none());
18033        assert!(matches!(
18034            forwarding
18035                .lookup_data_route(
18036                    client_ctx.connection_id,
18037                    pending.client_channel,
18038                    pending.client_epoch,
18039                )
18040                .unwrap(),
18041            DataRoute::Client(DataRouteState::Bound(_))
18042        ));
18043        assert!(handler
18044            .hello_launch_nonces
18045            .lock()
18046            .unwrap()
18047            .presented(module_ctx.connection_id, Some("alpha-nonce")));
18048        assert!(module_rx.try_recv().is_err());
18049    }
18050
18051    #[test]
18052    fn reserved_module_hello_requires_matching_launch_nonce() {
18053        let registry = Arc::new(Registry::default());
18054        let supervisor = SupervisorHandle::new();
18055        // The supervisor recorded the nonce it injected when it spawned the reserved
18056        // module; the HELLO verifier checks against the same shared handle.
18057        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
18058        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18059
18060        // A HELLO with NO nonce is rejected.
18061        let no_nonce = handler
18062            .handle_control(
18063                ConnectionId::new(1),
18064                hello_frame("vault", PROTOCOL_VERSION, 1),
18065            )
18066            .unwrap();
18067        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
18068        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
18069        assert!(registry.get_module("vault").unwrap().is_none());
18070
18071        // A HELLO with the WRONG nonce is rejected.
18072        let wrong = handler
18073            .handle_control(
18074                ConnectionId::new(2),
18075                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
18076            )
18077            .unwrap();
18078        assert_eq!(wrong[0].header.ty, FrameType::Error);
18079        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
18080        assert!(registry.get_module("vault").unwrap().is_none());
18081
18082        // A HELLO with the CORRECT nonce registers.
18083        let ok = handler
18084            .handle_control(
18085                ConnectionId::new(3),
18086                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
18087            )
18088            .unwrap();
18089        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18090        assert!(registry.get_module("vault").unwrap().is_some());
18091    }
18092
18093    #[test]
18094    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18095        let registry = Arc::new(Registry::default());
18096        let supervisor = SupervisorHandle::new();
18097        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18098        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18099        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18100
18101        let squat = handler
18102            .handle_control(
18103                ConnectionId::new(1),
18104                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18105            )
18106            .unwrap();
18107        assert_eq!(squat[0].header.ty, FrameType::Error);
18108        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18109        assert!(parse_error(&squat[0])["message"]
18110            .as_str()
18111            .unwrap()
18112            .contains("fed:"));
18113
18114        let accepted_peer = handler
18115            .handle_control(
18116                ConnectionId::new(2),
18117                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18118            )
18119            .unwrap();
18120        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18121
18122        let accepted_short = handler
18123            .handle_control(
18124                ConnectionId::new(3),
18125                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18126            )
18127            .unwrap();
18128        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18129
18130        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18131            let response = handler
18132                .handle_control(
18133                    ConnectionId::new(conn),
18134                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18135                )
18136                .unwrap();
18137            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18138        }
18139    }
18140
18141    #[test]
18142    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18143        let registry = Arc::new(Registry::default());
18144        let supervisor = SupervisorHandle::new();
18145        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18146        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18147        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18148        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18149
18150        let owner_nonce = handler
18151            .handle_control(
18152                ConnectionId::new(1),
18153                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18154            )
18155            .unwrap();
18156        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18157        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18158        assert!(registry.get_module("fed:special").unwrap().is_none());
18159
18160        let exact_nonce = handler
18161            .handle_control(
18162                ConnectionId::new(2),
18163                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18164            )
18165            .unwrap();
18166        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18167        assert!(registry.get_module("fed:special").unwrap().is_some());
18168    }
18169
18170    #[test]
18171    fn non_reserved_module_ignores_launch_nonce() {
18172        let registry = Arc::new(Registry::default());
18173        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18174        // registration succeeds whether a spawned process echoes a nonce or not.
18175        let handler = ControlHandler::new(Arc::clone(&registry));
18176        let no_nonce = handler
18177            .handle_control(
18178                ConnectionId::new(1),
18179                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18180            )
18181            .unwrap();
18182        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18183        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18184
18185        let echoed_nonce = handler
18186            .handle_control(
18187                ConnectionId::new(2),
18188                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18189            )
18190            .unwrap();
18191        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18192        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18193    }
18194
18195    #[test]
18196    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18197        let handler = ControlHandler::default();
18198        let conn = ConnectionId::new(1);
18199        let malformed = Frame::build(
18200            FrameType::Hello,
18201            control_flags(),
18202            0,
18203            0,
18204            3,
18205            b"{not json".to_vec(),
18206        )
18207        .unwrap();
18208
18209        let error = handler.handle_control(conn, malformed).unwrap();
18210        assert_eq!(error[0].header.ty, FrameType::Error);
18211        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18212
18213        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18214        let pong = handler.handle_control(conn, ping).unwrap();
18215        assert_eq!(pong[0].header.ty, FrameType::Pong);
18216        assert_eq!(pong[0].header.corr, 4);
18217    }
18218
18219    #[test]
18220    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18221        let registry = Arc::new(Registry::default());
18222        let handler = ControlHandler::new(Arc::clone(&registry));
18223
18224        handler
18225            .handle_control(
18226                ConnectionId::new(1),
18227                hello_frame("aft", PROTOCOL_VERSION, 1),
18228            )
18229            .unwrap();
18230        let duplicate = handler
18231            .handle_control(
18232                ConnectionId::new(2),
18233                hello_frame("aft", PROTOCOL_VERSION, 2),
18234            )
18235            .unwrap();
18236
18237        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18238        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18239        let registration = registry.get_module("aft").unwrap().unwrap();
18240        assert_eq!(registration.connection_id, ConnectionId::new(1));
18241    }
18242
18243    #[test]
18244    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18245        let registry = Arc::new(Registry::default());
18246        let forwarding = Arc::new(ForwardingTable::default());
18247        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18248        let handler =
18249            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18250                .with_process_liveness(process_liveness);
18251        let (ctx, route_channel, route_epoch) =
18252            bind_liveness_route(&registry, &forwarding, "aft-dead");
18253        let responses = handler
18254            .handle_route_poll(
18255                &ctx,
18256                route_poll_frame(41, PollKind::Liveness, route_channel),
18257                route_channel,
18258                route_epoch,
18259                PollKind::Liveness,
18260            )
18261            .unwrap();
18262
18263        assert_eq!(responses.len(), 1);
18264        assert_eq!(responses[0].header.ty, FrameType::Response);
18265        assert_route_poll_liveness(&responses[0], false);
18266    }
18267
18268    #[test]
18269    fn liveness_poll_without_process_source_uses_bound_route() {
18270        let registry = Arc::new(Registry::default());
18271        let forwarding = Arc::new(ForwardingTable::default());
18272        let handler =
18273            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18274        let (ctx, route_channel, route_epoch) =
18275            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18276        let responses = handler
18277            .handle_route_poll(
18278                &ctx,
18279                route_poll_frame(42, PollKind::Liveness, route_channel),
18280                route_channel,
18281                route_epoch,
18282                PollKind::Liveness,
18283            )
18284            .unwrap();
18285
18286        assert_route_poll_liveness(&responses[0], true);
18287    }
18288
18289    #[test]
18290    fn liveness_poll_untracked_process_source_uses_bound_route() {
18291        let registry = Arc::new(Registry::default());
18292        let forwarding = Arc::new(ForwardingTable::default());
18293        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18294        let handler =
18295            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18296                .with_process_liveness(process_liveness);
18297        let (ctx, route_channel, route_epoch) =
18298            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18299        let responses = handler
18300            .handle_route_poll(
18301                &ctx,
18302                route_poll_frame(43, PollKind::Liveness, route_channel),
18303                route_channel,
18304                route_epoch,
18305                PollKind::Liveness,
18306            )
18307            .unwrap();
18308
18309        assert_route_poll_liveness(&responses[0], true);
18310    }
18311
18312    #[tokio::test]
18313    async fn unknown_op_returns_unknown_control_op() {
18314        let handler = ControlHandler::default();
18315        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18316        let request = Frame::build(
18317            FrameType::Request,
18318            control_flags(),
18319            0,
18320            0,
18321            55,
18322            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18323        )
18324        .unwrap();
18325
18326        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18327
18328        assert_eq!(response.len(), 1);
18329        assert_eq!(response[0].header.ty, FrameType::Error);
18330        assert_eq!(response[0].header.corr, 55);
18331        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18332    }
18333
18334    #[tokio::test]
18335    async fn supervisor_provenance_rejects_unknown_exact_module() {
18336        let handler = ControlHandler::default();
18337        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18338        let request = Frame::build(
18339            FrameType::Request,
18340            control_flags(),
18341            0,
18342            0,
18343            57,
18344            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18345        )
18346        .unwrap();
18347
18348        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18349
18350        assert_eq!(response.len(), 1);
18351        assert_eq!(response[0].header.ty, FrameType::Error);
18352        assert_eq!(response[0].header.corr, 57);
18353        let error = parse_error(&response[0]);
18354        assert_eq!(error["code"], "unknown_module");
18355        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18356    }
18357
18358    #[test]
18359    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18360        let expected = subc_control::RunningImageAgreement::Unavailable {
18361            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18362        };
18363        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18364        assert_eq!(handler.provenance_probe_override, Some(expected));
18365    }
18366
18367    #[test]
18368    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18369        let verdict = reload_verdict(
18370            std::path::Path::new("/bin/new"),
18371            Some(std::path::Path::new("/bin/old")),
18372            subc_control::RunningImageAgreement::Unavailable {
18373                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18374            },
18375        );
18376        assert!(matches!(
18377            verdict.path,
18378            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18379                if configured == std::path::Path::new("/bin/new")
18380                    && spawned_from == std::path::Path::new("/bin/old")
18381        ));
18382    }
18383
18384    #[test]
18385    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18386        use subc_control::{
18387            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18388        };
18389        let configured = crate::supervise::ModuleSpec {
18390            script: None,
18391            carry_containment: false,
18392            module_id: "legacy".into(),
18393            program: "/module".into(),
18394            args: Vec::new(),
18395            env: Vec::new(),
18396            reserved: false,
18397            reserved_prefixes: Vec::new(),
18398            protocol: subc_control::ModuleProtocol::Subc,
18399            overlap: Default::default(),
18400        };
18401        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18402        assert_eq!(
18403            launch_spec_agreement(&configured, false, Some(&digest)),
18404            Agreement::Unavailable {
18405                reason: Reason::NotRunning
18406            }
18407        );
18408        assert_eq!(
18409            launch_spec_agreement(&configured, true, None),
18410            Agreement::Unavailable {
18411                reason: Reason::SpawnedSpecUnavailable
18412            }
18413        );
18414        assert_eq!(
18415            launch_spec_agreement(&configured, true, Some(&digest)),
18416            Agreement::Match
18417        );
18418    }
18419
18420    #[cfg(windows)]
18421    #[test]
18422    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18423        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18424        let configured = dir.join("module.exe");
18425        std::fs::write(&configured, b"executable path fixture").unwrap();
18426        let spawned = std::fs::canonicalize(&configured).unwrap();
18427        assert_ne!(
18428            configured, spawned,
18429            "fixture must exercise different path spellings"
18430        );
18431        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18432        let lower_case = configured.to_string_lossy().to_lowercase();
18433        for spelling in [
18434            &configured,
18435            Path::new(&forward_slashes),
18436            Path::new(&lower_case),
18437        ] {
18438            let verdict = reload_verdict(
18439                spelling,
18440                Some(&spawned),
18441                subc_control::RunningImageAgreement::Unavailable {
18442                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18443                },
18444            );
18445            assert_eq!(
18446                verdict.path,
18447                ReloadPathAgreement::Match,
18448                "configured {spelling:?}, spawned {spawned:?}"
18449            );
18450        }
18451    }
18452
18453    #[cfg(windows)]
18454    #[test]
18455    fn windows_reload_path_keeps_different_existing_program_pending() {
18456        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18457        let old = dir.join("old.exe");
18458        let new = dir.join("new.exe");
18459        std::fs::write(&old, b"same executable content").unwrap();
18460        std::fs::copy(&old, &new).unwrap();
18461        let spawned = std::fs::canonicalize(&old).unwrap();
18462        let image = subc_control::RunningImageAgreement::Unavailable {
18463            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18464        };
18465        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18466        assert!(
18467            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18468            if configured == new && spawned_from == spawned)
18469        );
18470        let missing = dir.join("missing.exe");
18471        assert!(matches!(
18472            reload_verdict(&missing, Some(&spawned), image).path,
18473            ReloadPathAgreement::Mismatch { .. }
18474        ));
18475    }
18476
18477    #[test]
18478    fn reload_verdict_detects_replaced_image_at_same_path() {
18479        let image = subc_control::RunningImageAgreement::Mismatch {
18480            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18481                digest: "old".into(),
18482            },
18483            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18484                digest: "new".into(),
18485            },
18486        };
18487        let verdict = reload_verdict(
18488            std::path::Path::new("/bin/same"),
18489            Some(std::path::Path::new("/bin/same")),
18490            image.clone(),
18491        );
18492        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18493        assert_eq!(verdict.image, image);
18494    }
18495
18496    #[test]
18497    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18498        let image = subc_control::RunningImageAgreement::Unavailable {
18499            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18500        };
18501        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18502        assert_eq!(
18503            verdict.path,
18504            subc_control::ReloadPathAgreement::Unavailable {
18505                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18506            }
18507        );
18508        assert_eq!(verdict.image, image);
18509
18510        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18511            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18512        };
18513        let verdict = reload_verdict(
18514            std::path::Path::new("/bin/same"),
18515            Some(std::path::Path::new("/bin/same")),
18516            unconfirmed.clone(),
18517        );
18518        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18519        assert_eq!(verdict.image, unconfirmed);
18520    }
18521
18522    #[test]
18523    fn reload_verdict_preserves_each_image_unavailability_reason() {
18524        use subc_control::RunningImageUnavailableReason as Reason;
18525
18526        for reason in [
18527            Reason::NotRunning,
18528            Reason::UnsupportedPlatform,
18529            Reason::RunningExecutableUnreadable,
18530            Reason::SpawnedPathUnreadable,
18531            Reason::HashFailed,
18532            Reason::ProcessIdentityUnconfirmed,
18533            Reason::Unknown("future_probe_reason".to_string()),
18534        ] {
18535            let image = subc_control::RunningImageAgreement::Unavailable {
18536                reason: reason.clone(),
18537            };
18538            let verdict = reload_verdict(
18539                std::path::Path::new("/bin/same"),
18540                Some(std::path::Path::new("/bin/same")),
18541                image.clone(),
18542            );
18543            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18544            assert_eq!(verdict.image, image, "{reason:?}");
18545        }
18546    }
18547
18548    #[tokio::test]
18549    async fn malformed_control_bodies_return_invalid_control_body() {
18550        let handler = ControlHandler::default();
18551        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18552
18553        for (corr, body) in [
18554            (56, br#"{"route_channel":1}"#.as_slice()),
18555            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18556            (
18557                58,
18558                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18559            ),
18560        ] {
18561            let request = Frame::build(
18562                FrameType::Request,
18563                control_flags(),
18564                0,
18565                0,
18566                corr,
18567                body.to_vec(),
18568            )
18569            .unwrap();
18570            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18571
18572            assert_eq!(response.len(), 1);
18573            assert_eq!(response[0].header.ty, FrameType::Error);
18574            assert_eq!(response[0].header.corr, corr);
18575            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18576        }
18577    }
18578
18579    #[tokio::test]
18580    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18581        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18582        let registry = Arc::new(Registry::default());
18583        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18584        let router = Router::with_control_handler(Arc::clone(&control));
18585        let connection = router.begin_connection();
18586        let (ctx, mut rx) = route_ctx(connection.id());
18587
18588        router
18589            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18590            .await
18591            .unwrap();
18592        let response = rx.recv().await.unwrap();
18593        let ack = parse_ack(&response);
18594        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18595        let channel = 1;
18596
18597        let goodbye =
18598            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18599        router.route_for_connection(&ctx, goodbye).await.unwrap();
18600        assert!(rx.try_recv().is_err());
18601        assert!(registry.get_module("aft").unwrap().is_none());
18602
18603        router
18604            .route_for_connection(&ctx, channel_request(channel, 13))
18605            .await
18606            .unwrap();
18607        let error_frame = rx.recv().await.unwrap();
18608        assert_eq!(error_frame.header.ty, FrameType::Error);
18609        assert_eq!(error_frame.header.channel, channel);
18610        let captured = crate::router::test_log::captured_logs(&logs);
18611        assert_eq!(
18612            captured
18613                .lines()
18614                .filter(|line| {
18615                    line.contains("module_id=aft")
18616                        && line.contains("reason=explicit_goodbye")
18617                        && line.contains("module registration ended")
18618                })
18619                .count(),
18620            1,
18621            "unexpected GOODBYE registry log: {captured}"
18622        );
18623    }
18624
18625    #[tokio::test]
18626    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18627        let registry = Arc::new(Registry::default());
18628        let handler = ControlHandler::new(registry).with_capability_config(
18629            [("prov".to_string(), true), ("cons".to_string(), true)],
18630            BTreeMap::new(),
18631        );
18632        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18633        register_capability_manifest(
18634            &handler,
18635            &provider_ctx,
18636            &mut provider_rx,
18637            capability_manifest("prov", &["thing/v1"], &[]),
18638            1,
18639        )
18640        .await;
18641        let mut consumer = capability_manifest("cons", &[], &[]);
18642        consumer.capabilities.as_mut().unwrap().requires.push(
18643            subc_protocol::manifest::CapabilityRequirement {
18644                capability: "thing/v1".to_string(),
18645                need: subc_protocol::manifest::CapabilityNeed::Required,
18646            },
18647        );
18648        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18649        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18650        assert_eq!(
18651            handler.capability_evaluator.verdict("cons", "thing/v1"),
18652            Some(CapabilityVerdict::Provided)
18653        );
18654        let (mut client_rx, _) = open_route_for_capability_test(
18655            &handler,
18656            &provider_ctx,
18657            &mut provider_rx,
18658            703,
18659            3,
18660            "prov",
18661            None,
18662        )
18663        .await;
18664        let goodbye =
18665            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18666        handler
18667            .handle_control_frame(&provider_ctx, goodbye)
18668            .await
18669            .unwrap();
18670        assert_eq!(
18671            handler.capability_evaluator.verdict("cons", "thing/v1"),
18672            Some(CapabilityVerdict::NeverProvided)
18673        );
18674        let closed = client_rx
18675            .try_recv()
18676            .expect("GOODBYE pushes route.closed before route GOODBYE");
18677        assert!(
18678            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18679            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18680        );
18681        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18682        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18683    }
18684
18685    struct RouteClosedFixture {
18686        handler: ControlHandler,
18687        #[cfg(unix)]
18688        supervisor: Supervisor,
18689        module_ctx: RouteCtx,
18690        #[cfg(unix)]
18691        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18692        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18693        route: Arc<crate::forwarding::RouteBinding>,
18694    }
18695
18696    async fn route_closed_fixture() -> RouteClosedFixture {
18697        let registry = Arc::new(Registry::default());
18698        let handler = ControlHandler::new(Arc::clone(&registry));
18699        #[cfg(unix)]
18700        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18701            .with_forwarding(Arc::clone(&handler.forwarding));
18702        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18703        register_capability_manifest(
18704            &handler,
18705            &module_ctx,
18706            &mut module_rx,
18707            capability_manifest("prov", &[], &[]),
18708            1,
18709        )
18710        .await;
18711        let (client_rx, bind) = open_route_for_capability_test(
18712            &handler,
18713            &module_ctx,
18714            &mut module_rx,
18715            702,
18716            2,
18717            "prov",
18718            None,
18719        )
18720        .await;
18721        let ModuleControlRequest::RouteBind {
18722            route_channel: channel,
18723            epoch: route_epoch,
18724            ..
18725        } = bind
18726        else {
18727            panic!("expected route.bind");
18728        };
18729        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18730            handler
18731                .forwarding
18732                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18733                .unwrap()
18734        else {
18735            panic!("the acknowledged route must be bound");
18736        };
18737        RouteClosedFixture {
18738            handler,
18739            #[cfg(unix)]
18740            supervisor,
18741            module_ctx,
18742            #[cfg(unix)]
18743            module_rx,
18744            client_rx,
18745            route,
18746        }
18747    }
18748
18749    impl RouteClosedFixture {
18750        #[cfg(unix)]
18751        async fn cut(&mut self) {
18752            let notices = async {
18753                let mut draining = self.module_rx.recv().await.unwrap();
18754                assert!(matches!(
18755                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18756                        &draining.body
18757                    )
18758                    .unwrap(),
18759                    subc_protocol::session::ModuleControlCommand::Draining {
18760                        reason: RouteCloseReason::Disable,
18761                        ..
18762                    }
18763                ));
18764                draining.flushed.take().unwrap().send(()).unwrap();
18765                let mut closing = self.client_rx.recv().await.unwrap();
18766                assert!(matches!(
18767                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18768                    ClientControlPush::RouteClosing {
18769                        reason: RouteCloseReason::Restart,
18770                        ..
18771                    }
18772                ));
18773                closing.flushed.take().unwrap().send(()).unwrap();
18774            };
18775            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18776            result.unwrap();
18777        }
18778
18779        fn disconnect(&mut self) -> ClientControlPush {
18780            self.handler
18781                .cleanup_connection(self.module_ctx.connection_id)
18782                .unwrap();
18783            let closed = self.client_rx.try_recv().unwrap();
18784            assert_eq!(closed.header.ty, FrameType::Push);
18785            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18786            assert!(matches!(
18787                &push,
18788                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18789                    if channels == &[self.route.client_channel]
18790            ));
18791            assert_eq!(
18792                self.client_rx.try_recv().unwrap().header.ty,
18793                FrameType::Goodbye
18794            );
18795            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18796            push
18797        }
18798    }
18799
18800    #[cfg(unix)]
18801    #[tokio::test(start_paused = true)]
18802    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18803        let mut fixture = route_closed_fixture().await;
18804        fixture.cut().await;
18805        assert!(matches!(
18806            fixture.disconnect(),
18807            ClientControlPush::RouteClosed {
18808                reason: RouteCloseReason::Restart,
18809                drained: true,
18810                ..
18811            }
18812        ));
18813    }
18814
18815    #[cfg(unix)]
18816    #[tokio::test(start_paused = true)]
18817    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18818        let mut fixture = route_closed_fixture().await;
18819        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18820        let started = tokio::time::Instant::now();
18821        fixture.cut().await;
18822        assert!(started.elapsed() >= Duration::from_secs(2));
18823        assert_eq!(fixture.route.flow.in_flight(), 1);
18824        assert!(matches!(
18825            fixture.disconnect(),
18826            ClientControlPush::RouteClosed {
18827                reason: RouteCloseReason::Restart,
18828                drained: false,
18829                ..
18830            }
18831        ));
18832    }
18833
18834    #[tokio::test]
18835    async fn module_connection_crash_reports_crash_and_not_drained() {
18836        let mut fixture = route_closed_fixture().await;
18837        // The server calls cleanup_connection on module EOF. Without a planned
18838        // daemon shutdown, that disconnect must remain a crash with no prior
18839        // route.closing notice, even when the route has no in-flight calls.
18840        assert!(matches!(
18841            fixture.disconnect(),
18842            ClientControlPush::RouteClosed {
18843                reason: RouteCloseReason::Crash,
18844                drained: false,
18845                ..
18846            }
18847        ));
18848    }
18849
18850    #[tokio::test]
18851    async fn dropping_router_connection_releases_registration() {
18852        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18853        let registry = Arc::new(Registry::default());
18854        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18855        let router = Router::with_control_handler(Arc::clone(&control));
18856        let connection = router.begin_connection();
18857        let connection_id = connection.id();
18858        let (ctx, mut rx) = route_ctx(connection_id);
18859
18860        router
18861            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18862            .await
18863            .unwrap();
18864        let response = rx.recv().await.unwrap();
18865        let ack = parse_ack(&response);
18866        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18867        assert!(registry.get_module("aft").unwrap().is_some());
18868
18869        drop(connection);
18870
18871        assert!(registry.get_module("aft").unwrap().is_none());
18872        assert_eq!(registry.active_registration_count().unwrap(), 0);
18873
18874        control
18875            .cleanup_connection(ConnectionId::new(u64::MAX))
18876            .unwrap();
18877        let captured = crate::router::test_log::captured_logs(&logs);
18878        println!("captured registry lifecycle logs:\n{captured}");
18879        let events: Vec<_> = captured
18880            .lines()
18881            .filter(|line| {
18882                line.contains("module registered module_id=aft ")
18883                    || line.contains("module registration ended")
18884            })
18885            .collect();
18886        assert_eq!(
18887            events.len(),
18888            2,
18889            "unexpected registry lifecycle logs: {captured}"
18890        );
18891        assert!(events[0].contains("module registered module_id=aft "));
18892        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18893        assert!(events[1].contains(&format!(
18894            "module_id=aft connection_id={}",
18895            connection_id.get()
18896        )));
18897        assert!(events[1].contains("reason=connection_closed"));
18898        assert!(events[1].contains("module registration ended"));
18899        assert_eq!(
18900            captured
18901                .lines()
18902                .filter(|line| line.contains("module registered module_id=aft "))
18903                .count(),
18904            1,
18905            "legacy registration admission line must appear once: {captured}"
18906        );
18907    }
18908
18909    #[tokio::test]
18910    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18911        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18912        let registry = Arc::new(Registry::default());
18913        let control = ControlHandler::new(Arc::clone(&registry));
18914        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18915        hello_via_sink(
18916            &control,
18917            &ctx,
18918            &mut rx,
18919            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18920        )
18921        .await;
18922
18923        let captured = crate::router::test_log::captured_logs(&logs);
18924        let admissions: Vec<_> = captured
18925            .lines()
18926            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18927            .collect();
18928        assert_eq!(
18929            admissions.len(),
18930            1,
18931            "legacy admission line must remain exactly once: {captured}"
18932        );
18933        assert!(admissions[0].contains("routable_provider=true"));
18934        assert!(admissions[0].contains("connection_id=777"));
18935    }
18936
18937    fn capability_manifest(
18938        module_id: &str,
18939        provides: &[&str],
18940        must_never_reach: &[&str],
18941    ) -> ModuleManifest {
18942        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18943        manifest.capabilities = Some(CapabilityDeclarations {
18944            provides: provides
18945                .iter()
18946                .map(|capability| (*capability).to_string())
18947                .collect(),
18948            requires: Vec::new(),
18949            must_never_reach: must_never_reach
18950                .iter()
18951                .map(|capability| (*capability).to_string())
18952                .collect(),
18953        });
18954        manifest
18955    }
18956
18957    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18958        Frame::build(
18959            FrameType::Hello,
18960            control_flags(),
18961            0,
18962            0,
18963            corr,
18964            serde_json::to_vec(&ModuleHelloBody {
18965                protocol_ver: manifest.protocol_ver,
18966                manifest,
18967                control_ops: None,
18968                launch_nonce: None,
18969            })
18970            .expect("capability test HELLO serializes"),
18971        )
18972        .expect("capability test HELLO frame builds")
18973    }
18974
18975    fn catalog_update_with_capabilities_frame(
18976        corr: u64,
18977        capabilities: CapabilityDeclarations,
18978    ) -> Frame {
18979        Frame::build(
18980            FrameType::Request,
18981            control_flags(),
18982            0,
18983            0,
18984            corr,
18985            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18986                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18987                capabilities: Some(capabilities),
18988                ready: None,
18989            })
18990            .expect("capability catalog.update serializes"),
18991        )
18992        .expect("capability catalog.update frame builds")
18993    }
18994
18995    async fn register_capability_manifest(
18996        handler: &ControlHandler,
18997        ctx: &RouteCtx,
18998        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18999        manifest: ModuleManifest,
19000        corr: u64,
19001    ) {
19002        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
19003    }
19004
19005    async fn open_route_for_capability_test(
19006        handler: &ControlHandler,
19007        target_ctx: &RouteCtx,
19008        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
19009        client_connection_id: u64,
19010        corr: u64,
19011        target_module_id: &str,
19012        consumer_identity: Option<ConsumerIdentity>,
19013    ) -> (
19014        mpsc::Receiver<crate::router::OutboundFrame>,
19015        ModuleControlRequest,
19016    ) {
19017        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
19018        let route_handler = handler.clone();
19019        let target_module_id = target_module_id.to_string();
19020        let route_task = tokio::spawn(async move {
19021            route_handler
19022                .handle_control_frame(
19023                    &client_ctx,
19024                    route_open_frame_with_admission_facts(
19025                        corr,
19026                        &target_module_id,
19027                        unique_project_root("admission-facts"),
19028                        consumer_identity,
19029                        None,
19030                    ),
19031                )
19032                .await
19033                .expect("capability test route.open succeeds")
19034        });
19035        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
19036            .await
19037            .expect("capability test route.open must reach route.bind")
19038            .expect("target control receiver stays open");
19039        let bind_request: ModuleControlRequest =
19040            serde_json::from_slice(&bind.body).expect("route.bind decodes");
19041        handler
19042            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
19043            .await
19044            .expect("capability test route.bind ACK succeeds");
19045        assert!(route_task.await.expect("route.open task joins").is_empty());
19046        let opened = client_rx
19047            .recv()
19048            .await
19049            .expect("successful route.open publishes a response");
19050        assert!(matches!(
19051            serde_json::from_slice::<ClientControlResponse>(&opened.body),
19052            Ok(ClientControlResponse::RouteOpen { .. })
19053        ));
19054        (client_rx, bind_request)
19055    }
19056
19057    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
19058        assert_eq!(frame.header.ty, FrameType::Push);
19059        assert_eq!(frame.header.channel, 0);
19060        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
19061            .expect("route.closed control push decodes");
19062        let ClientControlPush::RouteClosed { channels, .. } = &push else {
19063            panic!("expected route.closed");
19064        };
19065        assert_eq!(channels.len(), 1, "exactly one violating route closed");
19066        let closed_channel = channels[0];
19067        let channels = channels.clone();
19068        assert_eq!(
19069            push,
19070            ClientControlPush::RouteClosed {
19071                module_id: target_module_id.to_string(),
19072                channels,
19073                reason: RouteCloseReason::CapabilityDenied,
19074                drained: false,
19075                abandoned: 0,
19076                excluded_subscriptions: 0,
19077                terminal: Some(false),
19078            }
19079        );
19080        closed_channel
19081    }
19082
19083    #[tokio::test]
19084    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
19085        let registry = Arc::new(Registry::default());
19086        let forwarding = Arc::new(ForwardingTable::default());
19087        let supervisor = SupervisorHandle::new();
19088        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19089        let handler =
19090            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19091                .with_supervisor(supervisor);
19092        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19093        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19094        register_capability_manifest(
19095            &handler,
19096            &target_ctx,
19097            &mut target_rx,
19098            capability_manifest("target", &["credentials-provider/v1"], &[]),
19099            1,
19100        )
19101        .await;
19102        register_capability_manifest(
19103            &handler,
19104            &opener_ctx,
19105            &mut opener_rx,
19106            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19107            2,
19108        )
19109        .await;
19110
19111        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19112        let replies = handler
19113            .handle_control_frame(
19114                &client_ctx,
19115                route_open_frame_with_admission_facts(
19116                    3,
19117                    "target",
19118                    unique_project_root("admission-facts"),
19119                    Some(ConsumerIdentity {
19120                        module_id: "opener".to_string(),
19121                        launch_nonce: "opener-nonce".to_string(),
19122                    }),
19123                    None,
19124                ),
19125            )
19126            .await
19127            .expect("denied route.open returns a typed frame");
19128        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19129        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19130        assert!(
19131            target_rx.try_recv().is_err(),
19132            "forbidden route.open must not relay route.bind"
19133        );
19134    }
19135
19136    #[tokio::test]
19137    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19138        let registry = Arc::new(Registry::default());
19139        let forwarding = Arc::new(ForwardingTable::default());
19140        let supervisor = SupervisorHandle::new();
19141        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19142        let handler =
19143            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19144                .with_supervisor(supervisor);
19145        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19146        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19147        register_capability_manifest(
19148            &handler,
19149            &target_ctx,
19150            &mut target_rx,
19151            capability_manifest("target", &["credentials-provider/v1"], &[]),
19152            1,
19153        )
19154        .await;
19155        register_capability_manifest(
19156            &handler,
19157            &old_opener_ctx,
19158            &mut old_opener_rx,
19159            capability_manifest("opener", &[], &[]),
19160            2,
19161        )
19162        .await;
19163        let (mut client_rx, _) = open_route_for_capability_test(
19164            &handler,
19165            &target_ctx,
19166            &mut target_rx,
19167            712,
19168            3,
19169            "target",
19170            Some(ConsumerIdentity {
19171                module_id: "opener".to_string(),
19172                launch_nonce: "opener-nonce".to_string(),
19173            }),
19174        )
19175        .await;
19176        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19177
19178        handler
19179            .cleanup_connection(old_opener_ctx.connection_id)
19180            .expect("old opener registration cleans up");
19181        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19182        register_capability_manifest(
19183            &handler,
19184            &new_opener_ctx,
19185            &mut new_opener_rx,
19186            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19187            4,
19188        )
19189        .await;
19190
19191        let closed_channel = assert_capability_denied_push(
19192            client_rx
19193                .try_recv()
19194                .expect("HELLO deny addition must emit route.closed")
19195                .frame,
19196            "target",
19197        );
19198        let goodbye = client_rx
19199            .try_recv()
19200            .expect("HELLO deny addition must send the client a route GOODBYE")
19201            .frame;
19202        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19203        assert_eq!(goodbye.header.channel, closed_channel);
19204        assert_ne!(goodbye.header.channel, 0);
19205        assert_ne!(goodbye.header.epoch, 0);
19206        assert!(client_rx.try_recv().is_err());
19207        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19208        assert!(matches!(
19209            target_rx.try_recv(),
19210            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19211        ));
19212    }
19213
19214    #[tokio::test]
19215    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19216        let registry = Arc::new(Registry::default());
19217        let forwarding = Arc::new(ForwardingTable::default());
19218        let supervisor = SupervisorHandle::new();
19219        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19220        let handler =
19221            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19222                .with_supervisor(supervisor);
19223        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19224        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19225        register_capability_manifest(
19226            &handler,
19227            &target_ctx,
19228            &mut target_rx,
19229            capability_manifest("target", &[], &[]),
19230            1,
19231        )
19232        .await;
19233        register_capability_manifest(
19234            &handler,
19235            &opener_ctx,
19236            &mut opener_rx,
19237            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19238            2,
19239        )
19240        .await;
19241        let (mut client_rx, _) = open_route_for_capability_test(
19242            &handler,
19243            &target_ctx,
19244            &mut target_rx,
19245            722,
19246            3,
19247            "target",
19248            Some(ConsumerIdentity {
19249                module_id: "opener".to_string(),
19250                launch_nonce: "opener-nonce".to_string(),
19251            }),
19252        )
19253        .await;
19254        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19255
19256        let replies = handler
19257            .handle_control_frame(
19258                &target_ctx,
19259                catalog_update_with_capabilities_frame(
19260                    4,
19261                    CapabilityDeclarations {
19262                        provides: vec!["credentials-provider/v1".to_string()],
19263                        requires: Vec::new(),
19264                        must_never_reach: Vec::new(),
19265                    },
19266                ),
19267            )
19268            .await
19269            .expect("claim catalog.update succeeds");
19270        assert!(matches!(
19271            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19272            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19273        ));
19274        let closed_channel = assert_capability_denied_push(
19275            client_rx
19276                .try_recv()
19277                .expect("claim addition must emit route.closed")
19278                .frame,
19279            "target",
19280        );
19281        let goodbye = client_rx
19282            .try_recv()
19283            .expect("claim addition must send the client a route GOODBYE")
19284            .frame;
19285        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19286        assert_eq!(goodbye.header.channel, closed_channel);
19287        assert_ne!(goodbye.header.channel, 0);
19288        assert_ne!(goodbye.header.epoch, 0);
19289        assert!(client_rx.try_recv().is_err());
19290        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19291        assert!(matches!(
19292            target_rx.try_recv(),
19293            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19294        ));
19295    }
19296
19297    #[tokio::test]
19298    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19299        let registry = Arc::new(Registry::default());
19300        let forwarding = Arc::new(ForwardingTable::default());
19301        let supervisor = SupervisorHandle::new();
19302        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19303        let handler =
19304            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19305                .with_supervisor(supervisor);
19306        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19307        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19308        register_capability_manifest(
19309            &handler,
19310            &target_ctx,
19311            &mut target_rx,
19312            capability_manifest("target", &["credentials-provider/v1"], &[]),
19313            1,
19314        )
19315        .await;
19316        register_capability_manifest(
19317            &handler,
19318            &opener_ctx,
19319            &mut opener_rx,
19320            capability_manifest("opener", &[], &[]),
19321            2,
19322        )
19323        .await;
19324        let (mut client_rx, _) = open_route_for_capability_test(
19325            &handler,
19326            &target_ctx,
19327            &mut target_rx,
19328            732,
19329            3,
19330            "target",
19331            Some(ConsumerIdentity {
19332                module_id: "opener".to_string(),
19333                launch_nonce: "opener-nonce".to_string(),
19334            }),
19335        )
19336        .await;
19337        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19338
19339        handler
19340            .handle_control_frame(
19341                &target_ctx,
19342                catalog_update_with_capabilities_frame(
19343                    4,
19344                    CapabilityDeclarations {
19345                        provides: Vec::new(),
19346                        requires: Vec::new(),
19347                        must_never_reach: Vec::new(),
19348                    },
19349                ),
19350            )
19351            .await
19352            .expect("claim removal catalog.update succeeds");
19353        assert_eq!(
19354            forwarding.active_binding_count().unwrap(),
19355            1,
19356            "removing an attested target claim must leave the route census unchanged"
19357        );
19358        assert!(
19359            client_rx.try_recv().is_err(),
19360            "claim removal must not emit route.closed or a client route GOODBYE"
19361        );
19362        assert!(
19363            target_rx.try_recv().is_err(),
19364            "claim removal must not send the target a route GOODBYE"
19365        );
19366    }
19367
19368    /// A direct client may open a route to a denied capability provider; this
19369    /// policy applies only to attested supervised module origins, not to direct clients.
19370    #[tokio::test]
19371    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19372        let registry = Arc::new(Registry::default());
19373        let forwarding = Arc::new(ForwardingTable::default());
19374        let supervisor = SupervisorHandle::new();
19375        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19376        let handler =
19377            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19378                .with_supervisor(supervisor);
19379        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19380        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19381        register_capability_manifest(
19382            &handler,
19383            &target_ctx,
19384            &mut target_rx,
19385            capability_manifest("target", &["credentials-provider/v1"], &[]),
19386            1,
19387        )
19388        .await;
19389        register_capability_manifest(
19390            &handler,
19391            &opener_ctx,
19392            &mut opener_rx,
19393            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19394            2,
19395        )
19396        .await;
19397
19398        let (_client_rx, bind) = open_route_for_capability_test(
19399            &handler,
19400            &target_ctx,
19401            &mut target_rx,
19402            742,
19403            3,
19404            "target",
19405            None,
19406        )
19407        .await;
19408        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19409            panic!("direct scope-honesty route must bind");
19410        };
19411        assert_eq!(principal, Some(Principal::Direct));
19412        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19413    }
19414
19415    /// A module that denies a capability receives no self-route exemption when it
19416    /// also attestedly provides that capability.
19417    #[tokio::test]
19418    async fn must_never_reach_self_route_is_capability_forbidden() {
19419        let registry = Arc::new(Registry::default());
19420        let forwarding = Arc::new(ForwardingTable::default());
19421        let supervisor = SupervisorHandle::new();
19422        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19423        let handler =
19424            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19425                .with_supervisor(supervisor);
19426        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19427        register_capability_manifest(
19428            &handler,
19429            &self_ctx,
19430            &mut self_rx,
19431            capability_manifest(
19432                "self-provider",
19433                &["credentials-provider/v1"],
19434                &["credentials-provider/v1"],
19435            ),
19436            1,
19437        )
19438        .await;
19439
19440        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19441        let replies = handler
19442            .handle_control_frame(
19443                &client_ctx,
19444                route_open_frame_with_admission_facts(
19445                    2,
19446                    "self-provider",
19447                    unique_project_root("admission-facts"),
19448                    Some(ConsumerIdentity {
19449                        module_id: "self-provider".to_string(),
19450                        launch_nonce: "self-nonce".to_string(),
19451                    }),
19452                    None,
19453                ),
19454            )
19455            .await
19456            .expect("self-route refusal returns a typed frame");
19457        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19458        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19459        assert!(
19460            self_rx.try_recv().is_err(),
19461            "self denial must not relay route.bind"
19462        );
19463    }
19464
19465    #[test]
19466    fn unsupported_channel_zero_frame_returns_error() {
19467        let handler = ControlHandler::default();
19468        let request = Frame::build(
19469            FrameType::Request,
19470            control_flags(),
19471            0,
19472            0,
19473            21,
19474            b"opaque".to_vec(),
19475        )
19476        .unwrap();
19477
19478        let response = handler
19479            .handle_control(ConnectionId::new(1), request)
19480            .unwrap();
19481
19482        assert_eq!(response[0].header.ty, FrameType::Error);
19483        assert_eq!(
19484            parse_error(&response[0])["code"],
19485            "unsupported_control_frame"
19486        );
19487    }
19488
19489    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19490    /// a swap is not wired yet, so the candidate is registered here directly
19491    /// into the registry and forwarding candidate slots, the way the swap's
19492    /// HELLO admission will.
19493    mod swap {
19494        use super::*;
19495
19496        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19497        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19498
19499        struct Swap {
19500            registry: Arc<Registry>,
19501            forwarding: Arc<ForwardingTable>,
19502            handler: ControlHandler,
19503            incumbent_ctx: RouteCtx,
19504            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19505            candidate_ctx: RouteCtx,
19506            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19507        }
19508
19509        async fn swap_with_incumbent() -> Swap {
19510            let registry = Arc::new(Registry::default());
19511            let forwarding = Arc::new(ForwardingTable::default());
19512            let handler =
19513                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19514            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19515            hello_via_sink(
19516                &handler,
19517                &incumbent_ctx,
19518                &mut incumbent_rx,
19519                hello_frame("aft", PROTOCOL_VERSION, 7),
19520            )
19521            .await;
19522            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19523            Swap {
19524                registry,
19525                forwarding,
19526                handler,
19527                incumbent_ctx,
19528                incumbent_rx,
19529                candidate_ctx,
19530                candidate_rx,
19531            }
19532        }
19533
19534        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19535            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19536            candidate_manifest.ready = ready;
19537            let registration = swap
19538                .registry
19539                .register_candidate_with_control_ops(
19540                    candidate_manifest,
19541                    PROTOCOL_VERSION,
19542                    CANDIDATE,
19543                    module_baseline_control_ops(),
19544                )
19545                .unwrap();
19546            swap.forwarding
19547                .register_candidate_module_connection(
19548                    CANDIDATE,
19549                    "aft".to_string(),
19550                    PROTOCOL_VERSION,
19551                    manifest_concurrency(&registration.manifest),
19552                    swap.candidate_ctx.egress.clone(),
19553                )
19554                .unwrap();
19555        }
19556
19557        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19558            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19559            swap.registry.promote_candidate("aft").unwrap().unwrap();
19560            cutover.incumbent.unwrap()
19561        }
19562
19563        /// A swap candidate's HELLO reserves its candidate registry entry
19564        /// before installing its candidate forwarding endpoint. The swap
19565        /// supervisor promotes a ready candidate as soon as it reads it as
19566        /// registered, and promotion cuts forwarding over to the candidate
19567        /// endpoint, so the lookup the supervisor reads
19568        /// (`Registry::published_registration`) must not return the candidate
19569        /// until that endpoint exists. Otherwise the cutover finds no candidate
19570        /// endpoint and the swap fails as if the candidate had disconnected.
19571        #[tokio::test]
19572        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19573            let mut swap = swap_with_incumbent().await;
19574            let hold = Arc::new(std::sync::Barrier::new(2));
19575            let handler = swap
19576                .handler
19577                .clone()
19578                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19579            handler
19580                .supervisor
19581                .open_swap("aft", "candidate-nonce".to_string());
19582            let hello = {
19583                let handler = handler.clone();
19584                let candidate_ctx = swap.candidate_ctx.clone();
19585                std::thread::spawn(move || {
19586                    handler
19587                        .handle_hello(
19588                            candidate_ctx.connection_id,
19589                            Some(candidate_ctx.egress.clone()),
19590                            hello_frame_with_nonce(
19591                                "aft",
19592                                PROTOCOL_VERSION,
19593                                8,
19594                                Some("candidate-nonce"),
19595                            ),
19596                        )
19597                        .unwrap()
19598                })
19599            };
19600
19601            hold.wait();
19602            // Parked: the candidate slot is claimed but not published, and
19603            // forwarding has no candidate endpoint.
19604            assert!(swap
19605                .registry
19606                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19607                .unwrap()
19608                .is_some());
19609            assert!(swap
19610                .registry
19611                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19612                .unwrap()
19613                .is_none());
19614            assert!(swap
19615                .forwarding
19616                .module_endpoint_for_connection(CANDIDATE)
19617                .unwrap()
19618                .is_none());
19619
19620            hold.wait();
19621            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19622            assert_eq!(
19623                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19624                FrameType::HelloAck
19625            );
19626            let published = swap
19627                .registry
19628                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19629                .unwrap()
19630                .expect("candidate is published once its HELLO completes");
19631            assert_eq!(published.connection_id, CANDIDATE);
19632            assert!(swap
19633                .forwarding
19634                .module_endpoint_for_connection(CANDIDATE)
19635                .unwrap()
19636                .is_some());
19637        }
19638
19639        #[tokio::test]
19640        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19641            let mut swap = swap_with_incumbent().await;
19642            let hold = Arc::new(std::sync::Barrier::new(2));
19643            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19644            swap.handler
19645                .supervisor
19646                .open_swap("aft", "candidate-nonce".to_string());
19647            let hello = {
19648                let handler = swap.handler.clone();
19649                let candidate_ctx = swap.candidate_ctx.clone();
19650                std::thread::spawn(move || {
19651                    handler
19652                        .handle_hello(
19653                            CANDIDATE,
19654                            Some(candidate_ctx.egress),
19655                            hello_frame_with_nonce(
19656                                "aft",
19657                                PROTOCOL_VERSION,
19658                                8,
19659                                Some("candidate-nonce"),
19660                            ),
19661                        )
19662                        .unwrap()
19663                })
19664            };
19665            hold.wait();
19666            assert_eq!(
19667                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19668                FrameType::HelloAck
19669            );
19670            let reader_registry = Arc::clone(&swap.registry);
19671            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19672                reader_registry
19673                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19674                    .unwrap()
19675            });
19676            assert!(hello.join().unwrap().is_empty());
19677            assert_eq!(
19678                published
19679                    .expect("ACK makes candidate publication visible")
19680                    .connection_id,
19681                CANDIDATE
19682            );
19683            assert_eq!(
19684                swap.registry.generation().unwrap(),
19685                1,
19686                "candidate is not a second catalog entry"
19687            );
19688        }
19689
19690        #[tokio::test]
19691        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19692            let mut swap = swap_with_incumbent().await;
19693            let hold = Arc::new(std::sync::Barrier::new(2));
19694            let handler = swap
19695                .handler
19696                .clone()
19697                .with_hello_registry_to_forwarding_hold(hold.clone());
19698            handler
19699                .supervisor
19700                .open_swap("aft", "candidate-nonce".into());
19701            let hello = {
19702                let handler = handler.clone();
19703                let ctx = swap.candidate_ctx.clone();
19704                std::thread::spawn(move || {
19705                    handler
19706                        .handle_hello(
19707                            CANDIDATE,
19708                            Some(ctx.egress),
19709                            hello_frame_with_nonce(
19710                                "aft",
19711                                PROTOCOL_VERSION,
19712                                8,
19713                                Some("candidate-nonce"),
19714                            ),
19715                        )
19716                        .unwrap()
19717                })
19718            };
19719            hold.wait();
19720            assert_eq!(
19721                swap.registry
19722                    .deregister_connection(CANDIDATE)
19723                    .unwrap()
19724                    .len(),
19725                1
19726            );
19727            hold.wait();
19728            assert!(hello.join().unwrap().is_empty());
19729            assert_eq!(
19730                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19731                FrameType::HelloAck
19732            );
19733            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19734            assert_eq!(
19735                handler
19736                    .supervisor
19737                    .swap_hello_admission("aft", Some("candidate-nonce")),
19738                SwapHelloAdmission::Candidate,
19739                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19740            );
19741            handler.supervisor.close_swap("aft");
19742        }
19743
19744        fn keyed_total(counters: &Value, key: &str) -> u64 {
19745            counters[key]
19746                .as_object()
19747                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19748                .unwrap_or(0)
19749        }
19750
19751        #[tokio::test]
19752        async fn replacement_logs_old_end_and_new_admission_once() {
19753            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19754            let mut swap = swap_with_incumbent().await;
19755            swap.handler
19756                .supervisor
19757                .open_swap("aft", "candidate-nonce".to_string());
19758            hello_via_sink(
19759                &swap.handler,
19760                &swap.candidate_ctx,
19761                &mut swap.candidate_rx,
19762                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19763            )
19764            .await;
19765            cutover(&swap);
19766            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19767
19768            let captured = crate::router::test_log::captured_logs(&logs);
19769            println!("captured replacement registry logs:\n{captured}");
19770            let new_admissions: Vec<_> = captured
19771                .lines()
19772                .filter(|line| {
19773                    line.contains("connection_id=40")
19774                        && line.contains("swap candidate registered; not routable until cutover")
19775                })
19776                .collect();
19777            assert_eq!(
19778                new_admissions.len(),
19779                1,
19780                "unexpected admission logs: {captured}"
19781            );
19782            assert!(new_admissions[0].contains("module_id=aft"));
19783            assert!(new_admissions[0].contains("connection_id=40"));
19784            assert!(
19785                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19786            );
19787            assert!(new_admissions[0].contains("ready=true"));
19788
19789            let old_admissions: Vec<_> = captured
19790                .lines()
19791                .filter(|line| {
19792                    line.contains("module registered module_id=aft ")
19793                        && line.contains("connection_id=30")
19794                })
19795                .collect();
19796            assert_eq!(
19797                old_admissions.len(),
19798                1,
19799                "unexpected incumbent admission: {captured}"
19800            );
19801
19802            let old_ends: Vec<_> = captured
19803                .lines()
19804                .filter(|line| {
19805                    line.contains("connection_id=30") && line.contains("module registration ended")
19806                })
19807                .collect();
19808            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19809            assert!(old_ends[0].contains("module_id=aft"));
19810            assert!(old_ends[0].contains("connection_id=30"));
19811            assert!(old_ends[0].contains("reason=replaced"));
19812            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19813            assert_eq!(
19814                captured
19815                    .lines()
19816                    .filter(|line| line.contains("module registration promoted"))
19817                    .count(),
19818                1,
19819                "unexpected promotion logs: {captured}"
19820            );
19821        }
19822
19823        /// An ack from the incumbent for a bind it was sent before cutover,
19824        /// arriving before the incumbent is drained. The incumbent is the live
19825        /// connection carrying every other client's routes, so the ack must
19826        /// not end it: the waiting client is told to retry, the reservation is
19827        /// given back, and the incumbent is told to drop just that binding.
19828        #[tokio::test]
19829        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19830            let mut swap = swap_with_incumbent().await;
19831            let handler = swap.handler.clone();
19832
19833            // A co-tenant route, bound on the incumbent before the swap.
19834            let cotenant = ConnectionId::new(31);
19835            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19836            let (cotenant_task, cotenant_bind) = relay_route_open(
19837                &handler,
19838                cotenant,
19839                &cotenant_ctx.egress,
19840                &mut swap.incumbent_rx,
19841                100,
19842                "aft",
19843                "swap-cotenant",
19844            )
19845            .await;
19846            handler
19847                .handle_control_frame(
19848                    &swap.incumbent_ctx,
19849                    route_bind_ack(cotenant_bind.header.corr),
19850                )
19851                .await
19852                .unwrap();
19853            assert!(cotenant_task.await.unwrap().is_empty());
19854            let (cotenant_channel, cotenant_epoch) =
19855                published_route(&cotenant_rx.recv().await.unwrap());
19856
19857            // A second route.open, relayed to the incumbent and not yet acked.
19858            let caller = ConnectionId::new(32);
19859            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19860            let (caller_task, caller_bind) = relay_route_open(
19861                &handler,
19862                caller,
19863                &caller_ctx.egress,
19864                &mut swap.incumbent_rx,
19865                101,
19866                "aft",
19867                "swap-caller",
19868            )
19869            .await;
19870            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19871
19872            register_candidate(&swap, None);
19873            cutover(&swap);
19874
19875            // The incumbent acks after promotion and before any drain.
19876            let ack = handler
19877                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19878                .await;
19879            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19880            if module_loop_error.is_some() {
19881                // What the connection loop does with an untranslated router
19882                // error: end the connection, releasing every route on it.
19883                handler.cleanup_connection(INCUMBENT).unwrap();
19884            }
19885
19886            // 1. The incumbent's other routes survive.
19887            assert!(
19888                cotenant_rx.try_recv().is_err(),
19889                "the co-tenant route on the incumbent was torn down by one late ack: \
19890                 {module_loop_error:?}"
19891            );
19892            assert!(matches!(
19893                swap.forwarding
19894                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19895                    .unwrap(),
19896                DataRoute::Client(DataRouteState::Bound(_))
19897            ));
19898            assert_eq!(module_loop_error, None);
19899            assert!(swap
19900                .registry
19901                .get_module_by_connection(INCUMBENT)
19902                .unwrap()
19903                .is_some());
19904
19905            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19906            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19907                .await
19908                .expect("the incumbent is told to drop the abandoned binding")
19909                .unwrap()
19910                .frame;
19911            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19912            assert_eq!(goodbye.header.channel, abandoned_channel);
19913            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19914            assert!(swap.incumbent_rx.try_recv().is_err());
19915
19916            // 3. The waiting client gets a retryable refusal and no route.
19917            let response = caller_task.await.unwrap();
19918            assert_eq!(response.len(), 1);
19919            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19920            assert!(caller_rx.try_recv().is_err());
19921
19922            // 4. The reservation pair is given back, and the pending bind
19923            //    settled exactly once: one accepted open (the co-tenant) and one
19924            //    refused open (the caller), nothing counted twice.
19925            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19926            let counters = handler.counters().snapshot();
19927            assert_eq!(
19928                keyed_total(&counters, "route_open_accepted_by_principal"),
19929                1
19930            );
19931            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19932            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19933        }
19934
19935        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19936        /// id would resolve to the promoted candidate and every new route.open
19937        /// would be refused as reloading, leaving neither process routable.
19938        #[tokio::test]
19939        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19940            let mut swap = swap_with_incumbent().await;
19941            register_candidate(&swap, None);
19942            let incumbent = cutover(&swap);
19943            swap.forwarding
19944                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19945                .unwrap()
19946                .expect("the incumbent is still registered");
19947
19948            let client = ConnectionId::new(33);
19949            let (client_ctx, mut client_rx) = route_ctx(client);
19950            let route_handler = swap.handler.clone();
19951            let open_ctx = RouteCtx {
19952                connection_id: client,
19953                egress: client_ctx.egress.clone(),
19954            };
19955            let mut route_task = tokio::spawn(async move {
19956                route_handler
19957                    .handle_control_frame(
19958                        &open_ctx,
19959                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19960                    )
19961                    .await
19962                    .unwrap()
19963            });
19964            let bind = tokio::select! {
19965                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19966                response = &mut route_task => {
19967                    let response = response.unwrap();
19968                    panic!(
19969                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19970                        parse_error(&response[0])["code"]
19971                    );
19972                }
19973            };
19974            swap.handler
19975                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19976                .await
19977                .unwrap();
19978            assert!(route_task.await.unwrap().is_empty());
19979            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19980            match swap
19981                .forwarding
19982                .lookup_data_route(client, channel, epoch)
19983                .unwrap()
19984            {
19985                DataRoute::Client(DataRouteState::Bound(route)) => {
19986                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19987                }
19988                other => panic!("expected a bound route on the candidate, got {other:?}"),
19989            }
19990            assert!(swap.incumbent_rx.try_recv().is_err());
19991        }
19992
19993        /// A candidate declares itself ready with `catalog.update` on its own
19994        /// connection. If the connection-keyed registry lookups searched only the
19995        /// active slot, this would answer `not_registered` and the candidate
19996        /// would never become ready.
19997        #[tokio::test]
19998        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
19999            let swap = swap_with_incumbent().await;
20000            register_candidate(&swap, Some(false));
20001            let update = Frame::build(
20002                FrameType::Request,
20003                control_flags(),
20004                0,
20005                0,
20006                55,
20007                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
20008                    provides: manifest("aft", PROTOCOL_VERSION).provides,
20009                    capabilities: None,
20010                    ready: Some(true),
20011                })
20012                .unwrap(),
20013            )
20014            .unwrap();
20015
20016            let replies = swap
20017                .handler
20018                .handle_control_frame(&swap.candidate_ctx, update)
20019                .await
20020                .unwrap();
20021
20022            assert_eq!(replies.len(), 1);
20023            assert_eq!(
20024                replies[0].header.ty,
20025                FrameType::Response,
20026                "candidate catalog.update was refused: {:?}",
20027                serde_json::from_slice::<Value>(&replies[0].body).ok()
20028            );
20029            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
20030            assert_eq!(
20031                swap.registry
20032                    .get_module("aft")
20033                    .unwrap()
20034                    .unwrap()
20035                    .connection_id,
20036                INCUMBENT
20037            );
20038        }
20039    }
20040
20041    /// The HELLO gate while the supervisor has a swap open: only the nonce it
20042    /// minted for the candidate admits a second process, into the candidate
20043    /// slot, and that check runs ahead of the reserved-module gate.
20044    mod swap_admission {
20045        use super::*;
20046
20047        const INCUMBENT_NONCE: &str = "incumbent-nonce";
20048        const CANDIDATE_NONCE: &str = "candidate-nonce";
20049
20050        fn handler_with_incumbent(
20051            module_id: &str,
20052            reserved: bool,
20053        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
20054            let registry = Arc::new(Registry::default());
20055            let supervisor = SupervisorHandle::new();
20056            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
20057            if reserved {
20058                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
20059            }
20060            let handler =
20061                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
20062            let incumbent = handler
20063                .handle_control(
20064                    ConnectionId::new(1),
20065                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
20066                )
20067                .unwrap();
20068            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
20069            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
20070            (registry, supervisor, handler)
20071        }
20072
20073        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
20074        /// admits every nonce, so while a swap is open the swap gate is the only
20075        /// thing between a key-holder and the candidate slot. A nonce the
20076        /// supervisor did not mint, or none at all, is refused, and neither the
20077        /// incumbent's registration nor the candidate slot moves.
20078        #[test]
20079        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
20080            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
20081
20082            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
20083                let replies = handler
20084                    .handle_control(
20085                        ConnectionId::new(connection),
20086                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
20087                    )
20088                    .unwrap();
20089                assert_eq!(replies[0].header.ty, FrameType::Error);
20090                assert_eq!(
20091                    parse_error(&replies[0])["code"],
20092                    "swap_token_invalid",
20093                    "nonce {nonce:?}"
20094                );
20095            }
20096            assert!(registry.get_candidate("aft").unwrap().is_none());
20097            assert_eq!(
20098                registry.get_module("aft").unwrap().unwrap().connection_id,
20099                ConnectionId::new(1)
20100            );
20101
20102            // Control: the minted token is admitted, into the candidate slot,
20103            // and only once.
20104            let admitted = handler
20105                .handle_control(
20106                    ConnectionId::new(4),
20107                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20108                )
20109                .unwrap();
20110            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20111            assert_eq!(
20112                registry
20113                    .get_candidate("aft")
20114                    .unwrap()
20115                    .unwrap()
20116                    .connection_id,
20117                ConnectionId::new(4)
20118            );
20119            assert_eq!(
20120                registry.get_module("aft").unwrap().unwrap().connection_id,
20121                ConnectionId::new(1),
20122                "the candidate must not take the active slot"
20123            );
20124            let replayed = handler
20125                .handle_control(
20126                    ConnectionId::new(5),
20127                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20128                )
20129                .unwrap();
20130            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20131
20132            // The case only this gate covers: the incumbent has died mid-swap,
20133            // so its duplicate refusal is gone too, and without the gate a
20134            // key-holder would take the id's ACTIVE slot.
20135            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20136            let squatter = handler
20137                .handle_control(
20138                    ConnectionId::new(6),
20139                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20140                )
20141                .unwrap();
20142            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20143            assert!(
20144                registry.get_module("aft").unwrap().is_none(),
20145                "a squatter took the active slot of an id being swapped"
20146            );
20147        }
20148
20149        /// Design mutation arm (iii). A reserved module's candidate presents a
20150        /// nonce the reserved gate has never seen (that gate holds the
20151        /// incumbent's), so the swap gate must run first or the candidate is
20152        /// refused `reserved_module` and a reserved module can never be swapped.
20153        #[test]
20154        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20155            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20156
20157            let replies = handler
20158                .handle_control(
20159                    ConnectionId::new(2),
20160                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20161                )
20162                .unwrap();
20163
20164            assert_eq!(
20165                replies[0].header.ty,
20166                FrameType::HelloAck,
20167                "reserved candidate refused: {:?}",
20168                serde_json::from_slice::<Value>(&replies[0].body).ok()
20169            );
20170            assert_eq!(
20171                registry
20172                    .get_candidate("vault")
20173                    .unwrap()
20174                    .unwrap()
20175                    .connection_id,
20176                ConnectionId::new(2)
20177            );
20178        }
20179
20180        /// With no swap open the gate is inert: the incumbent's reserved gate
20181        /// and duplicate refusal behave exactly as before.
20182        #[test]
20183        fn without_an_open_swap_the_ordinary_gates_decide() {
20184            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20185            supervisor.close_swap("vault");
20186
20187            let candidate = handler
20188                .handle_control(
20189                    ConnectionId::new(2),
20190                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20191                )
20192                .unwrap();
20193            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20194            let duplicate = handler
20195                .handle_control(
20196                    ConnectionId::new(3),
20197                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20198                )
20199                .unwrap();
20200            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20201            assert!(registry.get_candidate("vault").unwrap().is_none());
20202        }
20203    }
20204
20205    /// `scope.sync` and `scope.describe` through the real control handler: who
20206    /// may sync is decided by the registration and launch nonce of the module
20207    /// connection, never by the request body.
20208    mod scopes {
20209        mod close_reasons {
20210            include!("route_close_reason_tests.rs");
20211        }
20212        mod idle_tests {
20213            use super::*;
20214            include!("scope_idle_tests.rs");
20215        }
20216        mod route_open_timings {
20217            use super::*;
20218            include!("route_open_timing_tests.rs");
20219        }
20220        mod route_open_refusal_log {
20221            use super::*;
20222            include!("route_open_refusal_log_tests.rs");
20223        }
20224        mod activity {
20225            include!("activity_scope_tests.rs");
20226        }
20227        mod delta {
20228            include!("scope_handler_delta_tests.rs");
20229        }
20230        mod watch {
20231            include!("scope_watch_tests.rs");
20232        }
20233        mod call_modes {
20234            include!("scope_call_mode_tests.rs");
20235        }
20236        mod federated {
20237            include!("scope_federated_tests.rs");
20238        }
20239        mod authorize {
20240            include!("route_authorize_tests.rs");
20241        }
20242        #[tokio::test]
20243        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20244            let rig = rig().await;
20245            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20246                "s".into(),
20247                1,
20248                "tool".into(),
20249            ))
20250            .unwrap();
20251            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20252            let (direct, _rx) = wide_ctx(999);
20253            for (ctx, expected) in [
20254                (&rig.owner, FrameType::Response),
20255                (&direct, FrameType::Error),
20256            ] {
20257                let frame =
20258                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20259                        .unwrap();
20260                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20261                assert_eq!(replies[0].header.ty, expected);
20262                if expected == FrameType::Response {
20263                    let reply: subc_control::ScopeServedByReply =
20264                        serde_json::from_slice(&replies[0].body).unwrap();
20265                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20266                } else {
20267                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20268                }
20269            }
20270            let reply = call(
20271                &rig.handler,
20272                &rig.owner,
20273                &ModuleControlRequestFromModule::ScopeDescribe {
20274                    owner: Principal::Reserved {
20275                        module_id: OWNER.into(),
20276                    },
20277                    scope_ref: "s".into(),
20278                },
20279            )
20280            .await;
20281            assert!(matches!(
20282                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20283                ModuleControlResponseToModule::ScopeDescribe { .. }
20284            ));
20285        }
20286
20287        use subc_protocol::scope::{
20288            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20289            ScopeStatus,
20290        };
20291
20292        use super::*;
20293
20294        const OWNER: &str = "prefrontal-core";
20295
20296        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20297            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20298        }
20299
20300        async fn call(
20301            handler: &ControlHandler,
20302            ctx: &RouteCtx,
20303            request: &ModuleControlRequestFromModule,
20304        ) -> Frame {
20305            let body = serde_json::to_vec(request).unwrap();
20306            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20307            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20308            assert_eq!(replies.len(), 1, "{replies:?}");
20309            replies.pop().unwrap()
20310        }
20311
20312        async fn sync(
20313            handler: &ControlHandler,
20314            ctx: &RouteCtx,
20315            generation: u64,
20316            scopes: Vec<ScopeRecord>,
20317        ) -> Result<ModuleControlResponseToModule, String> {
20318            let reply = call(
20319                handler,
20320                ctx,
20321                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20322            )
20323            .await;
20324            match reply.header.ty {
20325                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20326                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20327            }
20328        }
20329
20330        async fn describe(
20331            handler: &ControlHandler,
20332            ctx: &RouteCtx,
20333            owner: &str,
20334            scope_ref: &str,
20335        ) -> ModuleControlResponseToModule {
20336            let reply = call(
20337                handler,
20338                ctx,
20339                &ModuleControlRequestFromModule::ScopeDescribe {
20340                    owner: Principal::Reserved {
20341                        module_id: owner.to_string(),
20342                    },
20343                    scope_ref: scope_ref.to_string(),
20344                },
20345            )
20346            .await;
20347            assert_eq!(
20348                reply.header.ty,
20349                FrameType::Response,
20350                "{:?}",
20351                parse_error(&reply)
20352            );
20353            serde_json::from_slice(&reply.body).unwrap()
20354        }
20355
20356        #[tokio::test]
20357        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20358            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20359            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20360            let mut rig = rig().await;
20361            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20362                .await;
20363            let _bound = rig
20364                .bound(
20365                    Some(AFT),
20366                    PLEXUS,
20367                    Some(
20368                        rig.selector("s", Some(1))
20369                            .with_bind_proof(Some(PROOF.into())),
20370                    ),
20371                )
20372                .await;
20373            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20374            let output = serde_json::to_string(&reply).unwrap();
20375            assert!(output.contains("\"status\":\"live\""));
20376            assert!(!output.contains(PROOF));
20377            assert!(!output.contains(HASH));
20378        }
20379
20380        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20381        async fn module(
20382            handler: &ControlHandler,
20383            connection: u64,
20384            module_id: &str,
20385            nonce: Option<&str>,
20386        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20387            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20388            hello_via_sink(
20389                handler,
20390                &ctx,
20391                &mut rx,
20392                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20393            )
20394            .await;
20395            (ctx, rx)
20396        }
20397
20398        /// `direct` and every other client connection has no registration, so
20399        /// it can neither sync nor own a scope.
20400        #[tokio::test]
20401        async fn a_client_connection_cannot_sync_or_describe() {
20402            let handler = ControlHandler::new(Arc::new(Registry::default()));
20403            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20404            for request in [
20405                ModuleControlRequestFromModule::ScopeSync {
20406                    generation: 1,
20407                    scopes: vec![head("s", 1)],
20408                },
20409                ModuleControlRequestFromModule::ScopeDescribe {
20410                    owner: Principal::Direct,
20411                    scope_ref: "s".to_string(),
20412                },
20413            ] {
20414                let reply = call(&handler, &ctx, &request).await;
20415                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20416            }
20417            assert!(
20418                !handler
20419                    .scopes
20420                    .read()
20421                    .unwrap()
20422                    .describe(
20423                        &Principal::Reserved {
20424                            module_id: OWNER.to_string()
20425                        },
20426                        "s"
20427                    )
20428                    .owner_synced
20429            );
20430        }
20431
20432        /// A module the supervisor did not spawn registers without a launch
20433        /// nonce, so it is never an owner's current launch.
20434        #[tokio::test]
20435        async fn a_module_without_a_supervised_launch_cannot_sync() {
20436            let handler = ControlHandler::new(Arc::new(Registry::default()));
20437            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20438            assert_eq!(
20439                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20440                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20441            );
20442        }
20443
20444        #[tokio::test]
20445        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20446            let supervisor = SupervisorHandle::new();
20447            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20448            let handler = ControlHandler::new(Arc::new(Registry::default()))
20449                .with_supervisor(supervisor.clone());
20450            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20451            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20452                .await
20453                .expect("the current launch syncs");
20454
20455            // A swap candidate registers with the swap token and is refused
20456            // while the incumbent keeps syncing.
20457            supervisor.open_swap(OWNER, "n2".to_string());
20458            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20459            assert_eq!(
20460                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20461                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20462            );
20463            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20464                .await
20465                .expect("the serving owner syncs during the swap");
20466
20467            // The swap fails and is rolled back. The candidate never held sync
20468            // authority, and still cannot sync.
20469            supervisor.close_swap(OWNER);
20470            assert_eq!(
20471                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20472                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20473            );
20474            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20475                .await
20476                .expect("the serving owner syncs after the rollback");
20477            handler.cleanup_connection(candidate.connection_id).unwrap();
20478
20479            // A swap that cuts over. Promotion records the candidate's nonce as
20480            // the module's spawn nonce, which is what `set_spawn_nonce` does
20481            // here; the promoted connection then takes authority at any
20482            // generation and the superseded incumbent is refused.
20483            supervisor.open_swap(OWNER, "n3".to_string());
20484            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20485            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20486            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20487                .await
20488                .expect("the promoted launch takes authority");
20489            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20490                panic!("unexpected reply {reply:?}");
20491            };
20492            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20493            assert_eq!(
20494                sync(&handler, &incumbent, 4, Vec::new()).await,
20495                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20496            );
20497        }
20498
20499        /// Authority dies with its connection: the cleanup path releases it,
20500        /// so the owner's next connection takes it at any generation.
20501        #[tokio::test]
20502        async fn closing_the_authority_connection_frees_sync_authority() {
20503            let supervisor = SupervisorHandle::new();
20504            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20505            let handler = ControlHandler::new(Arc::new(Registry::default()))
20506                .with_supervisor(supervisor.clone());
20507            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20508            sync(&handler, &first, 10, vec![head("s", 1)])
20509                .await
20510                .unwrap();
20511            handler.cleanup_connection(first.connection_id).unwrap();
20512
20513            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20514            sync(&handler, &second, 1, vec![head("s", 1)])
20515                .await
20516                .expect("the next connection takes the released authority");
20517        }
20518
20519        #[tokio::test]
20520        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20521            let supervisor = SupervisorHandle::new();
20522            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20523            let handler =
20524                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20525            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20526            sync(&handler, &first, 10, vec![head("s", 1)])
20527                .await
20528                .unwrap();
20529            handler
20530                .handle_control_frame(
20531                    &first,
20532                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20533                )
20534                .await
20535                .unwrap();
20536            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20537            sync(&handler, &second, 1, vec![head("s", 1)])
20538                .await
20539                .expect("GOODBYE releases authority even if the old socket remains open");
20540        }
20541
20542        #[tokio::test]
20543        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20544            let registry = Arc::new(Registry::default());
20545            let supervisor_handle = SupervisorHandle::new();
20546            let supervisor =
20547                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20548                    .with_handle(supervisor_handle.clone())
20549                    .with_daemon_incarnation("incarnation-7".to_string());
20550            // Configured with enabled: false, so the supervisor lists the
20551            // module without spawning a process for it.
20552            supervisor
20553                .supervise_configured(
20554                    ModuleSpec {
20555                        script: None,
20556                        carry_containment: false,
20557                        module_id: OWNER.to_string(),
20558                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20559                        args: Vec::new(),
20560                        env: Vec::new(),
20561                        reserved: false,
20562                        reserved_prefixes: Vec::new(),
20563                        protocol: ModuleProtocol::Subc,
20564                        overlap: Default::default(),
20565                    },
20566                    false,
20567                )
20568                .unwrap();
20569            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20570            let handler =
20571                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20572            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20573
20574            // Configured but not yet synced: a reader waits for the owner.
20575            let ModuleControlResponseToModule::ScopeDescribe {
20576                status,
20577                daemon_incarnation,
20578                owner_synced,
20579                owner_configured,
20580                scope,
20581                ..
20582            } = describe(&handler, &reader, OWNER, "s").await
20583            else {
20584                panic!("not a describe reply");
20585            };
20586            assert_eq!(status, ScopeStatus::NotLive);
20587            assert_eq!(daemon_incarnation, "incarnation-7");
20588            assert!(!owner_synced);
20589            assert!(owner_configured);
20590            assert!(scope.is_none());
20591
20592            // Not a supervised module: the owner will never sync, and a reader
20593            // refuses rather than waits.
20594            let ModuleControlResponseToModule::ScopeDescribe {
20595                status,
20596                owner_configured,
20597                ..
20598            } = describe(&handler, &reader, "ghost", "s").await
20599            else {
20600                panic!("not a describe reply");
20601            };
20602            assert_eq!(status, ScopeStatus::NotLive);
20603            assert!(!owner_configured);
20604
20605            // Live, with the stamp fields and the computed owner_authorized.
20606            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20607            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20608            let ModuleControlResponseToModule::ScopeDescribe {
20609                status,
20610                scope_epoch,
20611                owner_synced,
20612                scope,
20613                ..
20614            } = describe(&handler, &reader, OWNER, "s").await
20615            else {
20616                panic!("not a describe reply");
20617            };
20618            assert_eq!(status, ScopeStatus::Live);
20619            assert_eq!(scope_epoch, Some(4));
20620            assert!(owner_synced);
20621            let stamp = scope.expect("a live scope carries its stamp");
20622            assert!(
20623                stamp.owner_authorized,
20624                "prefrontal-core is the default authority"
20625            );
20626            assert_eq!(stamp.kind, ScopeKind::Head);
20627        }
20628
20629        #[tokio::test]
20630        async fn scope_authority_owners_decides_owner_authorized() {
20631            let supervisor = SupervisorHandle::new();
20632            supervisor.set_spawn_nonce("broca", "b1".to_string());
20633            let handler = ControlHandler::new(Arc::new(Registry::default()))
20634                .with_supervisor(supervisor)
20635                .with_scope_authority_owners(vec!["broca".to_string()]);
20636            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20637            let mut gated = head("s", 1);
20638            gated.attributes.agent_id = Some("agent".to_string());
20639            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20640            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20641                describe(&handler, &broca, "broca", "s").await
20642            else {
20643                panic!("not a describe reply");
20644            };
20645            assert!(scope.unwrap().owner_authorized);
20646        }
20647
20648        /// With route admission, the stamp, the commit re-check and drains in
20649        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20650        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20651        #[tokio::test]
20652        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20653            let handler = ControlHandler::new(Arc::new(Registry::default()));
20654            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20655            let ack = hello_via_sink(
20656                &handler,
20657                &ctx,
20658                &mut rx,
20659                hello_frame("m", PROTOCOL_VERSION, 1),
20660            )
20661            .await;
20662            let ack = parse_ack(&ack);
20663            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20664                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20665            }
20666            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20667
20668            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20669            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20670            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20671            let reply = handler
20672                .handle_control_frame(&client, frame)
20673                .await
20674                .unwrap()
20675                .pop()
20676                .unwrap();
20677            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20678                serde_json::from_slice(&reply.body).unwrap()
20679            else {
20680                panic!("not a server.describe reply");
20681            };
20682            assert!(
20683                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20684                "{capabilities:?}"
20685            );
20686        }
20687
20688        // ---- route admission, stamps, commit re-check and drains ----------
20689
20690        const PLEXUS: &str = "plexus";
20691        const OTHER: &str = "other";
20692        const AFT: &str = "aft";
20693        const BROCA: &str = "broca";
20694        const MAGIC: &str = "magic-context";
20695
20696        fn nonce(module_id: &str) -> String {
20697            format!("nonce-{module_id}")
20698        }
20699
20700        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20701            let (tx, rx) = mpsc::channel(64);
20702            (
20703                RouteCtx {
20704                    connection_id: ConnectionId::new(connection),
20705                    egress: FrameSink::new(tx),
20706                },
20707                rx,
20708            )
20709        }
20710
20711        /// A daemon with a configured owner (prefrontal-core) registered on its
20712        /// own module connection, two routable targets (plexus, other), and
20713        /// launch nonces minted for the modules that open routes as carriers.
20714        struct Rig {
20715            handler: ControlHandler,
20716            forwarding: Arc<ForwardingTable>,
20717            owner: RouteCtx,
20718            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20719            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20720            generation: u64,
20721            next_connection: u64,
20722            _supervisor: Supervisor,
20723        }
20724
20725        async fn rig() -> Rig {
20726            rig_with_flow_support(true).await
20727        }
20728
20729        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20730            rig_with_scope_capabilities(flow_support, false).await
20731        }
20732
20733        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20734            let mut provides = Vec::new();
20735            if flow_support {
20736                provides.push("flow-scopes/v1");
20737            }
20738            if run_support {
20739                provides.push("agent-run-scopes/v1");
20740            }
20741            rig_with_target_capabilities(&provides).await
20742        }
20743
20744        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20745            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20746            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20747            // Decoder versions alone cannot admit scoped calls: only a capability
20748            // declaration promises the required run or flow behaviour.
20749            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20750            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20751            Frame::build(
20752                FrameType::Hello,
20753                control_flags(),
20754                0,
20755                0,
20756                connection,
20757                serde_json::to_vec(&body).unwrap(),
20758            )
20759            .unwrap()
20760        }
20761
20762        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20763            let registry = Arc::new(Registry::default());
20764            let forwarding = Arc::new(ForwardingTable::default());
20765            let supervisor_handle = SupervisorHandle::new();
20766            let supervisor =
20767                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20768                    .with_handle(supervisor_handle.clone());
20769            supervisor
20770                .supervise_configured(
20771                    ModuleSpec {
20772                        script: None,
20773                        carry_containment: false,
20774                        module_id: OWNER.to_string(),
20775                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20776                        args: Vec::new(),
20777                        env: Vec::new(),
20778                        reserved: false,
20779                        reserved_prefixes: Vec::new(),
20780                        protocol: ModuleProtocol::Subc,
20781                        overlap: Default::default(),
20782                    },
20783                    false,
20784                )
20785                .unwrap();
20786            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20787                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20788            }
20789            let handler =
20790                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20791                    .with_supervisor(supervisor_handle);
20792            let (owner, mut owner_rx) = wide_ctx(1);
20793            hello_via_sink(
20794                &handler,
20795                &owner,
20796                &mut owner_rx,
20797                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20798            )
20799            .await;
20800            let mut modules = BTreeMap::new();
20801            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20802                let (ctx, mut rx) = wide_ctx(connection);
20803                let hello = hello_with_capabilities(module_id, connection, provides);
20804                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20805                modules.insert(module_id.to_string(), (ctx, rx));
20806            }
20807            Rig {
20808                handler,
20809                forwarding,
20810                owner,
20811                _owner_rx: owner_rx,
20812                modules,
20813                generation: 0,
20814                next_connection: 100,
20815                _supervisor: supervisor,
20816            }
20817        }
20818
20819        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20820            ScopeCarrier::new(Principal::Reserved {
20821                module_id: module_id.to_string(),
20822            })
20823            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20824        }
20825
20826        /// The scope most tests open under: aft carries to any module, broca
20827        /// only to plexus and other, and the owner delegates as agent-1.
20828        fn session(scope_epoch: u64) -> ScopeRecord {
20829            let mut record = head("s", scope_epoch);
20830            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20831            record.attributes.agent_id = Some("agent-1".to_string());
20832            record.attributes.delegates = true;
20833            record
20834        }
20835
20836        impl Rig {
20837            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20838                self.generation += 1;
20839                sync(&self.handler, &self.owner, self.generation, scopes)
20840                    .await
20841                    .expect("the owner's sync is accepted");
20842            }
20843
20844            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20845                ScopeSelector::new(
20846                    Principal::Reserved {
20847                        module_id: OWNER.to_string(),
20848                    },
20849                    scope_ref.to_string(),
20850                    scope_epoch,
20851                )
20852            }
20853
20854            fn open_frame(
20855                &mut self,
20856                opener: Option<&str>,
20857                target: &str,
20858                scope: Option<ScopeSelector>,
20859            ) -> (
20860                RouteCtx,
20861                mpsc::Receiver<crate::router::OutboundFrame>,
20862                Frame,
20863            ) {
20864                self.next_connection += 1;
20865                let (ctx, rx) = wide_ctx(self.next_connection);
20866                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20867                    busy_refusals: None,
20868                    target: RouteTarget::ToolProvider {
20869                        module_id: target.to_string(),
20870                    },
20871                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20872                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20873                        module_id: module_id.to_string(),
20874                        launch_nonce: nonce(module_id),
20875                    }),
20876                    consumer_capabilities: None,
20877                    role_versions: None,
20878                    admission_facts: None,
20879                    scope,
20880                })
20881                .unwrap();
20882                let frame = Frame::build(
20883                    FrameType::Request,
20884                    control_flags(),
20885                    0,
20886                    0,
20887                    self.next_connection,
20888                    body,
20889                )
20890                .unwrap();
20891                (ctx, rx, frame)
20892            }
20893
20894            /// Open and expect a refusal before anything is relayed.
20895            async fn refused(
20896                &mut self,
20897                opener: Option<&str>,
20898                target: &str,
20899                scope: Option<ScopeSelector>,
20900            ) -> String {
20901                self.refusal_body(opener, target, scope).await["code"]
20902                    .as_str()
20903                    .unwrap()
20904                    .to_string()
20905            }
20906
20907            async fn refusal_body(
20908                &mut self,
20909                opener: Option<&str>,
20910                target: &str,
20911                scope: Option<ScopeSelector>,
20912            ) -> Value {
20913                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20914                let replies = tokio::time::timeout(
20915                    Duration::from_secs(2),
20916                    self.handler.handle_control_frame(&ctx, frame),
20917                )
20918                .await
20919                .expect("the open must be refused before waiting for a bind ack")
20920                .unwrap();
20921                assert_eq!(replies.len(), 1, "{replies:?}");
20922                assert_eq!(replies[0].header.ty, FrameType::Error);
20923                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20924                assert!(
20925                    module_rx.try_recv().is_err(),
20926                    "a refused open relays nothing"
20927                );
20928                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20929                parse_error(&replies[0])
20930            }
20931
20932            /// Start an open and return its task and the bind the target got.
20933            async fn relayed(
20934                &mut self,
20935                opener: Option<&str>,
20936                target: &str,
20937                scope: Option<ScopeSelector>,
20938            ) -> Relayed {
20939                self.relayed_with_legacy_root(opener, target, scope, None)
20940                    .await
20941            }
20942
20943            async fn relayed_with_legacy_root(
20944                &mut self,
20945                opener: Option<&str>,
20946                target: &str,
20947                scope: Option<ScopeSelector>,
20948                legacy_root: Option<&std::path::Path>,
20949            ) -> Relayed {
20950                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20951                if let Some(root) = legacy_root {
20952                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20953                    body["identity"]["project_root"] = serde_json::json!(root);
20954                    frame.body = serde_json::to_vec(&body).unwrap();
20955                }
20956                let handler = self.handler.clone();
20957                let task_ctx = ctx.clone();
20958                let task = tokio::spawn(async move {
20959                    handler
20960                        .handle_control_frame(&task_ctx, frame)
20961                        .await
20962                        .unwrap()
20963                });
20964                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20965                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20966                    .await
20967                    .expect("the target receives the relayed route.bind")
20968                    .unwrap()
20969                    .frame;
20970                Relayed {
20971                    target: target.to_string(),
20972                    client: ctx,
20973                    client_rx: rx,
20974                    task,
20975                    bind,
20976                }
20977            }
20978
20979            async fn ack(&self, relayed: &Relayed) {
20980                let (module, _) = &self.modules[&relayed.target];
20981                self.handler
20982                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20983                    .await
20984                    .unwrap();
20985            }
20986
20987            /// Open, ack and return the bound route.
20988            async fn bound(
20989                &mut self,
20990                opener: Option<&str>,
20991                target: &str,
20992                scope: Option<ScopeSelector>,
20993            ) -> Bound {
20994                let relayed = self.relayed(opener, target, scope).await;
20995                self.commit_relayed(relayed).await
20996            }
20997
20998            async fn bound_with_legacy_root(
20999                &mut self,
21000                opener: Option<&str>,
21001                target: &str,
21002                scope: Option<ScopeSelector>,
21003                root: &std::path::Path,
21004            ) -> Bound {
21005                let relayed = self
21006                    .relayed_with_legacy_root(opener, target, scope, Some(root))
21007                    .await;
21008                self.commit_relayed(relayed).await
21009            }
21010
21011            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
21012                self.ack(&relayed).await;
21013                let Relayed {
21014                    target,
21015                    client,
21016                    mut client_rx,
21017                    task,
21018                    bind,
21019                } = relayed;
21020                assert!(
21021                    task.await.unwrap().is_empty(),
21022                    "the open is answered by commit"
21023                );
21024                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
21025                Bound {
21026                    target,
21027                    client,
21028                    client_rx,
21029                    channel,
21030                    epoch,
21031                    bind,
21032                }
21033            }
21034
21035            fn live(&self, route: &Bound) -> bool {
21036                matches!(
21037                    self.forwarding
21038                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21039                        .unwrap(),
21040                    DataRoute::Client(DataRouteState::Bound(_))
21041                )
21042            }
21043        }
21044
21045        struct Relayed {
21046            target: String,
21047            client: RouteCtx,
21048            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21049            task: tokio::task::JoinHandle<Vec<Frame>>,
21050            bind: Frame,
21051        }
21052
21053        struct Bound {
21054            target: String,
21055            client: RouteCtx,
21056            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21057            channel: u16,
21058            epoch: u32,
21059            bind: Frame,
21060        }
21061
21062        impl Bound {
21063            /// The reason of the `route.closed` this client was sent, after
21064            /// checking it also got a GOODBYE on exactly this route.
21065            fn closed_reason(&mut self) -> RouteCloseReason {
21066                let mut reason = None;
21067                let mut goodbye = false;
21068                while let Ok(outbound) = self.client_rx.try_recv() {
21069                    let frame = outbound.frame;
21070                    match frame.header.ty {
21071                        FrameType::Goodbye => {
21072                            assert_eq!(
21073                                (frame.header.channel, frame.header.epoch),
21074                                (self.channel, self.epoch)
21075                            );
21076                            goodbye = true;
21077                        }
21078                        FrameType::Push => {
21079                            let ClientControlPush::RouteClosed {
21080                                reason: r,
21081                                module_id,
21082                                ..
21083                            } = serde_json::from_slice(&frame.body).unwrap()
21084                            else {
21085                                panic!("unexpected push");
21086                            };
21087                            assert_eq!(module_id, self.target);
21088                            reason = Some(r);
21089                        }
21090                        other => panic!("unexpected frame {other:?}"),
21091                    }
21092                }
21093                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21094                reason.expect("the client is told why the route closed")
21095            }
21096
21097            fn untouched(&mut self) -> bool {
21098                self.client_rx.try_recv().is_err()
21099            }
21100
21101            fn stamp(&self) -> Option<ScopeStamp> {
21102                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21103                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21104                    other => panic!("expected a route.bind, got {other:?}"),
21105                }
21106            }
21107        }
21108
21109        #[tokio::test]
21110        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21111        ) {
21112            let mut rig = rig().await;
21113            let mut record = session(1);
21114            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21115            record.child_owners = vec![Principal::Reserved {
21116                module_id: MAGIC.to_string(),
21117            }];
21118            rig.sync(vec![record]).await;
21119            let scope = || Some(rig_selector("s", Some(1)));
21120
21121            // Admitted: the owner, a bare carrier to any module, a targeted
21122            // carrier to its listed module.
21123            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21124            rig.bound(Some(AFT), OTHER, scope()).await;
21125            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21126
21127            // Refused scope_not_carrier: a targeted carrier to an unlisted
21128            // module, a module that is not listed at all (a child owner is not
21129            // a carrier), and a direct key-holder.
21130            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21131                assert_eq!(
21132                    rig.refused(opener, target, scope()).await,
21133                    error_codes::SCOPE_NOT_CARRIER,
21134                    "{opener:?} -> {target}"
21135                );
21136            }
21137        }
21138
21139        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21140            ScopeSelector::new(
21141                Principal::Reserved {
21142                    module_id: OWNER.to_string(),
21143                },
21144                scope_ref.to_string(),
21145                scope_epoch,
21146            )
21147        }
21148
21149        #[tokio::test]
21150        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21151            let mut rig = rig().await;
21152            rig.sync(vec![session(1)]).await;
21153            for opener in [OWNER, AFT] {
21154                assert_eq!(
21155                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21156                        .await,
21157                    error_codes::SCOPE_EPOCH_REQUIRED,
21158                    "{opener}"
21159                );
21160            }
21161        }
21162
21163        #[tokio::test]
21164        async fn admission_separates_not_synced_not_live_and_ended() {
21165            let mut rig = rig().await;
21166            // Before the configured owner's first sync: retryable.
21167            let code = rig
21168                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21169                .await;
21170            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21171            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21172
21173            // An owner that is not configured will never sync: terminal.
21174            let ghost = ScopeSelector::new(
21175                Principal::Reserved {
21176                    module_id: "ghost".to_string(),
21177                },
21178                "s".to_string(),
21179                Some(1),
21180            );
21181            assert_eq!(
21182                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21183                error_codes::SCOPE_NOT_LIVE
21184            );
21185
21186            rig.sync(vec![session(2)]).await;
21187            assert_eq!(
21188                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21189                    .await,
21190                error_codes::SCOPE_NOT_LIVE
21191            );
21192            for epoch in [1, 3] {
21193                assert_eq!(
21194                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21195                        .await,
21196                    error_codes::SCOPE_ENDED,
21197                    "epoch {epoch}"
21198                );
21199            }
21200            // Control: the live epoch is admitted.
21201            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21202                .await;
21203        }
21204
21205        #[tokio::test]
21206        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21207            let mut rig = rig().await;
21208            rig.sync(vec![session(1)]).await;
21209            let route = rig
21210                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21211                .await;
21212            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21213            assert_eq!(stamp.scope_ref, "s");
21214            assert_eq!(stamp.scope_epoch, 1);
21215            assert_eq!(stamp.kind, ScopeKind::Head);
21216            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21217            assert!(stamp.attributes.delegates);
21218            assert!(stamp.owner_authorized);
21219            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21220            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21221
21222            // broca owns a scope of its own on its own module connection; it is
21223            // not in scope_authority_owners, so its stamp is not authorized.
21224            let (broca, mut broca_rx) = wide_ctx(50);
21225            hello_via_sink(
21226                &rig.handler,
21227                &broca,
21228                &mut broca_rx,
21229                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21230            )
21231            .await;
21232            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21233                .await
21234                .unwrap();
21235            let own = ScopeSelector::new(
21236                Principal::Reserved {
21237                    module_id: BROCA.to_string(),
21238                },
21239                "b".to_string(),
21240                Some(1),
21241            );
21242            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21243            assert!(!route.stamp().unwrap().owner_authorized);
21244        }
21245
21246        #[tokio::test]
21247        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21248            let mut rig = rig().await;
21249            let mut record = head("s", 1);
21250            record.carriers = vec![carrier(AFT, None)];
21251            let flow_id = "Flow:run-7/step_2!~";
21252            record.attributes.flow_id = Some(flow_id.to_string());
21253            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21254                .await
21255                .unwrap();
21256            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21257                panic!("not a sync reply");
21258            };
21259            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21260            let route = rig
21261                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21262                .await;
21263            assert!(rig.live(&route), "the stamped bind committed");
21264            let stamp = route.stamp().expect("a flow scope carries a stamp");
21265            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21266            assert_eq!(stamp.attributes.agent_id, None);
21267            assert!(!stamp.attributes.delegates);
21268            assert!(stamp.owner_authorized);
21269            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21270            assert_eq!(unscoped.stamp(), None);
21271        }
21272
21273        #[tokio::test]
21274        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21275            let mut rig = rig_with_flow_support(false).await;
21276            let mut record = session(1);
21277            record.attributes.flow_id = Some("flow:7".to_string());
21278            rig.sync(vec![record]).await;
21279            for opener in [OWNER, AFT] {
21280                let body = rig
21281                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21282                    .await;
21283                assert_eq!(body["code"], "target_flow_unsupported");
21284                let message = body["message"].as_str().unwrap();
21285                for required in [PLEXUS, "flow-scopes/v1"] {
21286                    assert!(message.contains(required), "{message}");
21287                }
21288            }
21289        }
21290
21291        #[tokio::test]
21292        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21293            let mut rig = rig_with_flow_support(true).await;
21294            let mut record = session(1);
21295            record.attributes.flow_id = Some("flow:7".to_string());
21296            rig.sync(vec![record]).await;
21297            for opener in [OWNER, AFT] {
21298                let route = rig
21299                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21300                    .await;
21301                assert!(rig.live(&route));
21302                assert_eq!(
21303                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21304                    Some("flow:7")
21305                );
21306            }
21307        }
21308
21309        #[tokio::test]
21310        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21311            use std::future::Future;
21312
21313            let mut rig = rig_with_flow_support(true).await;
21314            let mut record = session(1);
21315            record.attributes.flow_id = Some("flow:7".to_string());
21316            rig.sync(vec![record]).await;
21317            let (client, mut client_rx, frame) =
21318                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21319            // Hold the route-open response permit so admission sees the first
21320            // target but relay reservation cannot capture an endpoint yet.
21321            for _ in 0..64 {
21322                client.egress.try_send(route_bind_ack(1)).unwrap();
21323            }
21324            let handler = rig.handler.clone();
21325            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21326            std::future::poll_fn(|cx| {
21327                assert!(open.as_mut().poll(cx).is_pending());
21328                std::task::Poll::Ready(())
21329            })
21330            .await;
21331            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21332
21333            let old_connection = rig.modules[PLEXUS].0.connection_id;
21334            rig.handler.cleanup_connection(old_connection).unwrap();
21335            let (replacement, mut replacement_rx) = wide_ctx(200);
21336            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21337            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21338            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21339            let hello = Frame::build(
21340                FrameType::Hello,
21341                control_flags(),
21342                0,
21343                0,
21344                200,
21345                serde_json::to_vec(&body).unwrap(),
21346            )
21347            .unwrap();
21348            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21349
21350            client_rx.try_recv().unwrap();
21351            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21352                .await
21353                .expect("the replacement is refused without waiting for a bind ack")
21354                .unwrap();
21355            assert_eq!(replies.len(), 1);
21356            let body = parse_error(&replies[0]);
21357            assert_eq!(body["code"], "target_flow_unsupported");
21358            for required in [PLEXUS, "flow-scopes/v1"] {
21359                assert!(body["message"].as_str().unwrap().contains(required));
21360            }
21361            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21362            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21363            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21364            assert!(rig
21365                .handler
21366                .registry
21367                .get_module_by_connection(replacement.connection_id)
21368                .unwrap()
21369                .is_some());
21370        }
21371
21372        #[tokio::test]
21373        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21374            use std::future::Future;
21375            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21376            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21377            const NEXT_HASH: &str =
21378                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21379            let mut rig = rig().await;
21380            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21381            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21382            rig.sync(vec![record.clone()]).await;
21383            let (client, mut rx, frame) = rig.open_frame(
21384                None,
21385                PLEXUS,
21386                Some(
21387                    rig.selector("s", Some(1))
21388                        .with_bind_proof(Some(PROOF.into())),
21389                ),
21390            );
21391            // Hold egress reservation while the scope owner changes its bind-proof
21392            // hash, so a proof valid at admission must be checked again at relay.
21393            for _ in 0..64 {
21394                client.egress.try_send(route_bind_ack(1)).unwrap();
21395            }
21396            let handler = rig.handler.clone();
21397            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21398            std::future::poll_fn(|cx| {
21399                assert!(open.as_mut().poll(cx).is_pending());
21400                std::task::Poll::Ready(())
21401            })
21402            .await;
21403            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21404            rig.sync(vec![record]).await;
21405            rx.try_recv().unwrap();
21406            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21407                .await
21408                .unwrap()
21409                .unwrap();
21410            assert_eq!(
21411                parse_error(&replies[0])["code"],
21412                error_codes::SCOPE_BIND_PROOF_MISMATCH
21413            );
21414            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21415            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21416            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21417        }
21418
21419        #[tokio::test]
21420        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21421            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21422            let mut rig = rig().await;
21423            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21424                .await;
21425            for opener in [OWNER, AFT] {
21426                for proof in [None, Some("malformed+proof=")] {
21427                    let route = rig
21428                        .bound(
21429                            Some(opener),
21430                            PLEXUS,
21431                            Some(
21432                                rig.selector("s", Some(1))
21433                                    .with_bind_proof(proof.map(str::to_string)),
21434                            ),
21435                        )
21436                        .await;
21437                    assert!(rig.live(&route));
21438                }
21439            }
21440        }
21441
21442        #[tokio::test]
21443        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21444            use std::future::Future;
21445            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21446            const NEXT_HASH: &str =
21447                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21448            let mut rig = rig().await;
21449            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21450                .await;
21451            let (client, mut rx, frame) =
21452                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21453            for _ in 0..64 {
21454                client.egress.try_send(route_bind_ack(1)).unwrap();
21455            }
21456            let handler = rig.handler.clone();
21457            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21458            std::future::poll_fn(|cx| {
21459                assert!(open.as_mut().poll(cx).is_pending());
21460                std::task::Poll::Ready(())
21461            })
21462            .await;
21463            rig.sync(vec![
21464                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21465            ])
21466            .await;
21467            rx.try_recv().unwrap();
21468            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21469            let bind = std::future::poll_fn(|cx| {
21470                assert!(open.as_mut().poll(cx).is_pending());
21471                module_rx.poll_recv(cx)
21472            })
21473            .await
21474            .unwrap()
21475            .frame;
21476            handler
21477                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21478                .await
21479                .unwrap();
21480            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21481                .await
21482                .unwrap()
21483                .unwrap();
21484            assert_eq!(replies.len(), 1);
21485            // Proof rechecking allowed the relay. Independent tag settlement
21486            // still asks the opener to retry after any same-epoch content change.
21487            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21488            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21489            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21490            let route = rig
21491                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21492                .await;
21493            assert!(rig.live(&route));
21494        }
21495
21496        #[tokio::test]
21497        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21498        {
21499            let mut rig = rig_with_flow_support(false).await;
21500            rig.sync(vec![session(1)]).await;
21501            let route = rig
21502                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21503                .await;
21504            assert!(rig.live(&route));
21505            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21506            let mut record = session(1);
21507            record.attributes.flow_id = Some("flow:7".to_string());
21508            rig.sync(vec![record]).await;
21509            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21510            assert!(rig.live(&unscoped));
21511            assert_eq!(unscoped.stamp(), None);
21512        }
21513
21514        #[tokio::test]
21515        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21516            let mut rig = rig().await;
21517            let mut record = session(1);
21518            record.attributes.flow_id = Some("flow:7".to_string());
21519            rig.sync(vec![record.clone()]).await;
21520            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21521            let mut owner_route = rig
21522                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21523                .await;
21524            let mut carrier_route = rig
21525                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21526                .await;
21527            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21528            rig.sync(vec![record.clone()]).await;
21529            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21530            assert!(rig.live(&owner_route) && owner_route.untouched());
21531            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21532
21533            record.attributes.flow_id = Some("flow:8".to_string());
21534            rig.sync(vec![record]).await;
21535            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21536            let before = before.unwrap();
21537            assert_eq!(after.scope_epoch, before.scope_epoch);
21538            assert!(after.version > before.version);
21539            for route in [&mut owner_route, &mut carrier_route] {
21540                assert!(!rig.live(route));
21541                assert_eq!(
21542                    route.closed_reason(),
21543                    RouteCloseReason::ScopeDelegationChanged
21544                );
21545            }
21546            assert!(rig.live(&unscoped) && unscoped.untouched());
21547            // Each provider also receives a GOODBYE for its drained route;
21548            // consume it before expecting the next route.bind on that sink.
21549            for target in [PLEXUS, OTHER] {
21550                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21551                let goodbye = module_rx
21552                    .try_recv()
21553                    .expect("the provider sees the drain")
21554                    .frame;
21555                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21556                assert!(module_rx.try_recv().is_err());
21557            }
21558            let rebound = rig
21559                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21560                .await;
21561            assert_eq!(
21562                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21563                Some("flow:8")
21564            );
21565        }
21566
21567        /// The owner's sync lands between admission and the module's ack. The
21568        /// open is refused by name, the module's other routes stay up, and the
21569        /// reserved pair is released. Changed content is retryable; an ended
21570        /// scope is not.
21571        #[tokio::test]
21572        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21573            let mut rig = rig().await;
21574            rig.sync(vec![session(1)]).await;
21575            let mut cotenant = rig
21576                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21577                .await;
21578
21579            let mut changed = session(1);
21580            changed.child_owners.push(Principal::Reserved {
21581                module_id: MAGIC.to_string(),
21582            });
21583            let mut ended = None;
21584            for (code, next) in [
21585                (error_codes::SCOPE_CHANGED, vec![changed]),
21586                (error_codes::SCOPE_ENDED, Vec::new()),
21587            ] {
21588                let relayed = rig
21589                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21590                    .await;
21591                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21592                ended = Some(next.is_empty());
21593                rig.sync(next).await;
21594                rig.ack(&relayed).await;
21595                let replies = relayed.task.await.unwrap();
21596                assert_eq!(replies.len(), 1, "{replies:?}");
21597                assert_eq!(parse_error(&replies[0])["code"], code);
21598                assert_eq!(
21599                    subc_protocol::error_codes::is_retryable_route_open(code),
21600                    code == error_codes::SCOPE_CHANGED
21601                );
21602                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21603                // The module is told to drop just the binding it created.
21604                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21605                // Collected, because ending the scope also closes the co-tenant
21606                // route, whose GOODBYE comes first.
21607                let mut goodbyes = Vec::new();
21608                while let Ok(outbound) = plexus_rx.try_recv() {
21609                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21610                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21611                }
21612                assert!(
21613                    goodbyes.contains(&(bind_channel, bind_epoch)),
21614                    "{goodbyes:?}"
21615                );
21616                assert!(rig
21617                    .handler
21618                    .registry
21619                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21620                    .unwrap()
21621                    .is_some());
21622            }
21623            assert_eq!(ended, Some(true));
21624            // The co-tenant stayed up through the change, and closed only when
21625            // the scope ended, by the drain rule rather than by the commit.
21626            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21627        }
21628
21629        /// Each row of the drain table on one set of routes: the owner's, a
21630        /// bare carrier's, and a targeted carrier's to each of its targets.
21631        #[tokio::test]
21632        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21633            struct Case {
21634                name: &'static str,
21635                change: fn(&mut ScopeRecord),
21636                /// Closed routes by index: owner->plexus, aft->plexus,
21637                /// broca->plexus, broca->other.
21638                closed: [Option<RouteCloseReason>; 4],
21639            }
21640            use RouteCloseReason::*;
21641            let cases = [
21642                Case {
21643                    name: "a carrier entry removed",
21644                    change: |r| {
21645                        r.carriers.retain(|c| {
21646                            c.principal
21647                                != Principal::Reserved {
21648                                    module_id: AFT.to_string(),
21649                                }
21650                        })
21651                    },
21652                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21653                },
21654                Case {
21655                    name: "a target removed from a carrier",
21656                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21657                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21658                },
21659                Case {
21660                    name: "a bare carrier narrowed to targets",
21661                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21662                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21663                },
21664                Case {
21665                    name: "delegates turned off",
21666                    change: |r| r.attributes.delegates = false,
21667                    closed: [Some(ScopeDelegationChanged); 4],
21668                },
21669                Case {
21670                    name: "agent_id changed",
21671                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21672                    closed: [Some(ScopeDelegationChanged); 4],
21673                },
21674                Case {
21675                    name: "a carrier added, child owners changed, the record re-sent",
21676                    change: |r| {
21677                        r.carriers.push(carrier(MAGIC, None));
21678                        r.child_owners.push(Principal::Reserved {
21679                            module_id: MAGIC.to_string(),
21680                        });
21681                    },
21682                    closed: [None; 4],
21683                },
21684                Case {
21685                    name: "a target added",
21686                    change: |r| {
21687                        r.carriers[1]
21688                            .targets
21689                            .as_mut()
21690                            .unwrap()
21691                            .push("third".to_string())
21692                    },
21693                    closed: [None; 4],
21694                },
21695                Case {
21696                    name: "delegates turned on",
21697                    change: |r| r.attributes.delegates = true,
21698                    closed: [None; 4],
21699                },
21700            ];
21701            for case in cases {
21702                let mut rig = rig().await;
21703                rig.sync(vec![session(1)]).await;
21704                let scope = || Some(rig_selector("s", Some(1)));
21705                let mut routes = [
21706                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21707                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21708                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21709                    rig.bound(Some(BROCA), OTHER, scope()).await,
21710                ];
21711                let mut record = session(1);
21712                (case.change)(&mut record);
21713                rig.sync(vec![record]).await;
21714                for (index, expected) in case.closed.iter().enumerate() {
21715                    let route = &mut routes[index];
21716                    match expected {
21717                        Some(reason) => {
21718                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21719                            assert_eq!(
21720                                route.closed_reason(),
21721                                *reason,
21722                                "{}: route {index}",
21723                                case.name
21724                            );
21725                        }
21726                        None => {
21727                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21728                            assert!(
21729                                route.untouched(),
21730                                "{}: route {index} was told something",
21731                                case.name
21732                            );
21733                        }
21734                    }
21735                }
21736            }
21737        }
21738
21739        #[tokio::test]
21740        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21741            // Removed, and replaced by a higher epoch.
21742            for next in [Vec::new(), vec![session(2)]] {
21743                let mut rig = rig().await;
21744                rig.sync(vec![session(1)]).await;
21745                let mut route = rig
21746                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21747                    .await;
21748                rig.sync(next).await;
21749                assert!(!rig.live(&route));
21750                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21751            }
21752
21753            // A child whose parent ends: its routes close as parent-ended, the
21754            // child stays live, and routes under the parent close as ended.
21755            let mut rig = rig().await;
21756            let mut child = session(1);
21757            child.scope_ref = "child".to_string();
21758            child.kind = ScopeKind::Worker;
21759            child.parent = Some(ScopeParent::new(
21760                Principal::Reserved {
21761                    module_id: OWNER.to_string(),
21762                },
21763                "s".to_string(),
21764                1,
21765            ));
21766            rig.sync(vec![session(1), child.clone()]).await;
21767            let mut child_route = rig
21768                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21769                .await;
21770            assert_eq!(
21771                child_route.stamp().unwrap().parent_state,
21772                Some(ParentState::Linked)
21773            );
21774            rig.sync(vec![child]).await;
21775            assert!(!rig.live(&child_route));
21776            assert_eq!(
21777                child_route.closed_reason(),
21778                RouteCloseReason::ScopeParentEnded
21779            );
21780        }
21781
21782        #[tokio::test]
21783        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21784        ) {
21785            let mut rig = rig().await;
21786            rig.sync(vec![session(1)]).await;
21787            let mut route = rig
21788                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21789                .await;
21790            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21791            rig.sync(vec![session(1)]).await;
21792            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21793            assert!(rig.live(&route) && route.untouched());
21794
21795            // A call in flight on the route when another carrier is added. A
21796            // forwarded REQUEST holds one credit on the route's flow until the
21797            // module answers; the router takes it exactly like this.
21798            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21799                .forwarding
21800                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21801                .unwrap()
21802            else {
21803                panic!("the route is bound");
21804            };
21805            binding.flow.acquire_tagged(9, false).await.unwrap();
21806            let mut widened = session(1);
21807            widened.carriers.push(carrier(MAGIC, None));
21808            rig.sync(vec![widened]).await;
21809            assert!(rig.live(&route) && route.untouched());
21810            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21811            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21812            // The call's credit is still held on an open flow, so its answer
21813            // will be delivered: closing the route would have closed the flow.
21814            assert_eq!(binding.flow.in_flight(), 1);
21815            binding
21816                .flow
21817                .acquire_tagged(10, false)
21818                .await
21819                .expect("the flow is still open");
21820        }
21821
21822        /// A swap's superseded endpoint keeps its routes until drained; ending
21823        /// the scope closes them there too.
21824        #[tokio::test]
21825        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21826            let mut rig = rig().await;
21827            rig.sync(vec![session(1)]).await;
21828            let mut on_incumbent = rig
21829                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21830                .await;
21831
21832            // Swap plexus: register a candidate and cut over, leaving the
21833            // incumbent superseded with the route still on it.
21834            let (candidate, _candidate_rx) = wide_ctx(9);
21835            let registration = rig
21836                .handler
21837                .registry
21838                .register_candidate_with_control_ops(
21839                    manifest(PLEXUS, PROTOCOL_VERSION),
21840                    PROTOCOL_VERSION,
21841                    candidate.connection_id,
21842                    module_baseline_control_ops(),
21843                )
21844                .unwrap();
21845            rig.forwarding
21846                .register_candidate_module_connection(
21847                    candidate.connection_id,
21848                    PLEXUS.to_string(),
21849                    PROTOCOL_VERSION,
21850                    manifest_concurrency(&registration.manifest),
21851                    candidate.egress.clone(),
21852                )
21853                .unwrap();
21854            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21855            rig.handler
21856                .registry
21857                .promote_candidate(PLEXUS)
21858                .unwrap()
21859                .unwrap();
21860            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21861
21862            rig.sync(Vec::new()).await;
21863            assert!(!rig.live(&on_incumbent));
21864            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21865            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21866            let goodbye = incumbent_rx
21867                .try_recv()
21868                .expect("the superseded endpoint is told")
21869                .frame;
21870            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21871        }
21872    }
21873}
21874
21875#[cfg(test)]
21876mod concurrency_default_exposure_tests {
21877    use super::*;
21878
21879    fn hello_body(role_json: &str) -> Vec<u8> {
21880        format!(
21881            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":[]}}}}}}}}"#
21882        )
21883        .into_bytes()
21884    }
21885
21886    fn manifest_from(body: &[u8]) -> ModuleManifest {
21887        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21888        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21889            .expect("manifest parses")
21890    }
21891
21892    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21893
21894    #[test]
21895    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21896        let body = hello_body(&format!(
21897            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21898        ));
21899        let manifest = manifest_from(&body);
21900        // Precondition: serde really resolved it to the default, so the typed
21901        // manifest alone cannot answer the question this probe exists for.
21902        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21903        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21904    }
21905
21906    #[test]
21907    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21908        let body = hello_body(&format!(
21909            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21910        ));
21911        let manifest = manifest_from(&body);
21912        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21913        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21914    }
21915
21916    #[test]
21917    fn non_management_roles_are_never_reported() {
21918        let body = hello_body(
21919            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21920        );
21921        let manifest = manifest_from(&body);
21922        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21923    }
21924}