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(RequirementStatus::into_wire)
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                    publication.as_deref(),
7662                )
7663                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7664            let script = configured.script.as_ref().map(|entry| {
7665                let approved = self
7666                    .config_runtime
7667                    .as_ref()
7668                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7669                crate::supervise::script::status(entry, approved.as_ref())
7670            });
7671            let configured_enabled = match &approved {
7672                ApprovedDaemonView::Approved {
7673                    config: approved, ..
7674                } => approved
7675                    .modules
7676                    .iter()
7677                    .find(|module| module.module_id == status.module_id)
7678                    .map(|module| module.enabled),
7679                ApprovedDaemonView::NotStamped => self
7680                    .capability_evaluator
7681                    .configured_enabled(&status.module_id),
7682                ApprovedDaemonView::Unavailable => None,
7683            };
7684            let admission_refused = status
7685                .admission_refused
7686                .clone()
7687                .filter(|_| status.enabled && !status.process_alive)
7688                .filter(|_| {
7689                    publication
7690                        .as_ref()
7691                        .and_then(|view| view.registration_declaration(&status.module_id))
7692                        .as_deref()
7693                        == Some("undeclared")
7694                });
7695            // Keep the retired policy field on the wire for one release so
7696            // existing status consumers still receive the platform policy.
7697            let mut entry = SupervisorEntry::new(
7698                status.module_id,
7699                status.state.to_string(),
7700                status.enabled,
7701                status.live,
7702                status.health.status,
7703            )
7704            .with_configured_enabled(configured_enabled)
7705            .with_script(script)
7706            .with_admission_refused(admission_refused)
7707            .with_next_retry_at_ms(next_retry_at_ms)
7708            .with_launch_nonce_env(Some(!cfg!(unix)))
7709            .with_launch_nonce_source(status.launch_nonce_source)
7710            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7711            .with_protocol(status.protocol)
7712            .with_pending_reload(pending_reload)
7713            .with_last_probe_ms(status.health.last_probe_ms)
7714            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7715            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7716            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7717            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7718            .with_restart_count(Some(status.restart_count))
7719            .with_max_restarts(Some(status.max_restarts))
7720            .with_lifetime_restarts(Some(status.lifetime_restarts))
7721            .with_spawn_generation(Some(status.spawn_generation))
7722            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7723            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7724            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7725            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7726            .with_resources(resources);
7727            entry.pending = pending;
7728            modules.push(entry);
7729        }
7730        for module in &mut modules {
7731            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7732                module.tree = tree.clone();
7733                module.cpu_last_hour = hour.clone();
7734            }
7735            module.tree_unavailable = readings
7736                .reasons
7737                .get(&module.module_id)
7738                .map(|reason| (*reason).to_owned());
7739            if module.tree.is_none() {
7740                module.tree_unavailable = Some(
7741                    if not_running.contains(&module.module_id) {
7742                        "not_running"
7743                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7744                        reason
7745                    } else {
7746                        "not_yet_measured"
7747                    }
7748                    .to_owned(),
7749                );
7750            }
7751        }
7752        let response = ClientControlResponse::SupervisorList {
7753            generation,
7754            modules,
7755            daemon: readings.daemon,
7756            agent_commands: readings.agent_commands,
7757        };
7758        Ok(vec![control_response_body_frame(
7759            &frame,
7760            &response,
7761            "ClientControlResponse::SupervisorList",
7762        )?])
7763    }
7764
7765    fn handle_supervisor_stderr_tail(
7766        &self,
7767        frame: Frame,
7768        module_id: String,
7769        max_lines: Option<u32>,
7770        max_bytes: Option<u32>,
7771    ) -> Result<Vec<Frame>, RouterError> {
7772        let Some(module) = self.supervisor.get(&module_id) else {
7773            return Ok(vec![control_error_frame(
7774                &frame,
7775                "unknown_module",
7776                format!("module_id '{module_id}' is not supervised"),
7777            )?]);
7778        };
7779
7780        let snapshot = module.stderr_tail(
7781            max_lines.map(|value| value as usize),
7782            max_bytes.map(|value| value as usize),
7783        );
7784
7785        let response = ClientControlResponse::SupervisorStderrTail {
7786            module_id,
7787            tail: StderrTail {
7788                capture: match snapshot.capture {
7789                    CaptureState::Captured => StderrCaptureState::Captured,
7790                    CaptureState::Incomplete { reason } => {
7791                        StderrCaptureState::Incomplete { reason }
7792                    }
7793                    CaptureState::NotCaptured { reason } => {
7794                        StderrCaptureState::NotCaptured { reason }
7795                    }
7796                },
7797                entries: snapshot
7798                    .entries
7799                    .into_iter()
7800                    .map(|entry| match entry {
7801                        TailEntry::Line {
7802                            text,
7803                            truncated,
7804                            at_ms,
7805                        } => StderrTailEntry::Line {
7806                            text,
7807                            truncated,
7808                            at_ms,
7809                        },
7810                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7811                    })
7812                    .collect(),
7813                dropped_lines: snapshot.dropped_lines,
7814            },
7815        };
7816        Ok(vec![control_response_body_frame(
7817            &frame,
7818            &response,
7819            "ClientControlResponse::SupervisorStderrTail",
7820        )?])
7821    }
7822
7823    async fn observe_control_wait<F: std::future::Future>(
7824        &self,
7825        ctx: &RouteCtx,
7826        target: Option<&str>,
7827        kind: &'static str,
7828        future: F,
7829    ) -> F::Output {
7830        self.counters
7831            .observe_reader_wait(
7832                || {
7833                    let module = self
7834                        .forwarding
7835                        .module_id_for_connection(ctx.connection_id)
7836                        .ok()
7837                        .flatten();
7838                    let principal = if module.is_some() { "module" } else { "direct" };
7839                    (
7840                        self.resolve_reader_wait_target(kind, target)
7841                            .or(module)
7842                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7843                        principal.into(),
7844                    )
7845                },
7846                kind,
7847                future,
7848            )
7849            .await
7850    }
7851
7852    /// Resolve the reader-wait module ID only from supervisor or registry
7853    /// records; never attribute a wait from the request selector alone.
7854    pub(crate) fn resolve_reader_wait_target(
7855        &self,
7856        op: &str,
7857        selector: Option<&str>,
7858    ) -> Option<String> {
7859        let selector = selector?;
7860        match op {
7861            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7862                .supervisor
7863                .get(selector)
7864                .map(|module| module.module_id().to_owned()),
7865            ops::SUPERVISOR_HEALTH_PROBE => self
7866                .registry
7867                .get_module(selector)
7868                .ok()
7869                .flatten()
7870                .map(|registration| registration.manifest.module_id),
7871            _ => None,
7872        }
7873    }
7874
7875    async fn handle_supervisor_terminals(
7876        &self,
7877        ctx: &RouteCtx,
7878        frame: Frame,
7879        module_id: String,
7880    ) -> Result<Vec<Frame>, RouterError> {
7881        let Some(module) = self.supervisor.get(&module_id) else {
7882            return Ok(vec![control_error_frame(
7883                &frame,
7884                "unknown_module",
7885                format!("module_id '{module_id}' is not supervised"),
7886            )?]);
7887        };
7888
7889        // The journal read runs on a blocking thread: it can be megabytes of
7890        // file I/O and must not occupy a runtime worker.
7891        let terminals = self
7892            .observe_control_wait(
7893                ctx,
7894                Some(module.module_id()),
7895                ops::SUPERVISOR_TERMINALS,
7896                module.read_durable_terminal_history(),
7897            )
7898            .await
7899            .map_err(|error| {
7900                RouterError::backend(
7901                    0,
7902                    frame.header.corr,
7903                    format!("failed to read terminal history: {error}"),
7904                )
7905            })?;
7906        let response = ClientControlResponse::SupervisorTerminals {
7907            module_id,
7908            terminals,
7909        };
7910        Ok(vec![control_response_body_frame(
7911            &frame,
7912            &response,
7913            "ClientControlResponse::SupervisorTerminals",
7914        )?])
7915    }
7916
7917    fn handle_supervisor_routes(
7918        &self,
7919        frame: Frame,
7920        module_id: Option<String>,
7921    ) -> Result<Vec<Frame>, RouterError> {
7922        let modules = self
7923            .forwarding
7924            .route_census(module_id.as_deref())
7925            .map_err(RouterError::Forwarding)?
7926            .into_iter()
7927            .map(|(module_id, routes)| SupervisorRouteModule {
7928                module_id,
7929                routes: routes
7930                    .into_iter()
7931                    .map(|route| SupervisorRoute {
7932                        consumer: match route.principal {
7933                            Principal::Reserved { module_id } => {
7934                                SupervisorRouteConsumer::Reserved { module_id }
7935                            }
7936                            Principal::Direct | Principal::Unverified => {
7937                                SupervisorRouteConsumer::Direct {
7938                                    connection_id: route.goodbye_target.connection_id.get(),
7939                                }
7940                            }
7941                        },
7942                        age_ms: Instant::now()
7943                            .saturating_duration_since(route.bound_at)
7944                            .as_millis()
7945                            .try_into()
7946                            .unwrap_or(u64::MAX),
7947                        draining: route.draining,
7948                        drain_reason: route.drain_reason,
7949                    })
7950                    .collect(),
7951            })
7952            .collect();
7953        let response = ClientControlResponse::SupervisorRoutes { modules };
7954        Ok(vec![control_response_body_frame(
7955            &frame,
7956            &response,
7957            "ClientControlResponse::SupervisorRoutes",
7958        )?])
7959    }
7960
7961    fn running_registration_method(
7962        &self,
7963        module: &str,
7964    ) -> Option<subc_control::RegistrationMethod> {
7965        let registration = self.registry.get_module(module).ok()??;
7966        let connection = registration.connection_id;
7967        let channel = self.supervisor.registration_spawn(connection).is_some();
7968        let nonce = if channel {
7969            None
7970        } else {
7971            self.hello_launch_nonces
7972                .lock()
7973                .ok()?
7974                .nonce(connection)
7975                .map(str::to_owned)
7976        };
7977        if !channel && nonce.is_none() {
7978            return None;
7979        }
7980        self.supervisor
7981            .registration_snapshot_is_current_live(
7982                &self.registry,
7983                module,
7984                connection,
7985                nonce.as_deref(),
7986            )
7987            .then_some(if channel {
7988                subc_control::RegistrationMethod::Channel
7989            } else {
7990                subc_control::RegistrationMethod::Nonce
7991            })
7992    }
7993
7994    async fn handle_supervisor_provenance(
7995        &self,
7996        ctx: &RouteCtx,
7997        frame: Frame,
7998        module_id: Option<String>,
7999    ) -> Result<Vec<Frame>, RouterError> {
8000        let targeted = module_id.is_some();
8001        let selected = if let Some(module_id) = module_id {
8002            let Some(module) = self.supervisor.get(&module_id) else {
8003                return Ok(vec![control_error_frame(
8004                    &frame,
8005                    "unknown_module",
8006                    format!("module_id '{module_id}' is not supervised"),
8007                )?]);
8008            };
8009            vec![module]
8010        } else {
8011            self.supervisor.list()
8012        };
8013
8014        let target = targeted.then(|| selected[0].module_id());
8015        let declarations = if let Some(owner) = &self.config_runtime {
8016            owner
8017                .on_blocking(|owner| owner.registration_declarations())
8018                .await
8019                .ok()
8020        } else {
8021            None
8022        };
8023        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
8024            let mut modules = Vec::with_capacity(selected.len());
8025            let mut extensions = Vec::with_capacity(selected.len());
8026            for module in &selected {
8027                let (status, observed_image) = module
8028                    .status_and_running_image_agreement()
8029                    .await
8030                    .map_err(|err| {
8031                        RouterError::backend(
8032                            0,
8033                            frame.header.corr,
8034                            format!("failed to read supervisor status: {err}"),
8035                        )
8036                    })?;
8037                let module_declared = self
8038                    .registry
8039                    .get_module(&status.module_id)
8040                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8041                    .and_then(|registration| registration.manifest.provenance)
8042                    .map(|build| ModuleDeclaredProvenance::Reported { build })
8043                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
8044                #[cfg(test)]
8045                let running_image = match &self.provenance_probe_override {
8046                    Some(result) => result.clone(),
8047                    None => observed_image,
8048                };
8049                #[cfg(not(test))]
8050                let running_image = observed_image;
8051                let registration = self.running_registration_method(&status.module_id);
8052                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
8053                    .with_registration(registration);
8054                extension.registration_declaration = declarations
8055                    .as_ref()
8056                    .and_then(|entries| entries.get(&status.module_id))
8057                    .cloned();
8058                if status.process_alive && status.registration_declaration.is_some() {
8059                    extension.registration_declaration = status.registration_declaration.clone();
8060                }
8061                extensions.push(extension);
8062                modules.push(SupervisorModuleProvenance {
8063                    module_id: status.module_id,
8064                    module_declared,
8065                    daemon_observed: SupervisorObservedProcess {
8066                        launch_nonce_source: status.launch_nonce_source,
8067                        pid: status.pid,
8068                        spawned_at_ms: status.spawned_at_ms,
8069                        spawned_from: status.spawned_from,
8070                        running_image,
8071                    },
8072                });
8073            }
8074            let daemon = SupervisorDaemonProvenance {
8075                daemon_build: self.daemon_provenance.build.clone(),
8076                daemon_observed: DaemonObservedProcess {
8077                    pid: self.daemon_provenance.pid,
8078                    started_at_ms: self
8079                        .daemon_provenance
8080                        .start_clock
8081                        .map(|clock| clock.started_at_ms())
8082                        .or(self.daemon_provenance.started_at_ms),
8083                    running_image: self
8084                        .daemon_provenance
8085                        .probe
8086                        .observe(
8087                            self.daemon_provenance.pid,
8088                            self.daemon_provenance.executable_path.as_deref(),
8089                            self.daemon_provenance.executable_identity.clone(),
8090                            self.daemon_provenance.process_start_time,
8091                        )
8092                        .await,
8093                },
8094            };
8095            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8096            let mut response = serde_json::to_value(response)
8097                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8098            for (entry, extension) in response["modules"]
8099                .as_array_mut()
8100                .expect("provenance modules are an array")
8101                .iter_mut()
8102                .zip(extensions)
8103            {
8104                extension.write_to(entry).map_err(|error| {
8105                    RouterError::backend(0, frame.header.corr, error.to_string())
8106                })?;
8107            }
8108            Ok(vec![control_response_body_frame(
8109                &frame,
8110                &response,
8111                "ClientControlResponse::SupervisorProvenance",
8112            )?])
8113        })
8114        .await
8115    }
8116
8117    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8118        self.refresh_capability_requirements();
8119        let publication = self
8120            .config_runtime
8121            .as_ref()
8122            .and_then(|owner| owner.polled_snapshot().ok());
8123        let generation = self
8124            .registry
8125            .generation()
8126            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8127        let modules = self
8128            .supervisor
8129            .list()
8130            .into_iter()
8131            .map(|module| {
8132                let status = module.status_for_control("health").map_err(|err| {
8133                    RouterError::backend(
8134                        0,
8135                        frame.header.corr,
8136                        format!("failed to read supervisor health: {err}"),
8137                    )
8138                })?;
8139                let module_id = status.module_id;
8140                let capability_detail = self
8141                    .capability_evaluator
8142                    .required_problem_detail(&module_id);
8143                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8144                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8145                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8146                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8147                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8148                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8149                Ok(SupervisorHealthEntry {
8150                    module_id,
8151                    status: status.health.status,
8152                    detail: append_capability_problem_detail(
8153                        status.health.detail,
8154                        capability_detail,
8155                    ),
8156                    metrics: status.health.metrics,
8157                    consecutive_failures: status.health.consecutive_failures,
8158                    late_answer_count: status.health.late_answer_count,
8159                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8160                    last_action: status.health.last_action,
8161                    last_action_ms: status.health.last_action_ms,
8162                    last_probe_ms: status.health.last_probe_ms,
8163                })
8164            })
8165            .collect::<Result<Vec<_>, RouterError>>()?;
8166        let response = ClientControlResponse::SupervisorHealth {
8167            generation,
8168            modules,
8169        };
8170        Ok(vec![control_response_body_frame(
8171            &frame,
8172            &response,
8173            "ClientControlResponse::SupervisorHealth",
8174        )?])
8175    }
8176
8177    async fn handle_supervisor_restart(
8178        &self,
8179        frame: Frame,
8180        module_id: String,
8181        drain_timeout_ms: Option<u64>,
8182        requester: Principal,
8183    ) -> Result<Vec<Frame>, RouterError> {
8184        let operation_lock = self.supervisor.operation_lock();
8185        let _operation_guard = operation_lock.lock().await;
8186        let Some(module) = self.supervisor.get(&module_id) else {
8187            return Ok(vec![control_error_frame(
8188                &frame,
8189                "unknown_module",
8190                format!("module_id '{module_id}' is not supervised"),
8191            )?]);
8192        };
8193
8194        self.route_outages.mark_operator_action(&module_id);
8195        if let Err(err) = module
8196            .restart_requested(drain_timeout_ms, Some(requester))
8197            .await
8198        {
8199            self.route_outages
8200                .operator_action_ended_unrefused(&module_id);
8201            let (code, message) = match err {
8202                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8203                crate::supervise::SuperviseError::Disabled { .. } => {
8204                    ("module_disabled", err.to_string())
8205                }
8206                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8207                    ("swap_in_progress", err.to_string())
8208                }
8209                _ => (
8210                    "target_unavailable",
8211                    format!("failed to restart module_id '{module_id}': {err}"),
8212                ),
8213            };
8214            return Ok(vec![control_error_frame(&frame, code, message)?]);
8215        }
8216
8217        let response = ClientControlResponse::SupervisorAck {
8218            module_id,
8219            applied: true,
8220        };
8221        Ok(vec![control_response_body_frame(
8222            &frame,
8223            &response,
8224            "ClientControlResponse::SupervisorAck",
8225        )?])
8226    }
8227
8228    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8229    /// when the old process has finished draining: a caller whose own lane
8230    /// rides the old process must get its reply before that drain waits on it.
8231    async fn handle_supervisor_swap(
8232        &self,
8233        frame: Frame,
8234        module_id: String,
8235        ready_timeout_ms: Option<u64>,
8236        requester: Principal,
8237    ) -> Result<Vec<Frame>, RouterError> {
8238        // The daemon-wide operation lock is held only to resolve the handle,
8239        // not across the swap. The swap can take its whole readiness budget,
8240        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8241        // holding it here would park an operator's stop behind the swap it is
8242        // meant to abort. A rescan or stop that reaches the module during the
8243        // swap is served by the swap itself (see `supervise_swap`).
8244        let module = {
8245            let operation_lock = self.supervisor.operation_lock();
8246            let _operation_guard = operation_lock.lock().await;
8247            self.supervisor.get(&module_id)
8248        };
8249        let Some(module) = module else {
8250            return Ok(vec![control_error_frame(
8251                &frame,
8252                "unknown_module",
8253                format!("module_id '{module_id}' is not supervised"),
8254            )?]);
8255        };
8256
8257        self.route_outages.mark_operator_action(&module_id);
8258        if let Err(err) = module
8259            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8260            .await
8261        {
8262            self.route_outages
8263                .operator_action_ended_unrefused(&module_id);
8264            use crate::supervise::SuperviseError;
8265            let message = err.to_string();
8266            let error = match err {
8267                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8268                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8269                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8270                    code: "swap_refused".to_string(),
8271                    message,
8272                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8273                },
8274                SuperviseError::SwapFailed {
8275                    arm,
8276                    candidate_exit,
8277                    ..
8278                } => ErrorBody {
8279                    code: "swap_failed".to_string(),
8280                    message,
8281                    detail: Some(serde_json::json!({
8282                        "arm": arm.as_str(),
8283                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8284                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8285                    })),
8286                },
8287                _ => ErrorBody::new(
8288                    "target_unavailable",
8289                    format!("failed to swap module_id '{module_id}': {message}"),
8290                ),
8291            };
8292            return Ok(vec![control_error_body_frame(&frame, error)?]);
8293        }
8294        // A completed swap kept the incumbent serving until cutover, so it
8295        // usually opened no outage; a mark left behind would make the next,
8296        // unrelated outage read as requested.
8297        self.route_outages
8298            .operator_action_ended_unrefused(&module_id);
8299
8300        let response = ClientControlResponse::SupervisorAck {
8301            module_id,
8302            applied: true,
8303        };
8304        Ok(vec![control_response_body_frame(
8305            &frame,
8306            &response,
8307            "ClientControlResponse::SupervisorAck",
8308        )?])
8309    }
8310
8311    async fn handle_supervisor_reload(
8312        &self,
8313        frame: Frame,
8314        module_id: String,
8315        requester: Principal,
8316    ) -> Result<Vec<Frame>, RouterError> {
8317        let operation_lock = self.supervisor.operation_lock();
8318        let _operation_guard = operation_lock.lock().await;
8319        let Some(module) = self.supervisor.get(&module_id) else {
8320            return Ok(vec![control_error_frame(
8321                &frame,
8322                "unknown_module",
8323                format!("module_id '{module_id}' is not supervised"),
8324            )?]);
8325        };
8326
8327        self.route_outages.mark_operator_action(&module_id);
8328        if let Err(err) = module.reload_requested(Some(requester)).await {
8329            self.route_outages
8330                .operator_action_ended_unrefused(&module_id);
8331            let (code, message) = match err {
8332                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8333                crate::supervise::SuperviseError::Disabled { .. } => {
8334                    ("module_disabled", err.to_string())
8335                }
8336                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8337                    ("swap_in_progress", err.to_string())
8338                }
8339                _ => (
8340                    "reload_failed",
8341                    format!("failed to reload module_id '{module_id}': {err}"),
8342                ),
8343            };
8344            return Ok(vec![control_error_frame(&frame, code, message)?]);
8345        }
8346
8347        let response = ClientControlResponse::SupervisorAck {
8348            module_id,
8349            applied: true,
8350        };
8351        Ok(vec![control_response_body_frame(
8352            &frame,
8353            &response,
8354            "ClientControlResponse::SupervisorAck",
8355        )?])
8356    }
8357
8358    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8359    /// the configuration comes from and whether to apply it; every mode then
8360    /// runs the same comparison, so a preview describes the apply it previews.
8361    async fn handle_supervisor_rescan(
8362        &self,
8363        frame: Frame,
8364        mode: RescanMode,
8365        requester: Principal,
8366    ) -> Result<Vec<Frame>, RouterError> {
8367        let preview = mode.previews();
8368        let Some(context) = self.rescan.clone() else {
8369            return Ok(vec![control_error_frame(
8370                &frame,
8371                "rescan_unavailable",
8372                "the daemon was not started with a reloadable config path".to_string(),
8373            )?]);
8374        };
8375
8376        let _rescan_guard = context.rescan_lock.lock().await;
8377        let rescan_checked::RescanInput {
8378            config: loaded,
8379            approved_preview,
8380            guard: _operation_guard,
8381        } = match self.rescan_input(&mode, &context).await {
8382            Ok(input) => input,
8383            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
8384        };
8385        // `load` reports a missing file as Ok(None), which is correct at boot
8386        // (no config, nothing to supervise) and catastrophic here: rescan treats
8387        // "not in the config" as "remove it", so an absent file would read as an
8388        // empty module list and retire the entire running fleet. An editor
8389        // writing via write-new-then-rename, or a half-finished edit, is enough
8390        // to open that window. Refuse instead: a config that cannot be read
8391        // carries no instruction to remove anything.
8392        let Some((config, activity_config)) = loaded else {
8393            return Ok(vec![control_error_frame(
8394                &frame,
8395                "invalid_daemon_config",
8396                format!(
8397                    "daemon config not found at {}; refusing to rescan (an absent config would \
8398                     retire every supervised module)",
8399                    context.config_path.display()
8400                ),
8401            )?]);
8402        };
8403        let (
8404            configured_port,
8405            storage_config,
8406            admission_facts_carrier_module_id,
8407            admission_facts_targets,
8408            scope_authority_owners,
8409            federated_scope_owner,
8410            privileged_operator_prompt,
8411            modules,
8412            reserved_capabilities,
8413        ) = (
8414            config.port,
8415            config.storage,
8416            config.admission_facts_carrier_module_id,
8417            config.admission_facts_targets,
8418            config.scope_authority_owners,
8419            config.federated_scope_owner,
8420            config.privileged_operator_prompt,
8421            config.modules,
8422            config.reserved_capabilities,
8423        );
8424
8425        // Collect the sections rescan cannot apply, so the REPLY carries them.
8426        //
8427        // The warning below has always been correct and has always gone only to
8428        // the journal -- addressed to whoever reads logs, while the person who
8429        // just edited the config is looking at the CLI. Naming each section
8430        // individually rather than setting a flag: "something outside modules
8431        // changed" sends the operator back to diffing their own file, which is
8432        // the work this is meant to save.
8433        let mut restart_required = Vec::new();
8434        for section in RestartRequiredSection::ALL {
8435            let changed = match section {
8436                RestartRequiredSection::Port => configured_port != context.configured_port,
8437                RestartRequiredSection::Storage => storage_config != context.storage_config,
8438                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8439                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8440                }
8441                RestartRequiredSection::AdmissionFactsTargets => {
8442                    admission_facts_targets != context.admission_facts_targets
8443                }
8444                RestartRequiredSection::ScopeAuthorityOwners => {
8445                    scope_authority_owners != context.scope_authority_owners
8446                }
8447                RestartRequiredSection::FederatedScopeOwner => {
8448                    federated_scope_owner != context.federated_scope_owner
8449                }
8450                RestartRequiredSection::PrivilegedOperatorPrompt => {
8451                    privileged_operator_prompt != context.privileged_operator_prompt
8452                }
8453            };
8454            if changed {
8455                restart_required.push(section.label().to_string());
8456            }
8457        }
8458        if !restart_required.is_empty() {
8459            warn!(
8460                config_path = %context.config_path.display(),
8461                sections = %restart_required.join(", "),
8462                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8463            );
8464        }
8465
8466        for configured in &modules {
8467            if let Err(err) = validate_spec(&configured.module_spec()) {
8468                return Ok(vec![control_error_frame(
8469                    &frame,
8470                    "invalid_daemon_config",
8471                    format!("supervisor rescan rejected daemon config: {err}"),
8472                )?]);
8473            }
8474        }
8475
8476        let configured_capabilities = modules
8477            .iter()
8478            .map(|module| (module.module_id.clone(), module.enabled))
8479            .collect::<Vec<_>>();
8480        let preview_capability_warnings = if preview {
8481            let (_, registrations) = self.runtime_capability_snapshot()?;
8482            let current_modules = self
8483                .supervisor
8484                .list()
8485                .into_iter()
8486                .map(|module| module.module_id().to_string())
8487                .collect::<BTreeSet<_>>();
8488            let resulting_modules = configured_capabilities.clone();
8489            let removed = current_modules
8490                .into_iter()
8491                .filter(|module_id| {
8492                    !resulting_modules
8493                        .iter()
8494                        .any(|(configured_id, _)| configured_id == module_id)
8495                })
8496                .collect::<Vec<_>>();
8497            // A candidate preview also names providers the candidate disables.
8498            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8499            let disabled = match &mode {
8500                RescanMode::Candidate(_) => resulting_modules
8501                    .iter()
8502                    .filter(|(_, enabled)| !enabled)
8503                    .map(|(module_id, _)| module_id.clone())
8504                    .collect::<Vec<_>>(),
8505                _ => Vec::new(),
8506            };
8507            self.capability_evaluator.preview_warnings(
8508                resulting_modules,
8509                &removed,
8510                &disabled,
8511                &registrations,
8512            )
8513        } else {
8514            Vec::new()
8515        };
8516        let reconciled = match (&mode, approved_preview.as_ref()) {
8517            (RescanMode::Preview, Some(approved)) => Ok((
8518                config_gate::preview_approved_daemon(approved, &modules),
8519                Vec::new(),
8520            )),
8521            (RescanMode::Candidate(candidate), _) => self
8522                .preview_candidate(&context, modules, candidate)
8523                .map(|result| (result, Vec::new())),
8524            _ => {
8525                self.reconcile_supervised_modules(
8526                    &context.supervisor,
8527                    modules,
8528                    preview,
8529                    requester.clone(),
8530                )
8531                .await
8532            }
8533        };
8534        let (result, changed) = match reconciled {
8535            Ok(result) => result,
8536            Err(message) => {
8537                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8538            }
8539        };
8540        if !preview {
8541            if let Some(ledger) = &self.activity {
8542                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8543                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8544            }
8545            if let Err(code) = self.configure_activity(activity_config).await {
8546                warn!(
8547                    code,
8548                    "activity retention could not be applied during rescan"
8549                );
8550            }
8551            self.capability_evaluator
8552                .configure(configured_capabilities, reserved_capabilities);
8553            self.capability_evaluator.wake_deadline_loop();
8554            self.refresh_capability_requirements();
8555        }
8556        let mut result = result;
8557        result.restart_required = restart_required;
8558        result.capability_warnings = preview_capability_warnings;
8559        let response = ClientControlResponse::SupervisorRescan { result };
8560        Ok(vec![control_response_body_frame(
8561            &frame,
8562            &response,
8563            "ClientControlResponse::SupervisorRescan",
8564        )?])
8565    }
8566
8567    async fn handle_supervisor_release_reserved(
8568        &self,
8569        frame: Frame,
8570        module_id: String,
8571    ) -> Result<Vec<Frame>, RouterError> {
8572        let Some(context) = self.rescan.clone() else {
8573            return Ok(vec![control_error_frame(
8574                &frame,
8575                "release_unavailable",
8576                "reserved-id release requires a daemon started with a reloadable config path",
8577            )?]);
8578        };
8579        let operation_lock = self.supervisor.operation_lock();
8580        let _operation_guard = operation_lock.lock().await;
8581        let approved = if let Some(owner) = &self.config_runtime {
8582            // Observe the file as a proposal, but decide membership solely from
8583            // approved bytes. A proposed re-add must not retain a removed id.
8584            match owner
8585                .on_blocking(|owner| {
8586                    owner.observe_file_proposal()?;
8587                    owner.approved_daemon_configuration()
8588                })
8589                .await
8590            {
8591                Ok(config) => config,
8592                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8593            }
8594        } else {
8595            None
8596        };
8597        let loaded = if let Some(approved) = approved {
8598            Ok(Some(approved))
8599        } else {
8600            crate::daemon_config::load(&context.config_path)
8601        };
8602        let loaded = match loaded {
8603            Ok(Some(config)) => config,
8604            Ok(None) => {
8605                return Ok(vec![control_error_frame(
8606                    &frame,
8607                    "invalid_daemon_config",
8608                    format!(
8609                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8610                        context.config_path.display()
8611                    ),
8612                )?])
8613            }
8614            Err(err) => {
8615                return Ok(vec![control_error_frame(
8616                    &frame,
8617                    "invalid_daemon_config",
8618                    format!("unable to verify reserved-id release against daemon config: {err}"),
8619                )?])
8620            }
8621        };
8622        if loaded
8623            .modules
8624            .iter()
8625            .any(|configured| configured.module_id == module_id)
8626        {
8627            return Ok(vec![control_error_frame(
8628                &frame,
8629                "reserved_module_configured",
8630                format!(
8631                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8632                ),
8633            )?]);
8634        }
8635        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8636            return Ok(vec![control_error_frame(
8637                &frame,
8638                "reserved_gate_not_retained",
8639                format!(
8640                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8641                ),
8642            )?]);
8643        }
8644
8645        let response = ClientControlResponse::SupervisorAck {
8646            module_id,
8647            applied: true,
8648        };
8649        Ok(vec![control_response_body_frame(
8650            &frame,
8651            &response,
8652            "ClientControlResponse::SupervisorAck",
8653        )?])
8654    }
8655
8656    /// Compare the configured module set with the supervised one, changing
8657    /// nothing. The staged spec each supervised module holds is what the
8658    /// configured entry is compared with.
8659    fn plan_rescan(
8660        &self,
8661        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8662    ) -> Result<RescanPlan, String> {
8663        let mut current = BTreeMap::new();
8664        for module in self.supervisor.list() {
8665            let (spec, health) = module.configuration().map_err(|err| {
8666                format!(
8667                    "failed to read configuration for module_id '{}': {err}",
8668                    module.module_id()
8669                )
8670            })?;
8671            let enabled = module
8672                .status()
8673                .map_err(|err| {
8674                    format!(
8675                        "failed to read status for module_id '{}': {err}",
8676                        module.module_id()
8677                    )
8678                })?
8679                .enabled;
8680            current.insert(
8681                module.module_id().to_string(),
8682                (module, spec, health, enabled),
8683            );
8684        }
8685        let configured = configured_modules
8686            .into_iter()
8687            .map(|module| (module.module_id.clone(), module))
8688            .collect::<BTreeMap<_, _>>();
8689
8690        let added = configured
8691            .keys()
8692            .filter(|module_id| !current.contains_key(*module_id))
8693            .cloned()
8694            .collect::<Vec<_>>();
8695        let removed = current
8696            .keys()
8697            .filter(|module_id| !configured.contains_key(*module_id))
8698            .cloned()
8699            .collect::<Vec<_>>();
8700        let mut changed_pending_reload = Vec::new();
8701        let mut changed_pending = Vec::new();
8702        let mut configuration_changes = BTreeSet::new();
8703        let mut enabled_changes = BTreeSet::new();
8704        let mut unchanged = 0_u32;
8705        let publication = self
8706            .config_runtime
8707            .as_ref()
8708            .and_then(|owner| owner.polled_snapshot().ok());
8709
8710        for (module_id, configured_module) in &configured {
8711            let Some((module, current_spec, current_health, current_enabled)) =
8712                current.get(module_id)
8713            else {
8714                continue;
8715            };
8716            // Compare the whole launch spec so a future launch field cannot
8717            // accidentally become a live-only policy change. Health is stored
8718            // separately and applies live without replacing the process.
8719            let launch_changed = *current_spec != configured_module.module_spec();
8720            let configuration_changed =
8721                launch_changed || *current_health != configured_module.health;
8722            let pending = self.pending_module_fields(
8723                module,
8724                Some(configured_module),
8725                configuration_changed,
8726                Self::registration_channel_in_force(
8727                    publication
8728                        .as_ref()
8729                        .and_then(|view| view.registration_declaration(module_id))
8730                        .as_deref(),
8731                    publication
8732                        .as_ref()
8733                        .and_then(|view| match &view.approved_daemon {
8734                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8735                                config,
8736                                ..
8737                            } => config
8738                                .modules
8739                                .iter()
8740                                .find(|entry| entry.module_id == *module_id)
8741                                .map(|entry| entry.registration_channel),
8742                            _ => None,
8743                        }),
8744                ),
8745                publication.as_deref(),
8746            )?;
8747            let has_pending = !pending.is_empty();
8748            if has_pending {
8749                changed_pending.push(subc_control::SupervisorPendingModule {
8750                    module_id: module_id.clone(),
8751                    fields: pending
8752                        .into_iter()
8753                        .map(|mut field| {
8754                            field.value = None;
8755                            field
8756                        })
8757                        .collect(),
8758                });
8759            }
8760            // Applying a rescan also replaces the recorded config value, even
8761            // when an operator already put the runtime in the requested state.
8762            let enabled_changed = *current_enabled != configured_module.enabled
8763                || self
8764                    .capability_evaluator
8765                    .configured_enabled(module_id)
8766                    .is_some_and(|enabled| enabled != configured_module.enabled);
8767            if configuration_changed {
8768                configuration_changes.insert(module_id.clone());
8769            }
8770            if launch_changed {
8771                changed_pending_reload.push(module_id.clone());
8772            }
8773            if enabled_changed {
8774                enabled_changes.insert(module_id.clone());
8775            }
8776            if !configuration_changed && !enabled_changed && !has_pending {
8777                unchanged = unchanged.saturating_add(1);
8778            }
8779        }
8780        Ok(RescanPlan {
8781            current,
8782            configured,
8783            added,
8784            removed,
8785            changed_pending_reload,
8786            changed_pending,
8787            configuration_changes,
8788            enabled_changes,
8789            unchanged,
8790        })
8791    }
8792
8793    /// Reconcile the running module set against the configured one.
8794    ///
8795    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8796    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8797    /// deliberately shares this function with the executing path rather than
8798    /// computing the same diff somewhere else -- two implementations of one
8799    /// decision agree until they do not, and the whole value of a preview is that
8800    /// it describes the operation that will actually run.
8801    async fn reconcile_supervised_modules(
8802        &self,
8803        supervisor: &Supervisor,
8804        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8805        preview: bool,
8806        requester: Principal,
8807    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8808        let plan = self.plan_rescan(configured_modules)?;
8809
8810        // Everything above this point is pure computation over two snapshots.
8811        // Everything below MUTATES. The preview returns here so the boundary is a
8812        // single early return rather than a condition repeated at each mutation
8813        // site, where one missed guard would apply part of a change the caller was
8814        // told would not happen.
8815        if preview {
8816            return Ok((plan.preview_result(), Vec::new()));
8817        }
8818        let changed = plan
8819            .configuration_changes
8820            .union(&plan.enabled_changes)
8821            .cloned()
8822            .collect::<Vec<_>>();
8823        let RescanPlan {
8824            current,
8825            configured,
8826            added,
8827            removed,
8828            changed_pending_reload,
8829            changed_pending,
8830            configuration_changes,
8831            enabled_changes,
8832            unchanged,
8833        } = plan;
8834        // The staged generation moves before the first change rather than
8835        // after the last, so a rescan that fails partway still invalidates
8836        // every earlier `supervisor.rescan_checked` preview: part of its diff
8837        // may have run.
8838        if !(added.is_empty()
8839            && removed.is_empty()
8840            && configuration_changes.is_empty()
8841            && changed_pending.is_empty()
8842            && enabled_changes.is_empty())
8843        {
8844            if let Some(context) = &self.rescan {
8845                context
8846                    .generation
8847                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8848            }
8849        }
8850
8851        for module_id in &removed {
8852            let module = &current
8853                .get(module_id)
8854                .expect("removed module came from current supervisor state")
8855                .0;
8856            module
8857                .retire_requested(Some(requester.clone()))
8858                .await
8859                .map_err(|err| {
8860                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8861                })?;
8862            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8863            //
8864            // `handle_route_open` resolves an absent module in three steps:
8865            // registry, then supervisor status, then tombstone. Retiring first
8866            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8867            // went with the teardown above, the supervisor entry went with
8868            // `retire`, and the tombstone does not exist yet -- so a route.open
8869            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8870            // it") for a module that was deliberately removed and whose caller
8871            // should get `module_removed` (TERMINAL, carrying a removal age).
8872            //
8873            // Writing the tombstone first closes it: during the window the
8874            // supervisor entry still answers, so the caller gets
8875            // `target_unavailable` -- retryable, and TRUE, because the module
8876            // is mid-teardown. After both statements it is `module_removed`.
8877            // No instant remains where a removed module reads as one that
8878            // never existed.
8879            //
8880            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8881            // the absence of a test beside a fix invites deletion: these are
8882            // two sync statements with no await between them, so reaching the
8883            // window needs a second worker thread to land exactly between them
8884            // and there is no hook to force it. MEASURED: the 25 daemon_config
8885            // tests pass identically with the old order and the new one, so
8886            // the existing suite cannot see this and a green run is not
8887            // evidence either way. What the suite does hold is the
8888            // post-condition -- a removed module answers `module_removed` --
8889            // which this preserves.
8890            //
8891            // Found by an Athena panel reading the shipped tree against a
8892            // design note (2026-09-19), as the one concrete instance of that
8893            // note's class that survived contact with source. Direction is
8894            // benign: retryable where terminal was intended, never the reverse.
8895            self.supervisor.record_rescan_removal(module_id);
8896            self.supervisor.retire(module_id);
8897            self.route_outages.forget(module_id);
8898        }
8899
8900        for module_id in configured.keys() {
8901            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8902                continue;
8903            };
8904            let configured_module = configured
8905                .get(module_id)
8906                .expect("configured module id came from configured map");
8907            if configuration_changes.contains(module_id) {
8908                module
8909                    .update_configuration(
8910                        configured_module.module_spec(),
8911                        configured_module.health.clone(),
8912                        configured_module.drain_timeout_ms,
8913                    )
8914                    .await
8915                    .map_err(|err| {
8916                        format!(
8917                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8918                        )
8919                    })?;
8920            }
8921            // Config-only drift is applied by the evaluator's config update;
8922            // do not turn it into a runtime start or stop.
8923            if *current_enabled != configured_module.enabled {
8924                // A rescan that starts or stops a module applies an operator's
8925                // edit to the config, so the resulting outage was asked for.
8926                self.route_outages.mark_operator_action(module_id);
8927                module
8928                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8929                    .await
8930                    .map_err(|err| {
8931                        self.route_outages.operator_action_ended_unrefused(module_id);
8932                        format!(
8933                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8934                            configured_module.enabled
8935                        )
8936                    })?;
8937            }
8938        }
8939
8940        for module_id in &added {
8941            let configured_module = configured
8942                .get(module_id)
8943                .expect("added module id came from configured map");
8944            supervisor
8945                .supervise_configured_requested_async(
8946                    configured_module.module_spec(),
8947                    configured_module.enabled,
8948                    configured_module.health.clone(),
8949                    configured_module.drain_timeout_ms,
8950                    configured_module.restart,
8951                    configured_module.register_timeout,
8952                    Some(requester.clone()),
8953                )
8954                .await
8955                .map_err(|err| {
8956                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8957                })?;
8958        }
8959
8960        if let Some(context) = &self.rescan {
8961            let mut entries = context
8962                .module_entries
8963                .lock()
8964                .unwrap_or_else(|e| e.into_inner());
8965            entries.record(&configured, &added, &removed);
8966        }
8967
8968        Ok((
8969            SupervisorRescanResult {
8970                added,
8971                removed,
8972                changed_pending_reload,
8973                changed_pending,
8974                enabled_changes: enabled_changes.iter().cloned().collect(),
8975                unchanged,
8976                preview: false,
8977                // Filled by the caller, which is the only layer that can see the
8978                // previous config to diff against.
8979                restart_required: Vec::new(),
8980                capability_warnings: Vec::new(),
8981                module_actions: Vec::new(),
8982                earlier_pending: Vec::new(),
8983                expect: None,
8984            },
8985            changed,
8986        ))
8987    }
8988
8989    async fn handle_supervisor_set_enabled(
8990        &self,
8991        frame: Frame,
8992        module_id: String,
8993        enabled: bool,
8994        requester: Principal,
8995    ) -> Result<Vec<Frame>, RouterError> {
8996        let operation_lock = self.supervisor.operation_lock();
8997        let _operation_guard = operation_lock.lock().await;
8998        let Some(module) = self.supervisor.get(&module_id) else {
8999            return Ok(vec![control_error_frame(
9000                &frame,
9001                "unknown_module",
9002                format!("module_id '{module_id}' is not supervised"),
9003            )?]);
9004        };
9005
9006        // Enabling counts as well as disabling: a module an operator starts
9007        // is refused until it registers, and that wait was asked for.
9008        self.route_outages.mark_operator_action(&module_id);
9009        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
9010            Ok(applied) => applied,
9011            Err(err) => {
9012                self.route_outages
9013                    .operator_action_ended_unrefused(&module_id);
9014                return Ok(vec![control_error_frame(
9015                    &frame,
9016                    if err.is_config_gate_error() {
9017                        "config_gated"
9018                    } else {
9019                        "target_unavailable"
9020                    },
9021                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
9022                )?]);
9023            }
9024        };
9025        if !applied {
9026            // Already in the requested state: nothing was made unavailable,
9027            // so the mark must not outlive this request.
9028            self.route_outages
9029                .operator_action_ended_unrefused(&module_id);
9030        }
9031
9032        self.capability_evaluator.wake_deadline_loop();
9033        self.refresh_capability_requirements();
9034        let response = ClientControlResponse::SupervisorAck { module_id, applied };
9035        Ok(vec![control_response_body_frame(
9036            &frame,
9037            &response,
9038            "ClientControlResponse::SupervisorAck",
9039        )?])
9040    }
9041
9042    async fn handle_supervisor_health_probe(
9043        &self,
9044        ctx: &RouteCtx,
9045        frame: Frame,
9046        module_id: String,
9047    ) -> Result<Vec<Frame>, RouterError> {
9048        self.refresh_capability_requirements();
9049        let Some(registration) = self
9050            .registry
9051            .get_module(&module_id)
9052            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
9053        else {
9054            return Ok(vec![control_error_frame(
9055                &frame,
9056                "unknown_module",
9057                format!("module_id '{module_id}' is not registered"),
9058            )?]);
9059        };
9060
9061        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
9062        // named for it. Making `module_registration_grants_op` return false
9063        // unconditionally reddens five tests, and every one is named for something
9064        // else -- capability relay, probe/bind demultiplexing, supervision-only
9065        // probing. They exercise a successful advertisement check on the way to their
9066        // own subject.
9067        //
9068        // Real protection, fragile in a specific way: narrowing any of those tests to
9069        // focus on its stated subject would silently remove coverage nobody knows
9070        // they are carrying. Recorded here rather than as a sixth test, because the
9071        // useful fact is WHICH tests hold the guard up -- a new test would add
9072        // coverage without telling the next person what the existing ones quietly do.
9073        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
9074        {
9075            return Ok(vec![control_error_frame(
9076                &frame,
9077                "health_not_advertised",
9078                format!("module_id '{module_id}' did not advertise health.check"),
9079            )?]);
9080        }
9081
9082        self.observe_control_wait(
9083            ctx,
9084            Some(&registration.manifest.module_id),
9085            ops::SUPERVISOR_HEALTH_PROBE,
9086            async {
9087                let deadline = Instant::now() + self.health_probe_timeout;
9088                let pending = match self.forwarding.begin_module_control_rpc_for(
9089                    &module_id,
9090                    MODULE_CONTROL_OP_HEALTH_CHECK,
9091                    deadline,
9092                ) {
9093                    Ok(pending) => pending,
9094                    Err(err) => {
9095                        return Ok(vec![control_error_frame(
9096                            &frame,
9097                            forwarding_error_code(&err),
9098                            err.to_string(),
9099                        )?])
9100                    }
9101                };
9102
9103                let PendingModuleControlRpc {
9104                    endpoint,
9105                    module_sink,
9106                    negotiated_ver,
9107                    corr: probe_corr,
9108                    receiver,
9109                } = pending;
9110                let mut guard =
9111                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9112                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9113                    .map_err(|err| {
9114                        RouterError::backend(
9115                            0,
9116                            frame.header.corr,
9117                            format!("failed to encode health.check request: {err}"),
9118                        )
9119                    })?;
9120                let probe_frame = Frame::build_with_version(
9121                    negotiated_ver,
9122                    FrameType::Request,
9123                    control_flags(),
9124                    0,
9125                    0,
9126                    probe_corr,
9127                    probe_body,
9128                )
9129                .map_err(RouterError::FrameBuild)?;
9130
9131                // Queue admission and the reply share one deadline, so a module that
9132                // stops reading cannot park the requesting connection's reader forever.
9133                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9134                    Ok(Ok(())) => {}
9135                    Ok(Err(err)) => {
9136                        return Ok(vec![control_error_frame(
9137                            &frame,
9138                            "target_unavailable",
9139                            err.to_string(),
9140                        )?]);
9141                    }
9142                    Err(_) => {
9143                        return Ok(vec![control_error_frame(
9144                            &frame,
9145                            "module_timeout",
9146                            format!(
9147                                "module_id '{module_id}' did not answer health.check within {:?}",
9148                                self.health_probe_timeout
9149                            ),
9150                        )?]);
9151                    }
9152                }
9153
9154                match timeout_at(deadline, receiver).await {
9155                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9156                        Ok(vec![control_error_frame(
9157                            &frame,
9158                            "invalid_control_body",
9159                            "health.check returned an unexpected config response",
9160                        )?])
9161                    }
9162                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9163                        guard.disarm();
9164                        let Some(report) = response.health_report() else {
9165                            return Ok(vec![control_error_frame(
9166                                &frame,
9167                                "invalid_control_body",
9168                                "health.check RPC returned a non-health response",
9169                            )?]);
9170                        };
9171                        // Metrics go out whole here. The supervisor's cached snapshot
9172                        // caps this blob (see truncate_health_metrics), and this path
9173                        // exists precisely to answer without that cap -- so applying it
9174                        // here would leave no way to see what the cached view drops.
9175                        let HealthReport {
9176                            status,
9177                            detail,
9178                            metrics,
9179                        } = report;
9180                        let capability_detail = self
9181                            .capability_evaluator
9182                            .required_problem_detail(&module_id);
9183                        let response = ClientControlResponse::SupervisorHealthProbe {
9184                            module_id,
9185                            status,
9186                            detail: append_capability_problem_detail(detail, capability_detail),
9187                            metrics,
9188                        };
9189                        Ok(vec![control_response_body_frame(
9190                            &frame,
9191                            &response,
9192                            "ClientControlResponse::SupervisorHealthProbe",
9193                        )?])
9194                    }
9195                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9196                        guard.disarm();
9197                        // The module refused the health probe with its own body, so
9198                        // the refusal is relayed without the daemon-origin flag
9199                        // (bit 6): a client must not read it as the daemon's own
9200                        // refusal, which it may treat as never forwarded.
9201                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9202                    }
9203                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9204                        guard.disarm();
9205                        Ok(vec![control_error_frame(
9206                            &frame,
9207                            "target_unavailable",
9208                            message,
9209                        )?])
9210                    }
9211                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9212                        guard.disarm();
9213                        Ok(vec![control_error_frame(
9214                            &frame,
9215                            "invalid_control_body",
9216                            message,
9217                        )?])
9218                    }
9219                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9220                        guard.disarm();
9221                        Ok(vec![control_error_frame(
9222                            &frame,
9223                            "invalid_control_body",
9224                            format!("expected module-control op '{expected}', got '{actual}'"),
9225                        )?])
9226                    }
9227                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9228                        guard.disarm();
9229                        Ok(vec![control_error_frame(
9230                            &frame,
9231                            "module_timeout",
9232                            format!(
9233                                "module_id '{module_id}' answered health.check after {:?}",
9234                                self.health_probe_timeout
9235                            ),
9236                        )?])
9237                    }
9238                    Ok(Err(_)) => Ok(vec![control_error_frame(
9239                        &frame,
9240                        "target_unavailable",
9241                        "health.check waiter was canceled before the module responded",
9242                    )?]),
9243                    Err(_) => Ok(vec![control_error_frame(
9244                        &frame,
9245                        "module_timeout",
9246                        format!(
9247                            "module_id '{module_id}' did not answer health.check within {:?}",
9248                            self.health_probe_timeout
9249                        ),
9250                    )?]),
9251                }
9252            },
9253        )
9254        .await
9255    }
9256
9257    fn supervisor_status(
9258        &self,
9259        module_id: &str,
9260        corr: u64,
9261    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9262        self.supervisor
9263            .get(module_id)
9264            .map(|module| {
9265                let warming = module.is_warming_for_control("status").map_err(|err| {
9266                    RouterError::backend(
9267                        0,
9268                        corr,
9269                        format!(
9270                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9271                        ),
9272                    )
9273                })?;
9274                module.status_for_control("status").map_err(|err| {
9275                    RouterError::backend(
9276                        0,
9277                        corr,
9278                        format!(
9279                            "failed to read supervisor status for module_id '{module_id}': {err}"
9280                        ),
9281                    )
9282                }).map(|status| (status, warming))
9283            })
9284            .transpose()
9285    }
9286
9287    fn guard_module_control_op(
9288        &self,
9289        frame: &Frame,
9290        module_id: &str,
9291        op: &str,
9292    ) -> Result<Option<Frame>, RouterError> {
9293        if self.module_grants_op(module_id, op, frame.header.corr)? {
9294            return Ok(None);
9295        }
9296
9297        Ok(Some(control_error_frame(
9298            frame,
9299            "op_not_allowed",
9300            format!("module_id '{module_id}' did not grant control op '{op}'"),
9301        )?))
9302    }
9303
9304    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9305        self.registry
9306            .grants_control_op(module_id, op)
9307            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9308    }
9309
9310    fn handle_status_update(
9311        &self,
9312        endpoint: ModuleEndpointId,
9313        frame: Frame,
9314    ) -> Result<Vec<Frame>, RouterError> {
9315        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9316            Ok(update) => update,
9317            Err(err) => {
9318                // Forward-compat: a newer module may push a channel-0 op this subc
9319                // version doesn't know. The control contract says unknown push ops
9320                // are IGNORED, never answered with an error. Only a malformed body
9321                // for an op we DO know is a real error worth surfacing.
9322                if is_known_module_push_op(&frame.body) {
9323                    return Ok(vec![control_error_frame(
9324                        &frame,
9325                        "invalid_control_body",
9326                        format!("malformed module control push body: {err}"),
9327                    )?]);
9328                }
9329                return Ok(Vec::new());
9330            }
9331        };
9332
9333        match update {
9334            ModuleControlPush::RouteStatus {
9335                route_channel,
9336                route_epoch,
9337                status,
9338            } => {
9339                self.forwarding
9340                    .cache_status(endpoint, route_channel, route_epoch, status)
9341                    .map_err(RouterError::Forwarding)?;
9342            }
9343        }
9344        Ok(Vec::new())
9345    }
9346
9347    fn handle_route_poll(
9348        &self,
9349        ctx: &RouteCtx,
9350        frame: Frame,
9351        route_channel: u16,
9352        route_epoch: u32,
9353        kind: PollKind,
9354    ) -> Result<Vec<Frame>, RouterError> {
9355        let snapshot = self
9356            .forwarding
9357            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9358            .map_err(RouterError::Forwarding)?;
9359        let response = match (kind, snapshot) {
9360            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9361                ClientControlResponse::RoutePoll {
9362                    route_channel,
9363                    route_epoch,
9364                    status,
9365                    live: None,
9366                }
9367            }
9368            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9369                route_channel,
9370                route_epoch,
9371                status: None,
9372                live: None,
9373            },
9374            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9375                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9376                // is what makes reporting `true` correct rather than a
9377                // confident guess. `process_live` returns None only when the
9378                // module id has no supervisor snapshot at all -- an
9379                // externally-started module the daemon did not spawn -- and
9380                // for those the supervisor has no opinion to offer, ever. It
9381                // is never None for a supervised module in an unknown state:
9382                // a supervised module always has a snapshot, and the answer
9383                // comes from `state == Running && process_alive`.
9384                //
9385                // The route is Bound, so the module completed a HELLO on a
9386                // live connection; "the process this route points at is
9387                // running" is therefore attested by the binding rather than
9388                // assumed. Reporting `false` for an unsupervised module would
9389                // be the actual lie -- it would tell a client its healthy
9390                // route is dead because the daemon does not manage the
9391                // process.
9392                //
9393                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9394                // module whose liveness is genuinely unknown, e.g. a snapshot
9395                // that has not been populated yet -- THIS DEFAULT BECOMES
9396                // WRONG and must split: unsupervised stays true, unknown
9397                // becomes null so the client can tell the two apart. The
9398                // response field is already `Option<bool>`, so the wire can
9399                // carry that distinction today.
9400                let live = self
9401                    .process_liveness
9402                    .as_ref()
9403                    .and_then(|source| source.process_live(&module_id))
9404                    .unwrap_or(true);
9405                ClientControlResponse::RoutePoll {
9406                    route_channel,
9407                    route_epoch,
9408                    status: None,
9409                    live: Some(live),
9410                }
9411            }
9412            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9413                route_channel,
9414                route_epoch,
9415                status: None,
9416                live: Some(false),
9417            },
9418        };
9419
9420        Ok(vec![control_response_body_frame(
9421            &frame,
9422            &response,
9423            "ClientControlResponse::RoutePoll",
9424        )?])
9425    }
9426
9427    pub(crate) fn observe_module_control_completion(
9428        &self,
9429        completion: ModuleControlRpcCompletion,
9430    ) -> bool {
9431        match completion {
9432            ModuleControlRpcCompletion::Unknown => false,
9433            ModuleControlRpcCompletion::Settled => true,
9434            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9435                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9436                info!(
9437                    module_id = %module_id,
9438                    latency_ms,
9439                    "late health.check answer proves the module is alive"
9440                );
9441                match self
9442                    .supervisor
9443                    .record_late_health_answer(&module_id, latency_ms)
9444                {
9445                    Ok(true) => {}
9446                    Ok(false) => debug!(
9447                        module_id = %module_id,
9448                        latency_ms,
9449                        "late health.check answer has no active supervisor snapshot"
9450                    ),
9451                    Err(err) => warn!(
9452                        module_id = %module_id,
9453                        latency_ms,
9454                        error = %err,
9455                        "failed to record late health.check answer"
9456                    ),
9457                }
9458                true
9459            }
9460        }
9461    }
9462
9463    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9464    /// the module connection whose frame is being handled, or to the client that
9465    /// relay was opened for.
9466    ///
9467    /// This runs on the MODULE connection's frame handler, where returning `Err`
9468    /// ends that connection -- and a module connection carries every client's
9469    /// routes to that module, so ending it costs the whole fleet its tools.
9470    /// `ConnectionClosing` carries the id of the connection that is closing, and
9471    /// when that id is a CLIENT's, the condition is entirely about that one
9472    /// client's route.open. A client-scoped condition has no authority over a
9473    /// shared module connection, so it is logged and the single relay is dropped:
9474    /// the client is going away, and `complete_pending_relay` already removed the
9475    /// relay before failing, so there is nothing left to settle. Anything that
9476    /// relay still reserved is released by that client's own connection teardown,
9477    /// which is already under way -- that is what "closing" means.
9478    ///
9479    /// Every other failure is a statement about THIS connection and stays fatal:
9480    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9481    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9482    /// frames correctly.
9483    fn refuse_to_end_module_connection_for_a_client(
9484        &self,
9485        module_connection_id: ConnectionId,
9486        corr: u64,
9487        err: ForwardingError,
9488    ) -> Result<(), RouterError> {
9489        if let ForwardingError::ConnectionClosing { connection_id } = err {
9490            if connection_id != module_connection_id {
9491                warn!(
9492                    module_connection_id = module_connection_id.get(),
9493                    client_connection_id = connection_id.get(),
9494                    corr,
9495                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9496                );
9497                return Ok(());
9498            }
9499        }
9500        Err(RouterError::Forwarding(err))
9501    }
9502
9503    fn handle_module_relay_response(
9504        &self,
9505        connection_id: ConnectionId,
9506        frame: Frame,
9507    ) -> Result<Vec<Frame>, RouterError> {
9508        let mut secondary_error = None;
9509        let outcome = match frame.header.ty {
9510            FrameType::Response => match module_control_response_probe(&frame.body) {
9511                Ok(probe) if probe.op == "route.bind" => {
9512                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9513                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9514                            RouteBindRelayOutcome::Accepted
9515                        }
9516                        Ok(other) => {
9517                            let message =
9518                                format!("route.bind response carried unexpected body: {other:?}");
9519                            secondary_error = Some(control_error_frame(
9520                                &frame,
9521                                "invalid_control_body",
9522                                message.clone(),
9523                            )?);
9524                            RouteBindRelayOutcome::ModuleGone(message)
9525                        }
9526                        Err(err) => {
9527                            let message = format!("malformed route.bind response body: {err}");
9528                            secondary_error = Some(control_error_frame(
9529                                &frame,
9530                                "invalid_control_body",
9531                                message.clone(),
9532                            )?);
9533                            RouteBindRelayOutcome::ModuleGone(message)
9534                        }
9535                    }
9536                }
9537                Ok(probe) => {
9538                    let outcome = if matches!(
9539                        probe.op.as_str(),
9540                        "config.review" | "consent/v1" | "projects.enumerate"
9541                    ) {
9542                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9543                    } else {
9544                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9545                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9546                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9547                                "malformed {} response body: {err}",
9548                                probe.op
9549                            )),
9550                        }
9551                    };
9552                    let completion = self
9553                        .forwarding
9554                        .complete_module_control_rpc(
9555                            connection_id,
9556                            frame.header.corr,
9557                            Some(&probe.op),
9558                            outcome,
9559                        )
9560                        .map_err(RouterError::Forwarding)?;
9561                    if !self.observe_module_control_completion(completion) {
9562                        debug!(
9563                            connection_id = connection_id.get(),
9564                            corr = frame.header.corr,
9565                            op = %probe.op,
9566                            "dropping late or unknown module-control RPC response"
9567                        );
9568                    }
9569                    return Ok(Vec::new());
9570                }
9571                Err(err) => {
9572                    if let Some(expected_op) = self
9573                        .forwarding
9574                        .pending_module_control_op(connection_id, frame.header.corr)
9575                        .map_err(RouterError::Forwarding)?
9576                    {
9577                        let completion = self
9578                            .forwarding
9579                            .complete_module_control_rpc(
9580                                connection_id,
9581                                frame.header.corr,
9582                                None,
9583                                ModuleControlRpcOutcome::MalformedResponse(format!(
9584                                    "malformed {expected_op} response body: {err}"
9585                                )),
9586                            )
9587                            .map_err(RouterError::Forwarding)?;
9588                        if !self.observe_module_control_completion(completion) {
9589                            debug!(
9590                                connection_id = connection_id.get(),
9591                                corr = frame.header.corr,
9592                                "dropping late malformed module-control RPC response"
9593                            );
9594                        }
9595                        return Ok(Vec::new());
9596                    }
9597                    let message = format!("malformed route.bind response body: {err}");
9598                    secondary_error = Some(control_error_frame(
9599                        &frame,
9600                        "invalid_control_body",
9601                        message.clone(),
9602                    )?);
9603                    RouteBindRelayOutcome::ModuleGone(message)
9604                }
9605            },
9606            FrameType::Error => {
9607                if self
9608                    .forwarding
9609                    .pending_module_control_op(connection_id, frame.header.corr)
9610                    .map_err(RouterError::Forwarding)?
9611                    .is_some()
9612                {
9613                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9614                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9615                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9616                            "malformed module-control ERROR body: {err}"
9617                        )),
9618                    };
9619                    let completion = self
9620                        .forwarding
9621                        .complete_module_control_rpc(
9622                            connection_id,
9623                            frame.header.corr,
9624                            None,
9625                            outcome,
9626                        )
9627                        .map_err(RouterError::Forwarding)?;
9628                    if !self.observe_module_control_completion(completion) {
9629                        debug!(
9630                            connection_id = connection_id.get(),
9631                            corr = frame.header.corr,
9632                            "dropping late or unknown module-control RPC error"
9633                        );
9634                    }
9635                    return Ok(Vec::new());
9636                }
9637                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9638                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9639                    Err(err) => {
9640                        let message = format!("malformed route.bind ERROR body: {err}");
9641                        secondary_error = Some(control_error_frame(
9642                            &frame,
9643                            "invalid_control_body",
9644                            message.clone(),
9645                        )?);
9646                        RouteBindRelayOutcome::ModuleGone(message)
9647                    }
9648                }
9649            }
9650            ty => {
9651                return Ok(vec![control_error_frame(
9652                    &frame,
9653                    "unsupported_control_frame",
9654                    format!("unsupported module channel-0 frame {ty:?}"),
9655                )?])
9656            }
9657        };
9658
9659        let settled =
9660            self.forwarding
9661                .complete_pending_relay(connection_id, frame.header.corr, outcome);
9662        let completion = match settled {
9663            Ok(completion) => completion,
9664            Err(err) => {
9665                self.refuse_to_end_module_connection_for_a_client(
9666                    connection_id,
9667                    frame.header.corr,
9668                    err,
9669                )?;
9670                return Ok(secondary_error.into_iter().collect());
9671            }
9672        };
9673        if let Some(target) = completion.abandoned.as_ref() {
9674            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9675        }
9676        if !completion.settled {
9677            debug!(
9678                connection_id = connection_id.get(),
9679                corr = frame.header.corr,
9680                frame_type = ?frame.header.ty,
9681                "dropping late or unknown route.bind relay response"
9682            );
9683        }
9684        Ok(secondary_error.into_iter().collect())
9685    }
9686
9687    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9688        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9689        // GOODBYE ends the connection's logical session even when its socket
9690        // stays open. Use disconnect teardown so verdicts, client notices and
9691        // scope authority are released at the same lifecycle boundary.
9692        self.cleanup_connection_with_end_reason(
9693            connection_id,
9694            RegistrationEndReason::ExplicitGoodbye,
9695        )
9696        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9697        Ok(Vec::new())
9698    }
9699}
9700
9701impl Default for ControlHandler {
9702    fn default() -> Self {
9703        Self::new(Arc::new(Registry::default()))
9704    }
9705}
9706
9707impl crate::supervise::SwapPromotionObserver for ControlHandler {
9708    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9709        self.apply_registration_capabilities(registration);
9710    }
9711}
9712
9713fn append_capability_problem_detail(
9714    detail: Option<String>,
9715    capability_detail: Option<String>,
9716) -> Option<String> {
9717    match (detail, capability_detail) {
9718        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9719        (Some(detail), None) => Some(detail),
9720        (None, Some(capability_detail)) => Some(capability_detail),
9721        (None, None) => None,
9722    }
9723}
9724
9725fn subc_ops() -> Vec<String> {
9726    SUBC_CONTROL_OPS
9727        .iter()
9728        .map(|op| (*op).to_string())
9729        .collect()
9730}
9731
9732fn module_subc_ops() -> Vec<String> {
9733    SUBC_CONTROL_OPS
9734        .iter()
9735        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9736        .map(|op| (*op).to_string())
9737        .collect()
9738}
9739
9740#[cfg(test)]
9741fn module_baseline_control_ops() -> Vec<String> {
9742    MODULE_BASELINE_CONTROL_OPS
9743        .iter()
9744        .map(|op| (*op).to_string())
9745        .collect()
9746}
9747
9748fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9749    let mut seen = HashSet::new();
9750    let mut effective = Vec::new();
9751    for op in MODULE_BASELINE_CONTROL_OPS {
9752        if seen.insert((*op).to_string()) {
9753            effective.push((*op).to_string());
9754        }
9755    }
9756    for op in declared.unwrap_or_default() {
9757        if seen.insert(op.clone()) {
9758            effective.push(op);
9759        }
9760    }
9761    effective
9762}
9763
9764fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9765    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9766}
9767
9768fn target_module_id(target: &RouteTarget) -> &str {
9769    match target {
9770        RouteTarget::ToolProvider { module_id }
9771        | RouteTarget::ManagementSurface { module_id }
9772        | RouteTarget::InternalService { module_id, .. } => module_id,
9773    }
9774}
9775
9776fn target_has_required_role(
9777    target: &RouteTarget,
9778    roles: &[crate::registry::AdmissionRole],
9779) -> bool {
9780    use crate::registry::AdmissionRole;
9781    roles.iter().any(|role| match (target, role) {
9782        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9783        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9784        (
9785            RouteTarget::InternalService { service_id, .. },
9786            AdmissionRole::InternalService(provided),
9787        ) => service_id == provided,
9788        _ => false,
9789    })
9790}
9791
9792fn is_routable_role(role: &ProviderRole) -> bool {
9793    matches!(
9794        role,
9795        ProviderRole::ToolProvider { .. }
9796            | ProviderRole::ManagementSurface { .. }
9797            | ProviderRole::InternalService { .. }
9798    )
9799}
9800
9801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9802enum ControlRequestBodyError {
9803    UnknownOp,
9804    InvalidBody,
9805}
9806
9807#[derive(Debug, Deserialize)]
9808struct ControlOpProbe {
9809    op: String,
9810}
9811
9812fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9813    serde_json::from_slice(body).or_else(|original| {
9814        #[derive(Deserialize)]
9815        struct ConsentProbe {
9816            protocol: String,
9817        }
9818        match serde_json::from_slice::<ConsentProbe>(body) {
9819            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9820                Ok(ControlOpProbe { op: probe.protocol })
9821            }
9822            _ => Err(original),
9823        }
9824    })
9825}
9826
9827/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9828/// this set is treated as a forward-compat unknown and ignored rather than errored.
9829const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9830
9831fn is_known_module_push_op(body: &[u8]) -> bool {
9832    serde_json::from_slice::<ControlOpProbe>(body)
9833        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9834        .unwrap_or(false)
9835}
9836
9837fn is_known_module_request_op(body: &[u8]) -> bool {
9838    serde_json::from_slice::<ControlOpProbe>(body)
9839        .map(|probe| is_module_to_subc_op(&probe.op))
9840        .unwrap_or(false)
9841}
9842
9843fn is_module_to_subc_op(op: &str) -> bool {
9844    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9845}
9846
9847fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9848    debug!(
9849        op = %op,
9850        connection_id = connection_id.get(),
9851        corr,
9852        "control dispatch"
9853    );
9854}
9855
9856fn log_slow_control_dispatch(
9857    dispatch_started_at: Option<StdInstant>,
9858    op: &'static str,
9859    connection_id: ConnectionId,
9860    corr: u64,
9861    route_open_timings: Option<&RouteOpenTimings>,
9862) {
9863    let Some(dispatch_started_at) = dispatch_started_at else {
9864        return;
9865    };
9866    // Use the same monotonic clock as the phase timers and relay deadline.
9867    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9868    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9869        if let Some(timings) = route_open_timings {
9870            warn!(
9871                op = %op,
9872                connection_id = connection_id.get(),
9873                corr,
9874                elapsed_ms = elapsed.as_millis() as u64,
9875                module_id = ?timings.module_id,
9876                principal = %timings.principal,
9877                admission_ms = timings.admission.as_millis() as u64,
9878                project_root_ms = timings.project_root.as_millis() as u64,
9879                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9880                bind_send_ms = timings.bind_send.as_millis() as u64,
9881                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9882                "slow control dispatch"
9883            );
9884            return;
9885        }
9886        warn!(
9887            op = %op,
9888            connection_id = connection_id.get(),
9889            corr,
9890            elapsed_ms = elapsed.as_millis() as u64,
9891            "slow control dispatch"
9892        );
9893    }
9894}
9895
9896/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9897#[cfg(test)]
9898type TestCallerLookup =
9899    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9900
9901/// Every new client operation needs an explicit privilege decision here.
9902fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9903    request.privileged_operation()
9904}
9905
9906trait PrivilegedRequest {
9907    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9908}
9909
9910impl PrivilegedRequest for ClientControlRequest {
9911    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9912        let request = self;
9913        match request {
9914        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9915            Some(PrivilegedOperation::Restart { module_id })
9916        }
9917        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9918            Some(PrivilegedOperation::Swap { module_id })
9919        }
9920        ClientControlRequest::SupervisorReload { module_id } => {
9921            Some(PrivilegedOperation::Reload { module_id })
9922        }
9923        ClientControlRequest::SupervisorRescan { preview } => {
9924            if *preview {
9925                None
9926            } else {
9927                Some(PrivilegedOperation::Rescan)
9928            }
9929        }
9930        // Only the well-formed apply asks for approval. A preview changes
9931        // nothing, and any other combination is refused before it touches
9932        // anything, so prompting the operator for it would ask about a request
9933        // that cannot run.
9934        ClientControlRequest::SupervisorRescanChecked {
9935            preview,
9936            candidate,
9937            expect,
9938        } => (!*preview && candidate.is_none() && expect.is_some())
9939            .then_some(PrivilegedOperation::Rescan),
9940        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9941            Some(PrivilegedOperation::SetEnabled {
9942                module_id,
9943                enabled: *enabled,
9944            })
9945        }
9946        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9947            Some(PrivilegedOperation::ReleaseReserved { module_id })
9948        }
9949        ClientControlRequest::ServerDescribe {}
9950        // The announcement uses the same client admission as supervisor.restart,
9951        // but cannot stop anything itself and needs no operator confirmation.
9952        | ClientControlRequest::DaemonShutdownIntent { .. }
9953        | ClientControlRequest::CatalogList { .. }
9954        | ClientControlRequest::RouteOpen { .. }
9955        | ClientControlRequest::RoutePoll { .. }
9956        | ClientControlRequest::SupervisorList {}
9957        | ClientControlRequest::SupervisorHealth {}
9958        | ClientControlRequest::SupervisorHealthProbe { .. }
9959        | ClientControlRequest::SupervisorRoutes { .. }
9960        | ClientControlRequest::SupervisorProvenance { .. }
9961        | ClientControlRequest::SupervisorStderrTail { .. }
9962        | ClientControlRequest::SupervisorTerminals { .. }
9963        | ClientControlRequest::SupervisorSpawnSnapshot {}
9964        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9965    }
9966    }
9967}
9968
9969fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9970    match request {
9971        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9972        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9973        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
9974        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
9975        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
9976        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
9977        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
9978        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
9979        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
9980        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
9981        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
9982        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
9983        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
9984        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
9985        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
9986        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
9987        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
9988        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
9989        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
9990        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
9991        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
9992    }
9993}
9994
9995/// The caller of one `route.open`, as its `route.open refused` line names it.
9996///
9997/// A connection id alone cannot name a caller after the fact: ids restart at
9998/// every daemon restart, so the same number belongs to different modules
9999/// before and after one. These three fields are what the refused line needs
10000/// to be attributable on its own, and they are rendered with the same helpers
10001/// as the `route.open accepted` line so both directions grep alike.
10002struct RouteOpenCaller {
10003    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
10004    /// when the request presented a consumer identity whose launch nonce did
10005    /// not verify. The claimed module id is never printed as a principal.
10006    principal: String,
10007    /// `none` for an unscoped open; the admitted stamp's label once scope
10008    /// admission issued one; before that, the requested selector's label.
10009    scope: String,
10010    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
10011    /// because it is a string the caller chose.
10012    harness: String,
10013}
10014
10015impl RouteOpenCaller {
10016    fn new(
10017        principal: Option<&Principal>,
10018        scope: Option<&ScopeSelector>,
10019        identity: &BindIdentity,
10020    ) -> Self {
10021        Self {
10022            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
10023            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
10024            harness: bounded_log_text(&identity.harness),
10025        }
10026    }
10027
10028    /// For a refusal that has no parsed request at hand: names whatever the
10029    /// frame still says, and `unknown` where it says nothing parseable.
10030    fn unknown() -> Self {
10031        Self {
10032            principal: "unknown".to_string(),
10033            scope: "unknown".to_string(),
10034            harness: "unknown".to_string(),
10035        }
10036    }
10037}
10038
10039/// Longest client-chosen text (a scope ref, a harness) a route.open log line
10040/// prints before cutting it.
10041const MAX_LOGGED_TEXT_CHARS: usize = 64;
10042
10043/// `value` Debug-quoted, so control characters land escaped and cannot forge
10044/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
10045/// `…` inside the quotes so one request cannot flood the line.
10046fn bounded_log_text(value: &str) -> String {
10047    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
10048    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
10049        bounded.push('…');
10050    }
10051    format!("{bounded:?}")
10052}
10053
10054/// The `scope=` field of the `route.open accepted` line, from the stamp that
10055/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
10056/// so a ref holding control characters cannot forge a log line, and cut to 64
10057/// characters with a trailing `…` to bound the line. The bind proof and the
10058/// scope's attributes never appear.
10059fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
10060    use subc_protocol::scope::ScopeKind;
10061    let kind = match stamp.kind {
10062        ScopeKind::Head => "head",
10063        ScopeKind::Worker => "worker",
10064        ScopeKind::Ephemeral => "ephemeral",
10065        ScopeKind::Federated => "federated",
10066        _ => "unknown",
10067    };
10068    format!(
10069        "{kind}/{}/{}@{}",
10070        principal_label(&stamp.owner),
10071        bounded_log_text(&stamp.scope_ref),
10072        stamp.scope_epoch
10073    )
10074}
10075
10076/// The `scope=` field of a `route.open refused` line for an open refused
10077/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
10078/// The kind is not known yet, so the literal `requested` stands in its place.
10079/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
10080/// owner it has not been checked against the configured modules: a quoted
10081/// owner means the value was never validated. The bind proof never appears.
10082fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10083    let epoch = selector
10084        .scope_epoch
10085        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10086    format!(
10087        "requested/{}/{}@{epoch}",
10088        bounded_log_text(&principal_label(&selector.owner)),
10089        bounded_log_text(&selector.scope_ref),
10090    )
10091}
10092
10093fn principal_label(principal: &Principal) -> String {
10094    match principal {
10095        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10096        Principal::Direct => "direct".to_string(),
10097        other => format!("{other:?}"),
10098    }
10099}
10100
10101fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10102    match request {
10103        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10104        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10105            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10106        }
10107        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10108        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10109        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10110        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10111        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10112            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10113        }
10114        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10115        _ => "unsupported",
10116    }
10117}
10118
10119fn parse_client_control_request(
10120    body: &[u8],
10121) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10122    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10123        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10124            Ok(probe)
10125                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10126                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10127            {
10128                ControlRequestBodyError::InvalidBody
10129            }
10130            Ok(_) => ControlRequestBodyError::UnknownOp,
10131            Err(_) => ControlRequestBodyError::InvalidBody,
10132        };
10133        (err, classification)
10134    })
10135}
10136
10137fn parse_module_control_request_from_module(
10138    body: &[u8],
10139) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10140    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10141        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10142            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10143            Ok(_) => ControlRequestBodyError::UnknownOp,
10144            Err(_) => ControlRequestBodyError::InvalidBody,
10145        };
10146        (err, classification)
10147    })
10148}
10149
10150#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10151enum ProviderRoleKind {
10152    ToolProvider,
10153    PipelineStage,
10154    ManagementSurface,
10155    InternalService,
10156}
10157
10158fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10159    match role {
10160        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10161        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10162        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10163        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10164    }
10165}
10166
10167fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10168    roles.iter().map(provider_role_kind).collect()
10169}
10170
10171/// Most refused scope records named individually in the log per sync; the
10172/// `refused` count on the accepted line is always complete.
10173const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10174
10175/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10176#[derive(Debug, Default, PartialEq, Eq)]
10177struct ScopeOutcomeCounts {
10178    created: usize,
10179    replaced: usize,
10180    updated: usize,
10181    unchanged: usize,
10182    refused: usize,
10183}
10184
10185impl ScopeOutcomeCounts {
10186    fn of(results: &[ScopeRecordResult]) -> Self {
10187        let mut counts = Self::default();
10188        for result in results {
10189            let slot = match result.outcome {
10190                ScopeRecordOutcome::Created => &mut counts.created,
10191                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10192                ScopeRecordOutcome::Updated => &mut counts.updated,
10193                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10194                ScopeRecordOutcome::Refused => &mut counts.refused,
10195            };
10196            *slot += 1;
10197        }
10198        counts
10199    }
10200}
10201
10202#[cfg(test)]
10203mod scope_outcome_count_tests {
10204    use super::*;
10205
10206    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10207        ScopeRecordResult {
10208            scope_ref: "r".to_string(),
10209            scope_epoch: 1,
10210            outcome,
10211            code: None,
10212            message: None,
10213            version: None,
10214            parent_state: None,
10215        }
10216    }
10217
10218    /// Each outcome lands in its own count, so a refused record can never be
10219    /// hidden inside the total the log already printed.
10220    #[test]
10221    fn every_outcome_is_counted_in_its_own_field() {
10222        let results = [
10223            result(ScopeRecordOutcome::Created),
10224            result(ScopeRecordOutcome::Created),
10225            result(ScopeRecordOutcome::Replaced),
10226            result(ScopeRecordOutcome::Updated),
10227            result(ScopeRecordOutcome::Unchanged),
10228            result(ScopeRecordOutcome::Refused),
10229            result(ScopeRecordOutcome::Refused),
10230            result(ScopeRecordOutcome::Refused),
10231        ];
10232        assert_eq!(
10233            ScopeOutcomeCounts::of(&results),
10234            ScopeOutcomeCounts {
10235                created: 2,
10236                replaced: 1,
10237                updated: 1,
10238                unchanged: 1,
10239                refused: 3,
10240            }
10241        );
10242    }
10243}
10244
10245/// Return whether a catalog change can create a newly violating live route.
10246/// Removing an attested claim is intentionally excluded: it makes fewer routes
10247/// forbidden and therefore must leave the existing route census untouched.
10248fn capability_census_trigger(
10249    old: Option<&CapabilityDeclarations>,
10250    new: Option<&CapabilityDeclarations>,
10251) -> bool {
10252    let old_provides = old
10253        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10254        .unwrap_or_default();
10255    let old_denies = old
10256        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10257        .unwrap_or_default();
10258    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10259        provides: Vec::new(),
10260        requires: Vec::new(),
10261        must_never_reach: Vec::new(),
10262    });
10263
10264    new.provides
10265        .iter()
10266        .any(|capability| !old_provides.contains(capability))
10267        || new
10268            .must_never_reach
10269            .iter()
10270            .any(|capability| !old_denies.contains(capability))
10271}
10272
10273fn catalog_update_frozen_field_message(
10274    registered: &ModuleManifest,
10275    provides: &[ProviderRole],
10276) -> Option<String> {
10277    let old_has_provides = !registered.provides.is_empty();
10278    let new_has_provides = !provides.is_empty();
10279    if old_has_provides != new_has_provides {
10280        return Some(format!(
10281            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10282            registered.module_id
10283        ));
10284    }
10285
10286    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10287        return Some(format!(
10288            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10289            registered.module_id
10290        ));
10291    }
10292
10293    let registered_concurrency = manifest_concurrency(registered);
10294    let mut candidate = registered.clone();
10295    candidate.provides = provides.to_vec();
10296    let candidate_concurrency = manifest_concurrency(&candidate);
10297    if candidate_concurrency != registered_concurrency {
10298        return Some(format!(
10299            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10300            registered.module_id, registered_concurrency, candidate_concurrency
10301        ));
10302    }
10303
10304    // control_ops live beside the manifest in the HELLO body, not inside
10305    // ModuleManifest, so a provides-only catalog.update cannot change them.
10306    None
10307}
10308
10309fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10310    manifest.provides.iter().any(is_routable_role)
10311}
10312
10313/// Returns the routable-provider concurrency subc should enforce for this manifest.
10314///
10315/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10316/// InternalService has no role-specific concurrency field, so it retains the
10317/// existing ModuleManaged default for backward compatibility.
10318fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10319    manifest
10320        .provides
10321        .iter()
10322        .find_map(|provider| match provider {
10323            ProviderRole::ToolProvider { concurrency, .. }
10324            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10325            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10326        })
10327        .unwrap_or(Concurrency::ModuleManaged)
10328}
10329
10330/// True when the manifest carries a ManagementSurface role whose concurrency
10331/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10332/// bytes because the typed manifest deliberately erases that distinction: the
10333/// default exists for wire compatibility, and this probe exists so the default
10334/// stays observable. Any parse irregularity returns false -- the caller only
10335/// logs, and a malformed body already failed registration upstream.
10336fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10337    let has_management_surface = manifest
10338        .provides
10339        .iter()
10340        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10341    if !has_management_surface {
10342        return false;
10343    }
10344    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10345        return false;
10346    };
10347    let Some(provides) = raw
10348        .get("manifest")
10349        .and_then(|manifest| manifest.get("provides"))
10350        .and_then(serde_json::Value::as_array)
10351    else {
10352        return false;
10353    };
10354    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10355    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10356    // against the management_surface_manifest_without_concurrency golden, not
10357    // recalled (the externally-tagged guess was this function's first bug).
10358    provides.iter().any(|role| {
10359        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10360            && role.get("concurrency").is_none()
10361    })
10362}
10363
10364fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10365    if peer_version != PROTOCOL_VERSION {
10366        return Err(format!(
10367            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10368        ));
10369    }
10370    Ok(PROTOCOL_VERSION)
10371}
10372
10373fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10374    Frame::build_with_version(
10375        response_version(frame),
10376        FrameType::Pong,
10377        frame.header.flags,
10378        0,
10379        0,
10380        frame.header.corr,
10381        Vec::new(),
10382    )
10383    .map_err(RouterError::FrameBuild)
10384}
10385
10386pub(crate) fn control_error_frame(
10387    frame: &Frame,
10388    code: &'static str,
10389    message: impl Into<String>,
10390) -> Result<Frame, RouterError> {
10391    control_error_body_frame(
10392        frame,
10393        ErrorBody {
10394            code: code.to_string(),
10395            message: message.into(),
10396            detail: None,
10397        },
10398    )
10399}
10400
10401/// A channel-0 ERROR for a refusal the daemon decided itself: every
10402/// route.open refusal, the drain `module_reloading` and scope-change/end
10403/// bodies, spawn-subscription and supervisor refusals. Carries the
10404/// daemon-origin bit, which is what lets a client treat `module_reloading`
10405/// as proof that its request never reached a module. Response, push,
10406/// goodbye and relay-request frames keep the plain control flags in their
10407/// own builders.
10408pub(crate) fn control_error_body_frame(
10409    frame: &Frame,
10410    error: ErrorBody,
10411) -> Result<Frame, RouterError> {
10412    control_error_frame_with_flags(frame, error, daemon_error_flags())
10413}
10414
10415/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10416/// refused route.bind answered as a route.open refusal, or a refused
10417/// module-control RPC. Plain control flags — the code and message are
10418/// module-chosen, so the frame must not claim daemon authorship, even when
10419/// the module picks a daemon code like `module_reloading`.
10420fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10421    control_error_frame_with_flags(frame, error, control_flags())
10422}
10423
10424fn control_error_frame_with_flags(
10425    frame: &Frame,
10426    error: ErrorBody,
10427    flags: Flags,
10428) -> Result<Frame, RouterError> {
10429    let body = serde_json::to_vec(&error).map_err(|err| {
10430        RouterError::backend(
10431            0,
10432            frame.header.corr,
10433            format!("failed to encode control ERROR: {err}"),
10434        )
10435    })?;
10436
10437    Frame::build_with_version(
10438        response_version(frame),
10439        FrameType::Error,
10440        flags,
10441        0,
10442        0,
10443        frame.header.corr,
10444        body,
10445    )
10446    .map_err(RouterError::FrameBuild)
10447}
10448
10449pub(crate) fn control_response_body_frame<T: Serialize>(
10450    frame: &Frame,
10451    reply: &T,
10452    label: &'static str,
10453) -> Result<Frame, RouterError> {
10454    let body = serde_json::to_vec(reply).map_err(|err| {
10455        RouterError::backend(
10456            0,
10457            frame.header.corr,
10458            format!("failed to encode {label}: {err}"),
10459        )
10460    })?;
10461
10462    Frame::build_with_version(
10463        response_version(frame),
10464        FrameType::Response,
10465        control_flags(),
10466        0,
10467        0,
10468        frame.header.corr,
10469        body,
10470    )
10471    .map_err(RouterError::FrameBuild)
10472}
10473
10474/// Map a forwarding failure to the wire code a client sees.
10475///
10476/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10477/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10478/// chosen here decides whether a caller retries or gives up.
10479///
10480/// That makes attribution the load-bearing property, not merely having a code. A
10481/// permanent fault published as a retryable one produces a fleet-wide retry storm
10482/// against something that can never recover; a transient fault published as
10483/// permanent gives up on work that would have succeeded. Both look correct in a
10484/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10485/// the mapping per variant rather than merely asserting that some code exists.
10486///
10487/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10488/// two codes on the same side of the boundary passes it. Measured rather than
10489/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10490/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10491/// a test named for something else that happens to assert the string.
10492///
10493/// That accidental coverage is deliberately left alone rather than promoted to a
10494/// named test, because it guards a property this function does not promise.
10495/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10496/// specific code within a class, so identity is free to change and only the
10497/// partition is a contract. Splitting it out would assert a guarantee nothing
10498/// depends on — and a suite that promises more than the code does is the harder
10499/// thing to correct later, because the next reader cannot tell which assertions
10500/// are load-bearing.
10501///
10502/// Pin identity here the moment a consumer branches on a specific code.
10503/// The spawn a HELLO would register as and the provider declarations it
10504/// requests, carried from the HELLO's checks to the point the registry
10505/// accepts it.
10506struct HelloAuthority {
10507    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10508    requested: ProviderDeclarations,
10509    /// Whether admitting this HELLO froze the spawn's requested declarations,
10510    /// so a refusal after admission undoes that freeze and no other.
10511    froze: std::sync::atomic::AtomicBool,
10512}
10513
10514fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10515    match err {
10516        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10517        ForwardingError::NoModuleConnection => "target_unavailable",
10518        ForwardingError::ModuleReloading { .. } => "module_reloading",
10519        ForwardingError::ClientRouteChannelExhausted { .. }
10520        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10521        ForwardingError::StaleModuleEndpoint
10522        | ForwardingError::UnknownReservation { .. }
10523        | ForwardingError::ConnectionClosing { .. }
10524        | ForwardingError::ClientEgressClosed { .. }
10525        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10526        // Only a swap candidate's registration can produce this, and it means
10527        // exactly what a second active HELLO for a live id means.
10528        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10529        ForwardingError::RelayCorrelationExhausted
10530        | ForwardingError::RouteOpenBuild(_)
10531        | ForwardingError::Poisoned => "forwarding_error",
10532    }
10533}
10534
10535fn response_version(frame: &Frame) -> u8 {
10536    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10537        frame.header.ver
10538    } else {
10539        PROTOCOL_VERSION
10540    }
10541}
10542
10543pub(crate) fn control_flags() -> Flags {
10544    Flags::new(false, Priority::Passive, false)
10545}
10546
10547/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10548/// channel. The target is the module (a client never saw the route), so this
10549/// takes the module path: delivered late rather than dropped when the module's
10550/// queue is momentarily full, and never closing its connection.
10551fn send_goodbye_target_best_effort(
10552    counters: &DaemonCounters,
10553    target: &GoodbyeTarget,
10554    context: &'static str,
10555) {
10556    let Ok(frame) = Frame::build_with_version(
10557        target.negotiated_ver,
10558        FrameType::Goodbye,
10559        control_flags(),
10560        target.channel,
10561        target.epoch,
10562        0,
10563        Vec::new(),
10564    ) else {
10565        return;
10566    };
10567    crate::forwarding::send_module_route_goodbye(
10568        counters,
10569        &target.sink,
10570        frame,
10571        target.module_id.as_deref(),
10572        context,
10573    );
10574}
10575
10576fn route_close_reason_for_opener(
10577    reason: RouteCloseReason,
10578    accepts_close_reasons: Option<&[String]>,
10579) -> RouteCloseReason {
10580    if reason == RouteCloseReason::AuthorityChanged
10581        && !accepts_close_reasons
10582            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10583    {
10584        // Older readers forbid reopening for unknown reasons. Reload already
10585        // permits reopening and, like an authority change, requires a new bind.
10586        RouteCloseReason::Reload
10587    } else {
10588        reason
10589    }
10590}
10591
10592pub(crate) fn send_route_control_pushes(
10593    forwarding: &ForwardingTable,
10594    routes: Vec<EndpointRoute>,
10595    push: ClientControlPush,
10596) {
10597    let reason = match &push {
10598        ClientControlPush::RouteClosing { reason, .. }
10599        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10600    };
10601    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10602    for route in routes {
10603        let recipient_reason =
10604            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10605        let target = route.goodbye_target;
10606        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10607            existing.connection_id == target.connection_id && *reason == recipient_reason
10608        }) {
10609            debug_assert_eq!(
10610                existing.negotiated_ver, target.negotiated_ver,
10611                "one connection cannot negotiate multiple frame versions"
10612            );
10613            if !channels.contains(&target.channel) {
10614                channels.push(target.channel);
10615            }
10616            continue;
10617        }
10618        let channel = target.channel;
10619        targets.push((target, recipient_reason, vec![channel]));
10620    }
10621    for (target, recipient_reason, mut channels) in targets {
10622        channels.sort_unstable();
10623        let mut push = push.clone();
10624        match &mut push {
10625            ClientControlPush::RouteClosing {
10626                channels: covered,
10627                reason,
10628                ..
10629            }
10630            | ClientControlPush::RouteClosed {
10631                channels: covered,
10632                reason,
10633                ..
10634            } => {
10635                *covered = channels;
10636                *reason = recipient_reason;
10637            }
10638        }
10639        let body = match serde_json::to_vec(&push) {
10640            Ok(body) => body,
10641            Err(err) => {
10642                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10643                continue;
10644            }
10645        };
10646        let frame = match Frame::build_with_version(
10647            target.negotiated_ver,
10648            FrameType::Push,
10649            control_flags(),
10650            0,
10651            0,
10652            0,
10653            body.clone(),
10654        ) {
10655            Ok(frame) => frame,
10656            Err(err) => {
10657                warn!(
10658                    route_channel = target.channel,
10659                    error = %err,
10660                    "failed to build route lifecycle control PUSH frame"
10661                );
10662                continue;
10663            }
10664        };
10665        if let Err(err) = target.sink.try_send(frame) {
10666            if target.close_on_delivery_failure() {
10667                warn!(
10668                    target_connection_id = target.connection_id.get(),
10669                    route_channel = target.channel,
10670                    error = %err,
10671                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10672                );
10673                let _ = forwarding.escalate_client_delivery_failure(
10674                    target.connection_id,
10675                    target.channel,
10676                    target.epoch,
10677                    CloseReason::new(
10678                        "route_lifecycle_push_delivery_failed",
10679                        format!(
10680                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10681                            target.channel
10682                        ),
10683                    ),
10684                    crate::forwarding::UndeliveredFrame {
10685                        module_id: target.module_id.as_deref(),
10686                        sink: &target.sink,
10687                    },
10688                );
10689            }
10690        }
10691    }
10692}
10693
10694#[cfg(test)]
10695mod tests {
10696    include!("control/agent_commands_tests.rs");
10697    include!("control/supervisor_health_vectors_tests.rs");
10698    include!("control/resource_revision_tests.rs");
10699    include!("control/route_open_recovery_tests.rs");
10700    #[tokio::test]
10701    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10702        let registry = Arc::new(Registry::default());
10703        let handler = ControlHandler::new(registry);
10704        assert_eq!(
10705            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10706            None
10707        );
10708        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10709        hello_via_sink(
10710            &handler,
10711            &ctx,
10712            &mut rx,
10713            hello_frame("daemon", PROTOCOL_VERSION, 1),
10714        )
10715        .await;
10716        assert_eq!(
10717            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10718            Some("daemon".into())
10719        );
10720        assert_eq!(
10721            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10722            None
10723        );
10724        assert_eq!(
10725            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10726            None,
10727            "a registered module is not necessarily supervised"
10728        );
10729        assert_eq!(
10730            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10731            None,
10732            "aggregate provenance has no single target"
10733        );
10734        assert_eq!(
10735            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10736            None
10737        );
10738    }
10739
10740    mod peer_manifest {
10741        include!("peer_manifest_tests.rs");
10742    }
10743    mod catalog_declarations {
10744        include!("control/catalog_tests.rs");
10745    }
10746    mod activity_read {
10747        include!("activity_read_tests.rs");
10748    }
10749
10750    mod lifecycle_activity {
10751        include!("control_lifecycle_tests.rs");
10752    }
10753    #[cfg(unix)]
10754    #[tokio::test]
10755    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10756        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10757        let path = dir.join("subc.jsonc");
10758        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10759            "program":"/bin/sleep","args":["60"],"protocol":"none",
10760            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10761        }}}).to_string()).unwrap();
10762        let mut configured = crate::daemon_config::load(&path)
10763            .unwrap()
10764            .unwrap()
10765            .modules
10766            .pop()
10767            .unwrap();
10768        let registry = std::sync::Arc::new(crate::Registry::default());
10769        let handle = crate::SupervisorHandle::new();
10770        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10771            .with_handle(handle.clone());
10772        let module = supervisor
10773            .supervise_configured_with_health(
10774                configured.module_spec(),
10775                true,
10776                configured.health.clone(),
10777                None,
10778                configured.restart,
10779            )
10780            .unwrap();
10781        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10782        let before = module.status().unwrap().pid;
10783        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10784        configured.health.cadence = std::time::Duration::from_secs(3600);
10785        let health_only = handler
10786            .reconcile_supervised_modules(
10787                &supervisor,
10788                vec![configured.clone()],
10789                false,
10790                Principal::Direct,
10791            )
10792            .await
10793            .unwrap();
10794        assert!(
10795            health_only.0.changed_pending_reload.is_empty(),
10796            "health policy is already applied live"
10797        );
10798        assert_eq!(module.status().unwrap().pid, before);
10799        assert_eq!(
10800            module.configuration().unwrap().1.http,
10801            configured.health.http
10802        );
10803        configured.args = vec!["61".into()];
10804        let launch = handler
10805            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10806            .await
10807            .unwrap();
10808        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10809        assert_eq!(
10810            module.status().unwrap().pid,
10811            before,
10812            "a launch edit is stored until reload"
10813        );
10814        module.drain().await.unwrap();
10815    }
10816    use cortexkit_test_support::ScratchDir;
10817    use std::{
10818        collections::BTreeMap,
10819        fmt,
10820        path::PathBuf,
10821        sync::{Arc, Mutex},
10822        time::Duration,
10823    };
10824
10825    use serde_json::{json, Value};
10826    use subc_protocol::{
10827        manifest::{
10828            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10829            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10830        },
10831        session::HealthStatus,
10832        FrameType,
10833    };
10834
10835    use super::*;
10836    use crate::{
10837        forwarding::{DataRoute, DataRouteState},
10838        registry::ChannelState,
10839        router::FrameSink,
10840        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10841        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10842        RouteCtx, Router,
10843    };
10844    use tokio::{
10845        sync::mpsc,
10846        time::{sleep, Instant},
10847    };
10848    use tracing::{
10849        field::{Field, Visit},
10850        Event, Subscriber,
10851    };
10852    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10853
10854    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10855    ///
10856    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10857    /// is only populated for `tests/*.rs` integration test binaries -- this file
10858    /// compiles as part of the library target, which gets neither. The binary
10859    /// lives in the profile folder this test was built into,
10860    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10861    /// from the test's own path.
10862    ///
10863    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10864    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10865    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10866    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10867    /// `NotFound`, which reads as a broken test rather than an unbuilt
10868    /// dependency -- so state the cause and the remedy instead. Deliberately a
10869    /// panic and not a silent skip: a test that quietly passes when it could not
10870    /// run is worse than one that fails, because it reports health it never
10871    /// verified.
10872    fn fake_aft_stub_path() -> PathBuf {
10873        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10874        assert!(
10875            path.exists(),
10876            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10877             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10878            path.display()
10879        );
10880        path
10881    }
10882
10883    /// Whether clients retry `code` in place: the predicate itself, never a copy
10884    /// of its set. A copied list breaks silently when a code is added to or
10885    /// removed from the real one, and a stale copy here would let exactly the
10886    /// failure this test exists to catch pass.
10887    fn client_retries(code: &str) -> bool {
10888        subc_protocol::error_codes::is_retryable_route_open(code)
10889    }
10890
10891    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10892    /// of failure is worse than publishing none. A permanent fault dressed as
10893    /// retryable makes every client in the fleet retry forever against something
10894    /// that cannot recover; a transient fault dressed as permanent abandons work
10895    /// that would have succeeded.
10896    ///
10897    /// Asserting "a code exists" cannot catch either, because the string is free
10898    /// to say anything. This enumerates every variant and pins which side of the
10899    /// retry boundary it lands on, so a new variant must be classified here
10900    /// deliberately rather than inheriting whichever arm it was appended to.
10901    #[test]
10902    fn retryability_of_forwarding_codes_matches_the_failure() {
10903        // Transient by nature: the target is booting, reloading, or its endpoint
10904        // was swapped mid-flight. Retrying is how these resolve.
10905        let transient = [
10906            ForwardingError::NoModuleConnection,
10907            ForwardingError::ModuleReloading {
10908                module_id: "m".into(),
10909            },
10910            ForwardingError::StaleModuleEndpoint,
10911            ForwardingError::UnknownReservation {
10912                client_channel: 1,
10913                module_channel: 1,
10914            },
10915            ForwardingError::ConnectionClosing {
10916                connection_id: ConnectionId::new(1),
10917            },
10918            ForwardingError::ClientEgressClosed {
10919                connection_id: ConnectionId::new(1),
10920            },
10921            ForwardingError::ModuleEgressUnavailable {
10922                connection_id: ConnectionId::new(1),
10923            },
10924        ];
10925        for err in transient {
10926            let code = forwarding_error_code(&err);
10927            assert!(
10928                client_retries(code),
10929                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10930            );
10931        }
10932
10933        // Not fixed by retrying. Channel and correlation exhaustion need the
10934        // caller to close routes, and a poisoned lock is a daemon that cannot
10935        // recover at all — the worst thing to advertise as retryable, since every
10936        // client would storm a daemon that will never answer.
10937        let permanent = [
10938            ForwardingError::ConnectionRoleConflict {
10939                connection_id: ConnectionId::new(1),
10940            },
10941            ForwardingError::ClientRouteChannelExhausted {
10942                connection_id: ConnectionId::new(1),
10943            },
10944            ForwardingError::ModuleRouteChannelExhausted {
10945                endpoint: ModuleEndpointId {
10946                    connection_id: ConnectionId::new(1),
10947                    generation: 1,
10948                },
10949            },
10950            ForwardingError::RelayCorrelationExhausted,
10951            ForwardingError::RouteOpenBuild("x".into()),
10952            ForwardingError::Poisoned,
10953        ];
10954        for err in permanent {
10955            let code = forwarding_error_code(&err);
10956            assert!(
10957                !client_retries(code),
10958                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10959            );
10960        }
10961    }
10962
10963    /// The principal is the daemon's answer to "who is calling", and modules
10964    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10965    /// plexus gates connector invocation. So a stamp is an authorization input in
10966    /// another process, not a label — and both possible answers SUCCEED, which is
10967    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10968    /// first-party capability to something that never proved it; a supervised one
10969    /// stamped `Direct` silently strips a module of capability it is entitled to.
10970    ///
10971    /// Neither shows up in a test that only checks the bind succeeded. Before this
10972    /// test the only coverage was accidental —
10973    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
10974    /// stamped principal on its way past, so narrowing that wire-shape test to its
10975    /// stated subject would have deleted the last assertion on this value. It
10976    /// still asserts the stamp, which is now redundancy rather than the only
10977    /// guard: both fail under the same mutation, and this one names the reason.
10978    /// SCOPE: this handler's supervisor has spawned nothing, so
10979    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
10980    /// is unreachable here. Both assertions below are refusals, and a mutant that
10981    /// refuses everything would satisfy them.
10982    ///
10983    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
10984    /// spawns a supervised consumer, reads its live nonce, and asserts the module
10985    /// observed `principal.kind == "reserved"` carrying that module_id — verified
10986    /// at source rather than assumed, since a citation is a claim about another
10987    /// file and ages like one. Recorded because a harness that structurally
10988    /// cannot reach an arm reports "none" for that arm identically to one that
10989    /// covers it and found nothing.
10990    #[tokio::test]
10991    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
10992        let handler = ControlHandler::default();
10993        let frame =
10994            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
10995
10996        // Absent consumer_identity is the ordinary case: a human at a terminal, or
10997        // any process holding the connection file. Nothing was proved, so nothing
10998        // may be granted beyond the unattested floor.
10999        let stamped = handler
11000            .route_open_principal(ConnectionId::new(1), &frame, None)
11001            .unwrap()
11002            .unwrap();
11003        assert_eq!(
11004            stamped,
11005            Principal::Direct,
11006            "a caller that proved nothing must not be stamped as a supervised module"
11007        );
11008
11009        // A claimed module_id with a nonce no supervised child was given is a
11010        // forgery attempt, not a weaker caller: it must be REFUSED rather than
11011        // quietly demoted to Direct, or an impersonation attempt looks identical
11012        // to an ordinary unattested connection.
11013        let forged = handler
11014            .route_open_principal(
11015                ConnectionId::new(1),
11016                &frame,
11017                Some(ConsumerIdentity {
11018                    module_id: "aft".to_string(),
11019                    launch_nonce: "not-a-real-nonce".to_string(),
11020                }),
11021            )
11022            .unwrap();
11023        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
11024        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
11025    }
11026
11027    /// The test above hands `route_open_principal` an identity it built itself,
11028    /// which proves the stamping rule and nothing about where the identity comes
11029    /// from. The real producer is a wire body, and the two are joined by a serde
11030    /// field name that nothing else asserts.
11031    ///
11032    /// That join fails quietly in one specific way: an unrecognised key is simply
11033    /// absent after parsing, so a renamed or misspelled `consumer_identity`
11034    /// yields `None` and every supervised module silently drops to `Direct`.
11035    /// Capability-wise that is the safe direction, but it surfaces far from its
11036    /// cause — as a module mysteriously refused bash — and it would pass every
11037    /// test that builds its own input.
11038    ///
11039    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
11040    /// would break every client the moment the daemon gains a field, trading a
11041    /// quiet demotion for a hard refusal on additive change. Asserting the join
11042    /// instead means a rename breaks a test here rather than the fleet.
11043    #[test]
11044    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
11045        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"}}"#;
11046        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
11047        let ClientControlRequest::RouteOpen {
11048            consumer_identity, ..
11049        } = parsed
11050        else {
11051            panic!("route.open body must parse as RouteOpen");
11052        };
11053        assert_eq!(
11054            consumer_identity,
11055            Some(ConsumerIdentity {
11056                module_id: "aft".to_string(),
11057                launch_nonce: "n".to_string(),
11058            }),
11059            "the wire field name must reach the value route_open_principal reads"
11060        );
11061    }
11062
11063    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
11064        ModuleManifest::builder(module_id, "0.1.0")
11065            .protocol_ver(protocol_ver)
11066            .provides(vec![ProviderRole::ToolProvider {
11067                tools: vec![Tool {
11068                    name: "read".to_string(),
11069                    description: None,
11070                    execution_mode: ExecutionMode::Pure,
11071                    schema: json!({"type": "object"}),
11072                }],
11073                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
11074                concurrency: Concurrency::ModuleManaged,
11075                emits_push: true,
11076                sub_supervises: true,
11077            }])
11078            .build()
11079    }
11080
11081    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11082        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11083    }
11084
11085    fn hello_frame_with_control_ops(
11086        module_id: &str,
11087        protocol_ver: u8,
11088        corr: u64,
11089        control_ops: Option<Vec<String>>,
11090    ) -> Frame {
11091        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11092    }
11093
11094    fn hello_frame_with_nonce(
11095        module_id: &str,
11096        protocol_ver: u8,
11097        corr: u64,
11098        launch_nonce: Option<&str>,
11099    ) -> Frame {
11100        hello_frame_full(
11101            module_id,
11102            protocol_ver,
11103            corr,
11104            None,
11105            launch_nonce.map(ToOwned::to_owned),
11106        )
11107    }
11108
11109    fn hello_frame_full(
11110        module_id: &str,
11111        protocol_ver: u8,
11112        corr: u64,
11113        control_ops: Option<Vec<String>>,
11114        launch_nonce: Option<String>,
11115    ) -> Frame {
11116        let body = serde_json::to_vec(&ModuleHelloBody {
11117            manifest: manifest(module_id, protocol_ver),
11118            protocol_ver,
11119            control_ops,
11120            launch_nonce,
11121        })
11122        .unwrap();
11123        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11124    }
11125
11126    fn hello_frame_with_rich_ui(
11127        module_id: &str,
11128        protocol_ver: u8,
11129        corr: u64,
11130        launch_nonce: Option<&str>,
11131        rich_ui: Value,
11132    ) -> Frame {
11133        let mut body = serde_json::to_value(ModuleHelloBody {
11134            manifest: manifest(module_id, protocol_ver),
11135            protocol_ver,
11136            control_ops: None,
11137            launch_nonce: launch_nonce.map(str::to_string),
11138        })
11139        .unwrap();
11140        body["manifest"]["rich_ui"] = rich_ui;
11141        Frame::build(
11142            FrameType::Hello,
11143            control_flags(),
11144            0,
11145            0,
11146            corr,
11147            serde_json::to_vec(&body).unwrap(),
11148        )
11149        .unwrap()
11150    }
11151
11152    fn non_routable_hello_frame_with_control_ops(
11153        module_id: &str,
11154        corr: u64,
11155        control_ops: Option<Vec<String>>,
11156    ) -> Frame {
11157        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11158        manifest.provides.clear();
11159        let body = serde_json::to_vec(&ModuleHelloBody {
11160            manifest,
11161            protocol_ver: PROTOCOL_VERSION,
11162            control_ops,
11163            launch_nonce: None,
11164        })
11165        .unwrap();
11166        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11167    }
11168
11169    fn capability_grammar_hello_frame(
11170        capabilities: Value,
11171        runtime_computed: Option<Value>,
11172        corr: u64,
11173    ) -> Frame {
11174        let mut body = serde_json::to_value(ModuleHelloBody {
11175            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11176            protocol_ver: PROTOCOL_VERSION,
11177            control_ops: None,
11178            launch_nonce: None,
11179        })
11180        .expect("HELLO body serializes");
11181        body["manifest"]["capabilities"] = capabilities;
11182        if let Some(runtime_computed) = runtime_computed {
11183            body["runtime_computed"] = runtime_computed;
11184        }
11185        Frame::build(
11186            FrameType::Hello,
11187            control_flags(),
11188            0,
11189            0,
11190            corr,
11191            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11192        )
11193        .expect("HELLO frame builds")
11194    }
11195
11196    fn channel_request(channel: u16, corr: u64) -> Frame {
11197        Frame::build(
11198            FrameType::Request,
11199            Flags::new(true, Priority::Interactive, false),
11200            channel,
11201            0,
11202            corr,
11203            b"opaque".to_vec(),
11204        )
11205        .unwrap()
11206    }
11207
11208    fn route_ctx(
11209        connection_id: ConnectionId,
11210    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11211        let (tx, rx) = mpsc::channel(8);
11212        (
11213            RouteCtx {
11214                connection_id,
11215                egress: FrameSink::new(tx),
11216            },
11217            rx,
11218        )
11219    }
11220
11221    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11222        serde_json::from_slice(&frame.body).unwrap()
11223    }
11224
11225    /// Register a module over a connection that has a sink and return the
11226    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11227    /// module's own sink rather than returning it as a reply, so the ack is
11228    /// taken off `rx` here and whatever the test reads next is what followed it.
11229    async fn hello_via_sink(
11230        handler: &ControlHandler,
11231        ctx: &RouteCtx,
11232        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11233        hello: Frame,
11234    ) -> Frame {
11235        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11236        assert!(
11237            replies.is_empty(),
11238            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11239        );
11240        let ack = rx
11241            .try_recv()
11242            .expect("HELLO_ACK is queued on the module sink")
11243            .frame;
11244        assert_eq!(ack.header.ty, FrameType::HelloAck);
11245        ack
11246    }
11247
11248    fn parse_error(frame: &Frame) -> Value {
11249        serde_json::from_slice(&frame.body).unwrap()
11250    }
11251
11252    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11253        serde_json::from_slice(&frame.body).unwrap()
11254    }
11255
11256    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11257        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11258            route_channel,
11259            route_epoch: 0,
11260            kind,
11261        })
11262        .unwrap();
11263        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11264    }
11265
11266    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11267        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11268            module_id: module_id.to_string(),
11269        })
11270        .unwrap();
11271        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11272    }
11273
11274    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11275        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11276    }
11277
11278    // Exercise retired opener fields without putting them back in BindIdentity.
11279    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11280        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11281        let mut frame = route_open_frame(corr, module_id, root);
11282        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11283        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11284        frame.body = serde_json::to_vec(&body).unwrap();
11285        frame
11286    }
11287
11288    fn route_open_frame_with_consumer_capabilities(
11289        corr: u64,
11290        module_id: &str,
11291        _project_root: ScratchDir,
11292        consumer_capabilities: Option<Vec<String>>,
11293    ) -> Frame {
11294        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11295            busy_refusals: None,
11296            target: RouteTarget::ToolProvider {
11297                module_id: module_id.to_string(),
11298            },
11299            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11300            consumer_identity: None,
11301            consumer_capabilities,
11302            role_versions: None,
11303            admission_facts: None,
11304            scope: None,
11305        })
11306        .unwrap();
11307        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11308    }
11309
11310    fn route_open_frame_with_role_versions(
11311        corr: u64,
11312        module_id: &str,
11313        _project_root: ScratchDir,
11314        role_versions: Option<BTreeMap<String, String>>,
11315    ) -> Frame {
11316        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11317            busy_refusals: None,
11318            target: RouteTarget::ToolProvider {
11319                module_id: module_id.to_string(),
11320            },
11321            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11322            consumer_identity: None,
11323            consumer_capabilities: None,
11324            role_versions,
11325            admission_facts: None,
11326            scope: None,
11327        })
11328        .unwrap();
11329        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11330    }
11331
11332    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11333        entries
11334            .iter()
11335            .map(|(role, version)| (role.to_string(), version.to_string()))
11336            .collect()
11337    }
11338
11339    fn route_open_frame_with_admission_facts(
11340        corr: u64,
11341        module_id: &str,
11342        _project_root: ScratchDir,
11343        consumer_identity: Option<subc_control::ConsumerIdentity>,
11344        facts: Option<Value>,
11345    ) -> Frame {
11346        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11347            busy_refusals: None,
11348            target: RouteTarget::ToolProvider {
11349                module_id: module_id.to_string(),
11350            },
11351            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11352            consumer_identity,
11353            consumer_capabilities: None,
11354            role_versions: None,
11355            admission_facts: facts,
11356            scope: None,
11357        })
11358        .unwrap();
11359        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11360    }
11361
11362    #[derive(Clone, Default)]
11363    struct EventCapture {
11364        events: Arc<Mutex<Vec<CapturedEvent>>>,
11365    }
11366
11367    #[derive(Clone, Debug)]
11368    struct CapturedEvent {
11369        target: String,
11370        level: tracing::Level,
11371        fields: BTreeMap<String, String>,
11372    }
11373
11374    impl EventCapture {
11375        fn events(&self) -> Vec<CapturedEvent> {
11376            self.events.lock().unwrap().clone()
11377        }
11378    }
11379
11380    impl<S> Layer<S> for EventCapture
11381    where
11382        S: Subscriber,
11383    {
11384        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11385            let mut visitor = EventFieldVisitor::default();
11386            event.record(&mut visitor);
11387            self.events.lock().unwrap().push(CapturedEvent {
11388                target: event.metadata().target().to_string(),
11389                level: *event.metadata().level(),
11390                fields: visitor.fields,
11391            });
11392        }
11393    }
11394
11395    #[derive(Default)]
11396    struct EventFieldVisitor {
11397        fields: BTreeMap<String, String>,
11398    }
11399
11400    impl Visit for EventFieldVisitor {
11401        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11402            self.fields
11403                .insert(field.name().to_string(), format!("{value:?}"));
11404        }
11405    }
11406
11407    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11408        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11409            status,
11410            detail: Some("warming".to_string()),
11411            metrics: Some(json!({"queue_depth": 3})),
11412        })
11413        .unwrap();
11414        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11415    }
11416
11417    fn route_bind_ack(corr: u64) -> Frame {
11418        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11419        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11420    }
11421
11422    fn unique_project_root(label: &str) -> ScratchDir {
11423        ScratchDir::new(label)
11424    }
11425
11426    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11427        match parse_route_poll(frame) {
11428            ClientControlResponse::RoutePoll {
11429                status: None,
11430                live: Some(live),
11431                ..
11432            } => assert_eq!(live, expected_live),
11433            other => panic!("unexpected route.poll response: {other:?}"),
11434        }
11435    }
11436
11437    fn bind_liveness_route(
11438        registry: &Registry,
11439        forwarding: &ForwardingTable,
11440        module_id: &str,
11441    ) -> (RouteCtx, u16, u32) {
11442        let module_connection = ConnectionId::new(101);
11443        let client_connection = ConnectionId::new(202);
11444        let registration = registry
11445            .register_with_control_ops(
11446                manifest(module_id, PROTOCOL_VERSION),
11447                PROTOCOL_VERSION,
11448                module_connection,
11449                module_baseline_control_ops(),
11450            )
11451            .unwrap();
11452        let (module_tx, _module_rx) = mpsc::channel(8);
11453        let endpoint = forwarding
11454            .register_module_connection(
11455                module_connection,
11456                module_id.to_string(),
11457                PROTOCOL_VERSION,
11458                manifest_concurrency(&registration.manifest),
11459                FrameSink::new(module_tx),
11460            )
11461            .unwrap();
11462        let (client_ctx, _client_rx) = route_ctx(client_connection);
11463        let pending = forwarding
11464            .begin_route_bind_relay_for_test(
11465                client_connection,
11466                client_ctx.egress.clone(),
11467                1,
11468                module_id,
11469            )
11470            .unwrap();
11471        assert_eq!(pending.endpoint, endpoint);
11472        let route_channel = pending.client_channel;
11473        let route_epoch = pending.client_epoch;
11474        forwarding
11475            .complete_pending_relay(
11476                module_connection,
11477                pending.corr,
11478                RouteBindRelayOutcome::Accepted,
11479            )
11480            .unwrap();
11481        (client_ctx, route_channel, route_epoch)
11482    }
11483
11484    struct FakeProcessLiveness {
11485        live: Option<bool>,
11486    }
11487
11488    impl ModuleProcessLiveness for FakeProcessLiveness {
11489        fn process_live(&self, _module_id: &str) -> Option<bool> {
11490            self.live
11491        }
11492    }
11493
11494    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11495    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11496    {
11497        let registry = Arc::new(Registry::default());
11498        let supervisor_handle = SupervisorHandle::new();
11499        let supervisor = Supervisor::new_for_test(
11500            Arc::clone(&registry),
11501            RestartPolicy::new(1, Duration::from_millis(10)),
11502        )
11503        .with_handle(supervisor_handle.clone());
11504        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11505        let module = supervisor
11506            .spawn(ModuleSpec {
11507                script: None,
11508                carry_containment: false,
11509                module_id: "stderr-tail-wire".to_string(),
11510                program: fake_aft_stub_path(),
11511                args: Vec::new(),
11512                env: vec![
11513                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11514                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11515                ],
11516                reserved: false,
11517                reserved_prefixes: Vec::new(),
11518                protocol: ModuleProtocol::Subc,
11519                overlap: Default::default(),
11520            })
11521            .unwrap();
11522
11523        let deadline = Instant::now() + Duration::from_secs(5);
11524        loop {
11525            let tail = module.stderr_tail(None, None);
11526            if tail
11527                .entries
11528                .iter()
11529                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11530                && tail.entries.iter().any(|entry| {
11531                    matches!(
11532                        entry,
11533                        TailEntry::Line {
11534                            truncated: true,
11535                            ..
11536                        }
11537                    )
11538                })
11539            {
11540                break;
11541            }
11542            assert!(
11543                Instant::now() < deadline,
11544                "module did not produce a truncated line and restart boundary: {tail:?}"
11545            );
11546            sleep(Duration::from_millis(10)).await;
11547        }
11548
11549        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11550        let request = ClientControlRequest::SupervisorStderrTail {
11551            module_id: "stderr-tail-wire".to_string(),
11552            max_lines: None,
11553            max_bytes: None,
11554        };
11555        let frame = Frame::build(
11556            FrameType::Request,
11557            control_flags(),
11558            0,
11559            0,
11560            1,
11561            serde_json::to_vec(&request).unwrap(),
11562        )
11563        .unwrap();
11564        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11565        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11566        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11567            serde_json::from_slice(&responses[0].body).unwrap()
11568        else {
11569            panic!("expected supervisor.stderr_tail response");
11570        };
11571
11572        assert!(
11573            tail.entries
11574                .iter()
11575                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11576            "the control response lost the restart boundary"
11577        );
11578        let Some(StderrTailEntry::Line {
11579            text,
11580            truncated,
11581            at_ms,
11582        }) = tail.entries.iter().find(|entry| {
11583            matches!(
11584                entry,
11585                StderrTailEntry::Line {
11586                    truncated: true,
11587                    ..
11588                }
11589            )
11590        })
11591        else {
11592            panic!("the control response lost the truncated line");
11593        };
11594        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11595        assert!(*truncated);
11596        assert!(
11597            at_ms.is_some(),
11598            "the control response lost the line's capture time"
11599        );
11600    }
11601
11602    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11603    /// read done on the worker thread would stall every other task until it
11604    /// finished; the read must run off the worker so this test's own task keeps
11605    /// running while the read is paused.
11606    #[tokio::test(flavor = "current_thread")]
11607    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11608        let dir = ScratchDir::new("terminals-off-worker");
11609        let journal_path = dir.join("terminals.jsonl");
11610        let registry = Arc::new(Registry::default());
11611        let supervisor_handle = SupervisorHandle::new();
11612        let supervisor =
11613            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11614                .with_handle(supervisor_handle.clone())
11615                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11616        let module = supervisor
11617            .spawn(ModuleSpec {
11618                script: None,
11619                carry_containment: false,
11620                module_id: "terminal-off-worker".to_string(),
11621                program: fake_aft_stub_path(),
11622                args: Vec::new(),
11623                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11624                reserved: false,
11625                reserved_prefixes: Vec::new(),
11626                protocol: ModuleProtocol::Subc,
11627                overlap: Default::default(),
11628            })
11629            .unwrap();
11630        let deadline = Instant::now() + Duration::from_secs(5);
11631        while module.terminal_history().entries.len() != 2 {
11632            assert!(Instant::now() < deadline, "module did not record two exits");
11633            sleep(Duration::from_millis(10)).await;
11634        }
11635
11636        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11637        let handler =
11638            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11639        let frame = Frame::build(
11640            FrameType::Request,
11641            control_flags(),
11642            0,
11643            0,
11644            1,
11645            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11646                module_id: "terminal-off-worker".to_string(),
11647            })
11648            .unwrap(),
11649        )
11650        .unwrap();
11651        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11652        let spawned_at = std::time::Instant::now();
11653        let read = tokio::spawn({
11654            let handler = Arc::clone(&handler);
11655            async move { handler.handle_control_frame(&ctx, frame).await }
11656        });
11657        // Waiting for the pause from a blocking thread keeps this task pending,
11658        // so the runtime's single worker is free to run the read task.
11659        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11660            .await
11661            .unwrap()
11662            .expect("the history read reached its pause");
11663        let elapsed = spawned_at.elapsed();
11664        assert!(
11665            elapsed < Duration::from_secs(2) && !read.is_finished(),
11666            "this task could not run while the history read was paused \
11667             (resumed after {elapsed:?}, read finished: {})",
11668            read.is_finished()
11669        );
11670
11671        drop(release);
11672        let responses = read.await.unwrap().unwrap();
11673        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11674        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11675            panic!("expected supervisor.terminals response");
11676        };
11677        assert_eq!(terminals.entries.len(), 2);
11678        assert_eq!(terminals.journal_skipped_lines, 0);
11679        assert_eq!(terminals.journal_read_errors, 0);
11680    }
11681
11682    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11683    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11684        let registry = Arc::new(Registry::default());
11685        let supervisor_handle = SupervisorHandle::new();
11686        let supervisor =
11687            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11688                .with_handle(supervisor_handle.clone());
11689        let module = supervisor
11690            .spawn(ModuleSpec {
11691                script: None,
11692                carry_containment: false,
11693                module_id: "terminal-golden".to_string(),
11694                program: fake_aft_stub_path(),
11695                args: Vec::new(),
11696                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11697                reserved: false,
11698                reserved_prefixes: Vec::new(),
11699                protocol: ModuleProtocol::Subc,
11700                overlap: Default::default(),
11701            })
11702            .unwrap();
11703
11704        let deadline = Instant::now() + Duration::from_secs(5);
11705        while module.terminal_history().entries.len() != 2 {
11706            assert!(
11707                Instant::now() < deadline,
11708                "module did not retain two terminal exits: {:?}",
11709                module.terminal_history()
11710            );
11711            sleep(Duration::from_millis(10)).await;
11712        }
11713
11714        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11715        let request = ClientControlRequest::SupervisorTerminals {
11716            module_id: "terminal-golden".to_string(),
11717        };
11718        let frame = Frame::build(
11719            FrameType::Request,
11720            control_flags(),
11721            0,
11722            0,
11723            1,
11724            serde_json::to_vec(&request).unwrap(),
11725        )
11726        .unwrap();
11727        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11728        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11729        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11730        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11731            panic!("expected supervisor.terminals response");
11732        };
11733        assert_eq!(terminals.entries.len(), 2);
11734        assert_eq!(terminals.dropped, 0);
11735
11736        let mut rendered = serde_json::to_value(response).unwrap();
11737        // Wall-clock fields are the observation contract, but not stable fixture
11738        // bytes; normalize only them after the real handler has shaped the response.
11739        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11740        for (index, entry) in rendered["entries"]
11741            .as_array_mut()
11742            .expect("terminal response entries array")
11743            .iter_mut()
11744            .enumerate()
11745        {
11746            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11747        }
11748
11749        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11750            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11751        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11752        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11753            std::fs::write(&golden_path, &serialized).unwrap();
11754        }
11755        let expected: Value =
11756            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11757        assert_eq!(rendered, expected);
11758    }
11759
11760    #[test]
11761    fn hello_registers_manifest_and_returns_ack() {
11762        let registry = Arc::new(Registry::default());
11763        let handler = ControlHandler::new(Arc::clone(&registry));
11764        let conn = ConnectionId::new(1);
11765
11766        let responses = handler
11767            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11768            .unwrap();
11769
11770        assert_eq!(responses.len(), 1);
11771        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11772        assert_eq!(responses[0].header.channel, 0);
11773        assert_eq!(responses[0].header.corr, 7);
11774        let ack = parse_ack(&responses[0]);
11775        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11776        assert!(ack
11777            .subc_capabilities
11778            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11779        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11780        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11781        assert!(ack
11782            .subc_ops
11783            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11784        assert!(ack
11785            .subc_ops
11786            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11787        assert!(ack
11788            .subc_ops
11789            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11790
11791        let registration = registry.get_module("aft").unwrap().unwrap();
11792        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11793        assert_eq!(registration.state, ChannelState::Active);
11794        assert_eq!(registration.connection_id, conn);
11795        assert_eq!(registration.control_ops, module_baseline_control_ops());
11796        assert!(registration.manifest.display_name.is_none());
11797    }
11798
11799    #[test]
11800    fn hello_display_name_refuses_invalid_manifest_by_field() {
11801        let registry = Arc::new(Registry::default());
11802        let handler = ControlHandler::new(Arc::clone(&registry));
11803        for (index, invalid) in [
11804            json!(""),
11805            json!("a".repeat(41)),
11806            json!(" Routing"),
11807            json!("a\nb"),
11808            json!("a\u{202e}b"),
11809            json!(7),
11810        ]
11811        .into_iter()
11812        .enumerate()
11813        {
11814            let module_id = format!("bad-display-name-{index}");
11815            let mut body = serde_json::to_value(ModuleHelloBody {
11816                manifest: manifest(&module_id, PROTOCOL_VERSION),
11817                protocol_ver: PROTOCOL_VERSION,
11818                control_ops: None,
11819                launch_nonce: None,
11820            })
11821            .unwrap();
11822            body["manifest"]["display_name"] = invalid;
11823            let hello = Frame::build(
11824                FrameType::Hello,
11825                control_flags(),
11826                0,
11827                0,
11828                7,
11829                serde_json::to_vec(&body).unwrap(),
11830            )
11831            .unwrap();
11832            let response = handler
11833                .handle_control(ConnectionId::new(100 + index as u64), hello)
11834                .unwrap();
11835            assert_eq!(response[0].header.ty, FrameType::Error);
11836            let error = parse_error(&response[0]);
11837            assert_eq!(error["code"], "invalid_manifest");
11838            assert!(error["message"].as_str().unwrap().contains("display_name"));
11839            assert!(registry.get_module(&module_id).unwrap().is_none());
11840        }
11841    }
11842
11843    #[test]
11844    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11845        let invalid_identifiers = [
11846            ("case_change", "credentials-Provider/v1"),
11847            ("leading_zero", "credentials-provider/v01"),
11848            ("trailing_hyphen", "credentials-provider-/v1"),
11849            ("consecutive_hyphens", "credentials--provider/v1"),
11850            ("uppercase", "Credentials-provider/v1"),
11851            ("missing_v", "credentials-provider/1"),
11852            ("whitespace", "credentials provider/v1"),
11853            ("zero_version", "credentials-provider/v0"),
11854            ("out_of_range_version", "credentials-provider/v4294967296"),
11855            (
11856                "overlength_name",
11857                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11858            ),
11859        ];
11860        let mut cases = invalid_identifiers
11861            .into_iter()
11862            .map(|(name, identifier)| {
11863                (
11864                    format!("identifier_{name}"),
11865                    "capabilities.provides[0]".to_string(),
11866                    identifier.to_string(),
11867                    json!({ "provides": [identifier] }),
11868                    None,
11869                )
11870            })
11871            .collect::<Vec<_>>();
11872        cases.extend([
11873            (
11874                "unknown_need".to_string(),
11875                "capabilities.requires[0].need".to_string(),
11876                "deferred".to_string(),
11877                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11878                None,
11879            ),
11880            (
11881                "duplicate_provides".to_string(),
11882                "capabilities.provides[1]".to_string(),
11883                "credentials-provider/v1".to_string(),
11884                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11885                None,
11886            ),
11887            (
11888                "duplicate_must_never_reach".to_string(),
11889                "capabilities.must_never_reach[1]".to_string(),
11890                "credentials-provider/v1".to_string(),
11891                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11892                None,
11893            ),
11894            (
11895                "duplicate_requires_same_need".to_string(),
11896                "capabilities.requires[1]".to_string(),
11897                "credentials-provider/v1".to_string(),
11898                json!({ "requires": [
11899                    { "capability": "credentials-provider/v1", "need": "required" },
11900                    { "capability": "credentials-provider/v1", "need": "required" }
11901                ] }),
11902                None,
11903            ),
11904            (
11905                "duplicate_requires_conflicting_need".to_string(),
11906                "capabilities.requires[1]".to_string(),
11907                "credentials-provider/v1".to_string(),
11908                json!({ "requires": [
11909                    { "capability": "credentials-provider/v1", "need": "required" },
11910                    { "capability": "credentials-provider/v1", "need": "optional" }
11911                ] }),
11912                None,
11913            ),
11914            (
11915                "capabilities_root_pointer".to_string(),
11916                "runtime_computed[0]".to_string(),
11917                "/capabilities".to_string(),
11918                json!({}),
11919                Some(json!(["/capabilities"])),
11920            ),
11921            (
11922                "capabilities_descendant_pointer".to_string(),
11923                "runtime_computed[0]".to_string(),
11924                "/capabilities/provides".to_string(),
11925                json!({}),
11926                Some(json!(["/capabilities/provides"])),
11927            ),
11928            (
11929                "malformed_pointer_without_leading_slash".to_string(),
11930                "runtime_computed[0]".to_string(),
11931                "capabilities".to_string(),
11932                json!({}),
11933                Some(json!(["capabilities"])),
11934            ),
11935            (
11936                "malformed_pointer_escape".to_string(),
11937                "runtime_computed[0]".to_string(),
11938                "/roles/~2/tools".to_string(),
11939                json!({}),
11940                Some(json!(["/roles/~2/tools"])),
11941            ),
11942            (
11943                "unknown_capabilities_field".to_string(),
11944                "capabilities.future".to_string(),
11945                "<array>".to_string(),
11946                json!({ "future": [] }),
11947                None,
11948            ),
11949        ]);
11950
11951        for (index, (name, field, value, capabilities, runtime_computed)) in
11952            cases.into_iter().enumerate()
11953        {
11954            let registry = Arc::new(Registry::default());
11955            let handler = ControlHandler::new(Arc::clone(&registry));
11956            let response = handler
11957                .handle_control(
11958                    ConnectionId::new((index + 1) as u64),
11959                    capability_grammar_hello_frame(
11960                        capabilities,
11961                        runtime_computed,
11962                        index as u64 + 1,
11963                    ),
11964                )
11965                .expect("invalid HELLO returns a refusal");
11966
11967            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11968            let error = parse_error(&response[0]);
11969            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11970            let message = error["message"]
11971                .as_str()
11972                .expect("error message is a string");
11973            assert!(
11974                message.contains(&field),
11975                "{name}: field missing from {message}"
11976            );
11977            assert!(
11978                message.contains(&value),
11979                "{name}: value missing from {message}"
11980            );
11981            assert_eq!(
11982                registry
11983                    .active_registration_count()
11984                    .expect("registry reads"),
11985                0,
11986                "{name}: refused HELLO must not create a catalog entry"
11987            );
11988        }
11989    }
11990
11991    #[test]
11992    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
11993        let registry = Arc::new(Registry::default());
11994        let handler = ControlHandler::new(Arc::clone(&registry));
11995        let capabilities = json!({
11996            "provides": ["credentials-provider/v1"],
11997            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
11998            "must_never_reach": ["federation-transport/v1"]
11999        });
12000        let response = handler
12001            .handle_control(
12002                ConnectionId::new(99),
12003                capability_grammar_hello_frame(
12004                    capabilities.clone(),
12005                    Some(json!(["/roles/0/tools"])),
12006                    99,
12007                ),
12008            )
12009            .expect("valid HELLO registers");
12010        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12011
12012        let request = Frame::build(
12013            FrameType::Request,
12014            control_flags(),
12015            0,
12016            0,
12017            100,
12018            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12019                .expect("catalog request serializes"),
12020        )
12021        .expect("catalog request frame builds");
12022        let response = handler
12023            .handle_catalog_list(request, None)
12024            .expect("catalog list succeeds");
12025        let ClientControlResponse::CatalogList { modules, .. } =
12026            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
12027        else {
12028            panic!("catalog request must return catalog.list");
12029        };
12030        assert_eq!(modules.len(), 1);
12031        assert_eq!(
12032            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
12033            capabilities
12034        );
12035    }
12036
12037    #[test]
12038    fn catalog_list_mirrors_management_operation_description() {
12039        let registry = Arc::new(Registry::default());
12040        let handler = ControlHandler::new(Arc::clone(&registry));
12041        let description = "List managed records and return their identifiers and metadata.";
12042        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
12043        manifest.provides = vec![ProviderRole::ManagementSurface {
12044            operations: vec![ManagementOperation {
12045                name: "records.list".to_string(),
12046                kind: ManagementOperationKind::Query,
12047                description: Some(description.to_string()),
12048            }],
12049            config_schema: json!({"type": "object"}),
12050            observability: vec![ObservabilitySurface {
12051                name: "records.stats".to_string(),
12052                kind: ObservabilityKind::Snapshot,
12053            }],
12054            identity_scope: vec![IdentityScope::Project],
12055            concurrency: Concurrency::ModuleManaged,
12056        }];
12057        registry
12058            .register_with_control_ops(
12059                manifest,
12060                PROTOCOL_VERSION,
12061                ConnectionId::new(99),
12062                Vec::new(),
12063            )
12064            .expect("described management manifest registers");
12065
12066        let request = Frame::build(
12067            FrameType::Request,
12068            control_flags(),
12069            0,
12070            0,
12071            100,
12072            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12073                .expect("catalog request serializes"),
12074        )
12075        .expect("catalog request frame builds");
12076        let response = handler
12077            .handle_catalog_list(request, None)
12078            .expect("catalog list succeeds");
12079        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12080        assert_eq!(
12081            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12082            "catalog.list must preserve the declared operation description verbatim"
12083        );
12084    }
12085
12086    #[test]
12087    fn catalog_list_mirrors_registered_operation_delivery() {
12088        let registry = Arc::new(Registry::default());
12089        let handler = ControlHandler::new(Arc::clone(&registry));
12090        let delivery =
12091            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12092        let mut body = serde_json::to_value(ModuleHelloBody {
12093            manifest: manifest("watch-management", PROTOCOL_VERSION),
12094            protocol_ver: PROTOCOL_VERSION,
12095            control_ops: None,
12096            launch_nonce: None,
12097        })
12098        .unwrap();
12099        body["manifest"]["provides"] = json!([{
12100            "role": "management_surface",
12101            "operations": [
12102                {"name": "status", "kind": "query"},
12103                {"name": "future", "kind": "query"},
12104                {"name": "reset", "kind": "mutate"}
12105            ],
12106            "config_schema": {}, "observability": [], "identity_scope": []
12107        }]);
12108        body["manifest"]["operation_delivery"] = delivery.clone();
12109        let hello = Frame::build(
12110            FrameType::Hello,
12111            control_flags(),
12112            0,
12113            0,
12114            99,
12115            serde_json::to_vec(&body).unwrap(),
12116        )
12117        .unwrap();
12118        let response = handler
12119            .handle_control(ConnectionId::new(99), hello)
12120            .unwrap();
12121        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12122
12123        let (_, registrations) = registry.list_modules().unwrap();
12124        let registered = &registrations[0].manifest;
12125        assert!(registered.is_watch_operation("status"));
12126        assert!(!registered.is_watch_operation("future"));
12127        assert!(!registered.is_watch_operation("reset"));
12128        assert!(!registered.is_watch_operation("missing"));
12129
12130        let request = Frame::build(
12131            FrameType::Request,
12132            control_flags(),
12133            0,
12134            0,
12135            100,
12136            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12137        )
12138        .unwrap();
12139        let response = handler.handle_catalog_list(request, None).unwrap();
12140        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12141        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12142        let ClientControlResponse::CatalogList { modules, .. } =
12143            serde_json::from_slice(&response[0].body).unwrap()
12144        else {
12145            panic!("expected catalog.list");
12146        };
12147        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12148    }
12149
12150    #[test]
12151    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12152        let registry = Arc::new(Registry::default());
12153        let supervisor = SupervisorHandle::new();
12154        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12155        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12156        let descriptor = json!({
12157            "schema": "ckios.richui.manifest/1",
12158            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12159            "bytes": 4096,
12160            "chunks": 4
12161        });
12162        let connection = ConnectionId::new(201);
12163        let hello = handler
12164            .handle_control(
12165                connection,
12166                hello_frame_with_rich_ui(
12167                    "vault",
12168                    PROTOCOL_VERSION,
12169                    201,
12170                    Some("the-real-nonce"),
12171                    descriptor.clone(),
12172                ),
12173            )
12174            .unwrap();
12175        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12176
12177        let request =
12178            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12179        let provides = registry
12180            .get_module_by_connection(connection)
12181            .unwrap()
12182            .unwrap()
12183            .manifest
12184            .provides;
12185        handler
12186            .handle_catalog_update(connection, request, provides, None, Some(false))
12187            .unwrap();
12188
12189        let request = Frame::build(
12190            FrameType::Request,
12191            control_flags(),
12192            0,
12193            0,
12194            203,
12195            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12196        )
12197        .unwrap();
12198        let response = handler.handle_catalog_list(request, None).unwrap();
12199        let ClientControlResponse::CatalogList { modules, .. } =
12200            serde_json::from_slice(&response[0].body).unwrap()
12201        else {
12202            panic!("expected catalog.list");
12203        };
12204        assert_eq!(
12205            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12206            descriptor
12207        );
12208        assert!(modules[0].nonce_verified);
12209    }
12210
12211    fn hello_with_role_declarations(declarations: Value) -> Frame {
12212        let mut body = serde_json::to_value(ModuleHelloBody {
12213            manifest: manifest("role-test", PROTOCOL_VERSION),
12214            protocol_ver: PROTOCOL_VERSION,
12215            control_ops: None,
12216            launch_nonce: None,
12217        })
12218        .unwrap();
12219        body["manifest"]["role_declarations"] = declarations;
12220        Frame::build(
12221            FrameType::Hello,
12222            control_flags(),
12223            0,
12224            0,
12225            301,
12226            serde_json::to_vec(&body).unwrap(),
12227        )
12228        .unwrap()
12229    }
12230
12231    fn update_role_declarations_frame(declarations: Value) -> Frame {
12232        Frame::build(
12233            FrameType::Request,
12234            control_flags(),
12235            0,
12236            0,
12237            303,
12238            serde_json::to_vec(&json!({
12239                "op": "catalog.update_role_declarations",
12240                "role_declarations": declarations,
12241            }))
12242            .unwrap(),
12243        )
12244        .unwrap()
12245    }
12246
12247    #[tokio::test]
12248    async fn role_declarations_update_replaces_then_clears_catalog() {
12249        let registry = Arc::new(Registry::default());
12250        let handler = ControlHandler::new(Arc::clone(&registry));
12251        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12252        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12253        hello_via_sink(
12254            &handler,
12255            &ctx,
12256            &mut rx,
12257            hello_with_role_declarations(initial.clone()),
12258        )
12259        .await;
12260        assert_eq!(
12261            role_declarations_catalog(&handler).0["role_declarations"],
12262            initial
12263        );
12264        let before = registry.get_module("role-test").unwrap().unwrap();
12265        for declarations in [
12266            json!({"media-provider/v1": {"engines": ["new"]}}),
12267            json!({}),
12268        ] {
12269            let response = handler
12270                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12271                .await
12272                .unwrap();
12273            assert_eq!(response[0].header.ty, FrameType::Response);
12274            assert_eq!(
12275                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12276                json!({"op": "catalog.update_role_declarations"})
12277            );
12278            let (raw, entry) = role_declarations_catalog(&handler);
12279            assert_eq!(
12280                serde_json::to_value(entry.role_declarations).unwrap(),
12281                declarations
12282            );
12283            if declarations.as_object().unwrap().is_empty() {
12284                assert!(raw.get("role_declarations").is_none());
12285            } else {
12286                assert_eq!(raw["role_declarations"], declarations);
12287            }
12288            let after = registry.get_module("role-test").unwrap().unwrap();
12289            let mut expected = before.manifest.clone();
12290            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12291            assert_eq!(after.manifest, expected);
12292            assert_eq!(after.ready, before.ready);
12293        }
12294    }
12295
12296    #[tokio::test]
12297    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12298        let registry = Arc::new(Registry::default());
12299        let handler = ControlHandler::new(registry);
12300        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12301        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12302        hello_via_sink(
12303            &handler,
12304            &ctx,
12305            &mut rx,
12306            hello_with_role_declarations(initial.clone()),
12307        )
12308        .await;
12309        for (invalid, reason) in [
12310            (json!(null), "role_declarations must be an object"),
12311            (json!([]), "role_declarations must be an object"),
12312            (
12313                json!({"bad key": {}}),
12314                "role_declarations key must use capability-name grammar",
12315            ),
12316            (
12317                json!({"media-provider/v1": []}),
12318                "role_declarations values must be objects",
12319            ),
12320            (
12321                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12322                "role_declarations exceeds 16384 compact JSON bytes",
12323            ),
12324        ] {
12325            let response = handler
12326                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12327                .await
12328                .unwrap();
12329            let error = parse_error(&response[0]);
12330            assert_eq!(error["code"], "invalid_role_declarations");
12331            assert_eq!(error["message"], reason);
12332            assert_eq!(
12333                role_declarations_catalog(&handler).0["role_declarations"],
12334                initial
12335            );
12336        }
12337    }
12338
12339    #[tokio::test]
12340    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12341        let registry = Arc::new(Registry::default());
12342        let handler = ControlHandler::new(Arc::clone(&registry));
12343        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12344        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12345        hello_via_sink(
12346            &handler,
12347            &owner,
12348            &mut owner_rx,
12349            hello_with_role_declarations(initial.clone()),
12350        )
12351        .await;
12352        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12353        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12354        let response = handler
12355            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12356            .await
12357            .unwrap();
12358        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12359        hello_via_sink(
12360            &handler,
12361            &other,
12362            &mut other_rx,
12363            hello_frame("other", PROTOCOL_VERSION, 304),
12364        )
12365        .await;
12366        let response = handler
12367            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12368            .await
12369            .unwrap();
12370        assert_eq!(response[0].header.ty, FrameType::Response);
12371        assert_eq!(
12372            serde_json::to_value(
12373                registry
12374                    .get_module("role-test")
12375                    .unwrap()
12376                    .unwrap()
12377                    .manifest
12378                    .role_declarations
12379            )
12380            .unwrap(),
12381            initial
12382        );
12383        assert_eq!(
12384            serde_json::to_value(
12385                registry
12386                    .get_module("other")
12387                    .unwrap()
12388                    .unwrap()
12389                    .manifest
12390                    .role_declarations
12391            )
12392            .unwrap(),
12393            replacement
12394        );
12395    }
12396
12397    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12398        let request = Frame::build(
12399            FrameType::Request,
12400            control_flags(),
12401            0,
12402            0,
12403            302,
12404            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12405        )
12406        .unwrap();
12407        let response = handler.handle_catalog_list(request, None).unwrap();
12408        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12409        let ClientControlResponse::CatalogList { mut modules, .. } =
12410            serde_json::from_slice(&response[0].body).unwrap()
12411        else {
12412            panic!("expected catalog.list");
12413        };
12414        (raw["modules"][0].clone(), modules.remove(0))
12415    }
12416
12417    #[test]
12418    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12419        let registry = Arc::new(Registry::default());
12420        let handler = ControlHandler::new(Arc::clone(&registry));
12421        let declarations = json!({
12422            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12423            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12424        });
12425        let connection = ConnectionId::new(301);
12426        let response = handler
12427            .handle_control(
12428                connection,
12429                hello_with_role_declarations(declarations.clone()),
12430            )
12431            .unwrap();
12432        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12433        let registered = registry
12434            .get_module_by_connection(connection)
12435            .unwrap()
12436            .unwrap()
12437            .manifest;
12438        // Compared as JSON values, not bytes: object key order is not part of
12439        // the relay's promise, and workspace builds unify serde_json's
12440        // preserve_order feature, which changes the order a literal keeps.
12441        assert_eq!(
12442            serde_json::to_value(&registered.role_declarations).unwrap(),
12443            declarations
12444        );
12445        let (raw, entry) = role_declarations_catalog(&handler);
12446        assert_eq!(raw["role_declarations"], declarations);
12447        assert_eq!(entry.role_declarations, registered.role_declarations);
12448
12449        let request =
12450            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12451        handler
12452            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12453            .unwrap();
12454        let (raw, entry) = role_declarations_catalog(&handler);
12455        assert_eq!(raw["role_declarations"], declarations);
12456        assert_eq!(entry.role_declarations, registered.role_declarations);
12457    }
12458
12459    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12460        let registry = Arc::new(Registry::default());
12461        let handler = ControlHandler::new(Arc::clone(&registry));
12462        let capture = EventCapture::default();
12463        let _subscriber =
12464            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12465        let response = handler
12466            .handle_control(
12467                ConnectionId::new(301),
12468                hello_with_role_declarations(declarations),
12469            )
12470            .unwrap();
12471        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12472        assert!(registry
12473            .get_module_by_connection(ConnectionId::new(301))
12474            .unwrap()
12475            .unwrap()
12476            .manifest
12477            .role_declarations
12478            .is_empty());
12479        let (raw, entry) = role_declarations_catalog(&handler);
12480        assert!(raw.get("role_declarations").is_none());
12481        assert!(entry.role_declarations.is_empty());
12482        let warnings: Vec<_> = capture
12483            .events()
12484            .into_iter()
12485            .filter(|event| {
12486                event.fields.get("message").map(String::as_str)
12487                    == Some("dropping whole role_declarations map from HELLO")
12488            })
12489            .collect();
12490        assert_eq!(warnings.len(), 1);
12491        assert_eq!(warnings[0].level, tracing::Level::WARN);
12492        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12493        assert_eq!(warnings[0].fields["reason"], reason);
12494    }
12495
12496    #[test]
12497    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12498        for value in [
12499            json!(null),
12500            json!(false),
12501            json!(0),
12502            json!("opaque"),
12503            json!([]),
12504        ] {
12505            assert_hello_drops_role_declarations_with_warning(
12506                json!({"routing/v1": {}, "broken/v1": value}),
12507                "role_declarations values must be objects",
12508            );
12509        }
12510        assert_hello_drops_role_declarations_with_warning(
12511            json!([]),
12512            "role_declarations must be an object",
12513        );
12514    }
12515
12516    #[test]
12517    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12518        assert_hello_drops_role_declarations_with_warning(
12519            json!({"routing/v1": {}, "bad key": {}}),
12520            "role_declarations key must use capability-name grammar",
12521        );
12522    }
12523
12524    #[test]
12525    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12526        assert_hello_drops_role_declarations_with_warning(
12527            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12528            "role_declarations exceeds 16384 compact JSON bytes",
12529        );
12530    }
12531
12532    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12533        let mut body = serde_json::to_value(ModuleHelloBody {
12534            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12535            protocol_ver: PROTOCOL_VERSION,
12536            control_ops: None,
12537            launch_nonce: None,
12538        })
12539        .unwrap();
12540        body["manifest"]["provides"] = json!([{
12541            "role": "management_surface",
12542            "operations": [
12543                {"name": "diagnostics.findings", "kind": "query"},
12544                {"name": "reset", "kind": "mutate"}
12545            ],
12546            "config_schema": {}, "observability": [], "identity_scope": []
12547        }]);
12548        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12549        if let Some(flow_operations) = flow_operations {
12550            body["manifest"]["flow_operations"] = flow_operations;
12551        }
12552        Frame::build(
12553            FrameType::Hello,
12554            control_flags(),
12555            0,
12556            0,
12557            401,
12558            serde_json::to_vec(&body).unwrap(),
12559        )
12560        .unwrap()
12561    }
12562
12563    #[test]
12564    fn catalog_list_mirrors_flow_operations_unchanged() {
12565        // Order is kept as declared (not sorted) and an empty list stays an
12566        // affirmative "none", distinct from an absent declaration.
12567        for (capability, flow_operations) in [
12568            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12569            ("call-modes/v1", json!(["diagnostics.findings"])),
12570            ("flow-scopes/v1", json!([])),
12571        ] {
12572            let registry = Arc::new(Registry::default());
12573            let handler = ControlHandler::new(Arc::clone(&registry));
12574            let connection = ConnectionId::new(401);
12575            let response = handler
12576                .handle_control(
12577                    connection,
12578                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12579                )
12580                .unwrap();
12581            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12582            let registered = registry
12583                .get_module_by_connection(connection)
12584                .unwrap()
12585                .unwrap()
12586                .manifest;
12587            assert_eq!(
12588                serde_json::to_value(&registered.flow_operations).unwrap(),
12589                flow_operations
12590            );
12591            let (raw, entry) = role_declarations_catalog(&handler);
12592            assert_eq!(raw["flow_operations"], flow_operations);
12593            assert_eq!(entry.flow_operations, registered.flow_operations);
12594        }
12595
12596        let registry = Arc::new(Registry::default());
12597        let handler = ControlHandler::new(Arc::clone(&registry));
12598        let response = handler
12599            .handle_control(
12600                ConnectionId::new(401),
12601                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12602            )
12603            .unwrap();
12604        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12605        let (raw, entry) = role_declarations_catalog(&handler);
12606        assert!(raw.get("flow_operations").is_none());
12607        assert_eq!(entry.flow_operations, None);
12608    }
12609
12610    #[test]
12611    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12612        let oversized: serde_json::Map<String, Value> = (0..257)
12613            .map(|n| (format!("tool:t{n}"), json!(true)))
12614            .collect();
12615        for (capabilities, map, valid) in [
12616            (
12617                json!(["scope-federated/v1"]),
12618                json!({"tool:read":true,"management:reset":true}),
12619                true,
12620            ),
12621            (json!(["scope-federated/v1"]), json!({}), true),
12622            (json!([]), json!({"tool:read":true}), false),
12623            (
12624                json!(["scope-federated/v1"]),
12625                json!({"tool:valid":true,"tool:bad":false}),
12626                false,
12627            ),
12628            (
12629                json!(["scope-federated/v1"]),
12630                json!({"tool:valid":true,"management:missing":true}),
12631                false,
12632            ),
12633            (
12634                json!(["scope-federated/v1"]),
12635                Value::Object(oversized),
12636                false,
12637            ),
12638        ] {
12639            let capture = EventCapture::default();
12640            let _subscriber = tracing::subscriber::set_default(
12641                tracing_subscriber::registry().with(capture.clone()),
12642            );
12643            let registry = Arc::new(Registry::default());
12644            let handler = ControlHandler::new(Arc::clone(&registry));
12645            let hello = hello_with_flow_operations(capabilities, None);
12646            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12647            body["manifest"]["operation_deferral"] = map.clone();
12648            let hello = Frame::build(
12649                FrameType::Hello,
12650                control_flags(),
12651                0,
12652                0,
12653                401,
12654                serde_json::to_vec(&body).unwrap(),
12655            )
12656            .unwrap();
12657            let response = handler
12658                .handle_control(ConnectionId::new(401), hello)
12659                .unwrap();
12660            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12661            let (raw, entry) = role_declarations_catalog(&handler);
12662            if valid {
12663                assert_eq!(raw["operation_deferral"], map);
12664                assert_eq!(
12665                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12666                    map
12667                );
12668            } else {
12669                assert!(entry.operation_deferral.is_none());
12670                assert!(raw.get("operation_deferral").is_none());
12671                assert_eq!(
12672                    capture
12673                        .events()
12674                        .iter()
12675                        .filter(|event| event.fields.get("message").map(String::as_str)
12676                            == Some("dropping operation_deferral from HELLO"))
12677                        .count(),
12678                    1
12679                );
12680            }
12681        }
12682    }
12683
12684    fn assert_hello_drops_flow_operations_with_warning(
12685        capabilities: Value,
12686        flow_operations: Value,
12687        reason: &str,
12688    ) {
12689        let registry = Arc::new(Registry::default());
12690        let handler = ControlHandler::new(Arc::clone(&registry));
12691        let capture = EventCapture::default();
12692        let _subscriber =
12693            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12694        let response = handler
12695            .handle_control(
12696                ConnectionId::new(401),
12697                hello_with_flow_operations(capabilities, Some(flow_operations)),
12698            )
12699            .unwrap();
12700        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12701        let registered = registry
12702            .get_module_by_connection(ConnectionId::new(401))
12703            .unwrap()
12704            .expect("the module still registers")
12705            .manifest;
12706        assert_eq!(registered.module_id, "flow-ops");
12707        assert_eq!(registered.flow_operations, None);
12708        let (raw, entry) = role_declarations_catalog(&handler);
12709        assert_eq!(raw["module_id"], "flow-ops");
12710        assert!(raw.get("flow_operations").is_none());
12711        assert_eq!(entry.flow_operations, None);
12712        let warnings: Vec<_> = capture
12713            .events()
12714            .into_iter()
12715            .filter(|event| {
12716                event.fields.get("message").map(String::as_str)
12717                    == Some("dropping flow_operations from HELLO")
12718            })
12719            .collect();
12720        assert_eq!(warnings.len(), 1);
12721        assert_eq!(warnings[0].level, tracing::Level::WARN);
12722        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12723        assert_eq!(warnings[0].fields["reason"], reason);
12724    }
12725
12726    #[test]
12727    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12728        assert_hello_drops_flow_operations_with_warning(
12729            json!(["flow-scopes/v1"]),
12730            json!(["diagnostics.findings", "missing"]),
12731            "flow_operations names 'missing', which is not a declared management operation",
12732        );
12733    }
12734
12735    #[test]
12736    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12737        assert_hello_drops_flow_operations_with_warning(
12738            json!([]),
12739            json!(["diagnostics.findings"]),
12740            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12741        );
12742        // A run-only capability does not admit flows either.
12743        assert_hello_drops_flow_operations_with_warning(
12744            json!(["agent-run-scopes/v1"]),
12745            json!([]),
12746            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12747        );
12748    }
12749
12750    #[test]
12751    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12752        assert_hello_drops_flow_operations_with_warning(
12753            json!(["flow-scopes/v1"]),
12754            json!(["reset", "reset"]),
12755            "flow_operations names 'reset' more than once",
12756        );
12757        assert_hello_drops_flow_operations_with_warning(
12758            json!(["flow-scopes/v1"]),
12759            json!(vec!["reset"; 257]),
12760            "flow_operations lists 257 names, more than 256",
12761        );
12762        assert_hello_drops_flow_operations_with_warning(
12763            json!(["flow-scopes/v1"]),
12764            json!("reset"),
12765            "flow_operations must be an array of operation names",
12766        );
12767    }
12768
12769    #[test]
12770    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12771        let registry = Arc::new(Registry::default());
12772        let handler = ControlHandler::new(registry.clone());
12773        let descriptor = json!({
12774            "schema": "ckios.richui.manifest/1",
12775            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12776            "bytes": 128,
12777            "chunks": 2
12778        });
12779        let malformed = [
12780            ("schema", json!("")),
12781            ("schema", json!("a".repeat(65))),
12782            ("schema", json!("Bad schema")),
12783            (
12784                "manifest_digest",
12785                json!(format!("sha256:{}", "A".repeat(64))),
12786            ),
12787            ("manifest_digest", json!("sha256:abc")),
12788            ("bytes", json!(0)),
12789            ("bytes", json!(16_777_217)),
12790            ("bytes", json!("128")),
12791            ("chunks", json!(0)),
12792            ("chunks", json!(1025)),
12793            ("chunks", json!("2")),
12794        ];
12795        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12796            let mut invalid = descriptor.clone();
12797            invalid[field] = invalid_value;
12798            let response = handler
12799                .handle_control(
12800                    ConnectionId::new(210 + index as u64),
12801                    hello_frame_with_rich_ui(
12802                        &format!("bad-rich-ui-{index}"),
12803                        PROTOCOL_VERSION,
12804                        210 + index as u64,
12805                        None,
12806                        invalid,
12807                    ),
12808                )
12809                .unwrap();
12810            assert_eq!(response[0].header.ty, FrameType::Error);
12811            let error = parse_error(&response[0]);
12812            assert_eq!(error["code"], "invalid_manifest");
12813            assert!(error["message"]
12814                .as_str()
12815                .unwrap()
12816                .contains(&format!("rich_ui.{field}")));
12817            assert!(registry
12818                .get_module(&format!("bad-rich-ui-{index}"))
12819                .unwrap()
12820                .is_none());
12821        }
12822    }
12823
12824    #[test]
12825    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12826        let registry = Arc::new(Registry::default());
12827        let handler = ControlHandler::new(Arc::clone(&registry));
12828        let connection = ConnectionId::new(219);
12829        registry
12830            .register_with_control_ops(
12831                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12832                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12833                        "bad schema",
12834                        format!("sha256:{}", "a".repeat(64)),
12835                        128,
12836                        2,
12837                    )))
12838                    .build(),
12839                PROTOCOL_VERSION,
12840                connection,
12841                Vec::new(),
12842            )
12843            .unwrap();
12844        let request =
12845            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12846        let response = handler
12847            .handle_catalog_update(connection, request, Vec::new(), None, None)
12848            .unwrap();
12849        assert_eq!(response[0].header.ty, FrameType::Error);
12850        let error = parse_error(&response[0]);
12851        assert_eq!(error["code"], "invalid_manifest");
12852        assert!(error["message"]
12853            .as_str()
12854            .unwrap()
12855            .contains("rich_ui.schema"));
12856    }
12857
12858    #[test]
12859    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12860        let registry = Arc::new(Registry::default());
12861        let supervisor = SupervisorHandle::new();
12862        supervisor.open_swap("provider", "candidate-nonce".to_string());
12863        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12864        let connection = ConnectionId::new(218);
12865        let hello = handler
12866            .handle_control(
12867                connection,
12868                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12869            )
12870            .unwrap();
12871        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12872        assert!(registry.list_modules().unwrap().1.is_empty());
12873
12874        registry.promote_candidate("provider").unwrap().unwrap();
12875        let request = Frame::build(
12876            FrameType::Request,
12877            control_flags(),
12878            0,
12879            0,
12880            219,
12881            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12882        )
12883        .unwrap();
12884        let response = handler.handle_catalog_list(request, None).unwrap();
12885        let ClientControlResponse::CatalogList { modules, .. } =
12886            serde_json::from_slice(&response[0].body).unwrap()
12887        else {
12888            panic!("expected catalog.list");
12889        };
12890        assert_eq!(modules.len(), 1);
12891        assert!(modules[0].nonce_verified);
12892    }
12893
12894    #[test]
12895    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12896        for provenance_json in [
12897            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12898            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12899        ] {
12900            let registry = Arc::new(Registry::default());
12901            let handler = ControlHandler::new(registry);
12902            let hello = Frame::build(
12903                FrameType::Hello,
12904                control_flags(),
12905                0,
12906                0,
12907                220,
12908                serde_json::to_vec(&ModuleHelloBody {
12909                    manifest: ModuleManifest::builder("built", "0.1.0")
12910                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12911                        .build(),
12912                    protocol_ver: PROTOCOL_VERSION,
12913                    control_ops: None,
12914                    launch_nonce: None,
12915                })
12916                .unwrap(),
12917            )
12918            .unwrap();
12919            assert_eq!(
12920                handler
12921                    .handle_control(ConnectionId::new(220), hello)
12922                    .unwrap()[0]
12923                    .header
12924                    .ty,
12925                FrameType::HelloAck
12926            );
12927            let request = Frame::build(
12928                FrameType::Request,
12929                control_flags(),
12930                0,
12931                0,
12932                221,
12933                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12934            )
12935            .unwrap();
12936            let response = handler.handle_catalog_list(request, None).unwrap();
12937            let ClientControlResponse::CatalogList { modules, .. } =
12938                serde_json::from_slice(&response[0].body).unwrap()
12939            else {
12940                panic!("expected catalog.list");
12941            };
12942            assert_eq!(modules.len(), 1);
12943            assert_eq!(
12944                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12945                format!(
12946                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12947                )
12948                .as_bytes()
12949            );
12950        }
12951    }
12952
12953    #[test]
12954    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12955        let registry = Arc::new(Registry::default());
12956        let handler = ControlHandler::new(Arc::clone(&registry));
12957        let hello = Frame::build(
12958            FrameType::Hello,
12959            control_flags(),
12960            0,
12961            0,
12962            220,
12963            serde_json::to_vec(&ModuleHelloBody {
12964                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12965                protocol_ver: PROTOCOL_VERSION,
12966                control_ops: None,
12967                launch_nonce: Some("unverified".to_string()),
12968            })
12969            .unwrap(),
12970        )
12971        .unwrap();
12972        assert_eq!(
12973            handler
12974                .handle_control(ConnectionId::new(220), hello)
12975                .unwrap()[0]
12976                .header
12977                .ty,
12978            FrameType::HelloAck
12979        );
12980        let request = Frame::build(
12981            FrameType::Request,
12982            control_flags(),
12983            0,
12984            0,
12985            221,
12986            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12987        )
12988        .unwrap();
12989        let response = handler.handle_catalog_list(request, None).unwrap();
12990        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
12991        assert!(wire["modules"][0].get("provenance").is_none());
12992        let ClientControlResponse::CatalogList { modules, .. } =
12993            serde_json::from_slice(&response[0].body).unwrap()
12994        else {
12995            panic!("expected catalog.list");
12996        };
12997        assert_eq!(
12998            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12999            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
13000        );
13001        assert!(!modules[0].nonce_verified);
13002        assert!(modules[0].provenance.is_none());
13003    }
13004
13005    // Preserve the legacy-field byte pins while discovery adds optional facts.
13006    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
13007        assert_eq!(entry.first_party, Some(false));
13008        entry.incarnation = None;
13009        entry.spawn = None;
13010        entry.first_party = None;
13011        entry.origin = None;
13012        entry.requested_declarations_digest = None;
13013        entry.approved_declarations_digest = None;
13014        entry
13015    }
13016
13017    #[test]
13018    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
13019        let registry = Arc::new(Registry::default());
13020        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13021            [("vault".to_string(), true), ("squatter".to_string(), true)],
13022            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13023        );
13024        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
13025        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13026            provides: vec!["credentials-provider/v1".to_string()],
13027            requires: Vec::new(),
13028            must_never_reach: Vec::new(),
13029        });
13030        let frame = Frame::build(
13031            FrameType::Hello,
13032            control_flags(),
13033            0,
13034            0,
13035            77,
13036            serde_json::to_vec(&ModuleHelloBody {
13037                manifest: squatter,
13038                protocol_ver: PROTOCOL_VERSION,
13039                control_ops: None,
13040                launch_nonce: None,
13041            })
13042            .expect("HELLO serializes"),
13043        )
13044        .expect("HELLO frame builds");
13045        let response = handler
13046            .handle_control(ConnectionId::new(77), frame)
13047            .expect("reserved claim receives a typed refusal");
13048        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13049        assert_eq!(
13050            registry
13051                .active_registration_count()
13052                .expect("registry reads"),
13053            0,
13054            "a reserved capability refusal must not leave a catalog entry"
13055        );
13056    }
13057
13058    #[test]
13059    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
13060        for settlement in ["timeout", "inconclusive", "drop"] {
13061            let breakers = RouteBindBreakers::default();
13062            let RouteBindAdmission::Admitted {
13063                guard: mut old,
13064                probe: false,
13065            } = breakers.admit("prov")
13066            else {
13067                panic!("ordinary relay admitted")
13068            };
13069            let RouteBindAdmission::Admitted {
13070                guard: mut opener, ..
13071            } = breakers.admit("prov")
13072            else {
13073                panic!("second relay admitted")
13074            };
13075            assert!(
13076                !opener
13077                    .record_timeout(1, Duration::ZERO)
13078                    .unwrap()
13079                    .reopened_after_probe
13080            );
13081            let RouteBindAdmission::Admitted {
13082                guard: mut probe,
13083                probe: true,
13084            } = breakers.admit("prov")
13085            else {
13086                panic!("one cooldown probe admitted")
13087            };
13088            match settlement {
13089                "timeout" => assert!(
13090                    !old.record_timeout(1, Duration::ZERO)
13091                        .unwrap()
13092                        .reopened_after_probe
13093                ),
13094                "inconclusive" => old.record_inconclusive(),
13095                "drop" => drop(old),
13096                _ => unreachable!(),
13097            }
13098            assert!(
13099                matches!(
13100                    breakers.admit("prov"),
13101                    RouteBindAdmission::Refused {
13102                        probe_in_flight: true,
13103                        ..
13104                    }
13105                ),
13106                "{settlement} of a pre-open relay cannot release the real probe"
13107            );
13108            assert!(
13109                probe
13110                    .record_timeout(1, Duration::ZERO)
13111                    .unwrap()
13112                    .reopened_after_probe
13113            );
13114            assert!(matches!(
13115                breakers.admit("prov"),
13116                RouteBindAdmission::Admitted { probe: true, .. }
13117            ));
13118        }
13119        let breakers = RouteBindBreakers::default();
13120        let admit = || match breakers.admit("prov") {
13121            RouteBindAdmission::Admitted { guard, .. } => guard,
13122            _ => panic!("relay admitted"),
13123        };
13124        admit().record_timeout(1, Duration::ZERO);
13125        let mut old_probe = admit();
13126        breakers.reset_for_new_module_connection("prov");
13127        admit().record_timeout(1, Duration::ZERO);
13128        let _new_probe = admit();
13129        old_probe.record_inconclusive();
13130        assert!(matches!(
13131            breakers.admit("prov"),
13132            RouteBindAdmission::Refused {
13133                probe_in_flight: true,
13134                ..
13135            }
13136        ));
13137    }
13138
13139    #[tokio::test]
13140    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13141        for candidate in [false, true] {
13142            let registry = Arc::new(Registry::default());
13143            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13144                [("vault".to_string(), true), ("squatter".to_string(), true)],
13145                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13146            );
13147            let conn = ConnectionId::new(77);
13148            let (ctx, mut rx) = route_ctx(conn);
13149            let initial = capability_manifest("squatter", &[], &[]);
13150            if candidate {
13151                registry
13152                    .register_candidate_with_control_ops(
13153                        initial.clone(),
13154                        PROTOCOL_VERSION,
13155                        conn,
13156                        module_baseline_control_ops(),
13157                    )
13158                    .unwrap();
13159                handler
13160                    .forwarding
13161                    .register_candidate_module_connection(
13162                        conn,
13163                        "squatter".to_string(),
13164                        PROTOCOL_VERSION,
13165                        manifest_concurrency(&initial),
13166                        ctx.egress.clone(),
13167                    )
13168                    .unwrap();
13169            } else {
13170                hello_via_sink(
13171                    &handler,
13172                    &ctx,
13173                    &mut rx,
13174                    hello_frame_with_manifest(initial.clone(), 1),
13175                )
13176                .await;
13177            }
13178            let response = handler
13179                .handle_control_frame(
13180                    &ctx,
13181                    catalog_update_with_capabilities_frame(
13182                        2,
13183                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13184                            .capabilities
13185                            .unwrap(),
13186                    ),
13187                )
13188                .await
13189                .unwrap();
13190            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13191            assert_eq!(
13192                registry
13193                    .get_module_by_connection(conn)
13194                    .unwrap()
13195                    .unwrap()
13196                    .manifest,
13197                initial
13198            );
13199        }
13200    }
13201
13202    #[test]
13203    #[cfg(not(feature = "dev-desktop-approval"))]
13204    fn server_describe_default_build_advertises_no_config_capability() {
13205        let assert_default = |handler: &ControlHandler| {
13206            let request = Frame::build(
13207                FrameType::Request,
13208                control_flags(),
13209                0,
13210                0,
13211                79,
13212                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13213            )
13214            .unwrap();
13215            let responses = handler.handle_server_describe(request).unwrap();
13216            assert_eq!(responses.len(), 1);
13217            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13218            assert_eq!(response["op"], "server.describe");
13219            let capabilities = response["capabilities"]
13220                .as_array()
13221                .expect("capability array");
13222            assert!(
13223                !capabilities.is_empty(),
13224                "exercise an actual describe response, not an empty fixture"
13225            );
13226            assert!(
13227                capabilities
13228                    .iter()
13229                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13230                "a default build must not announce configuration authority: {capabilities:?}"
13231            );
13232        };
13233        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13234        #[cfg(unix)]
13235        {
13236            // A local store does not prove that project-membership validation,
13237            // active-scope usage tracking and approved-program launch selection
13238            // are connected. Defaults must not advertise that authority.
13239            let (_rig, _owner, _supervisor, handler, _spec) =
13240                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13241                );
13242            assert_default(&handler);
13243        }
13244    }
13245
13246    #[test]
13247    fn server_describe_surfaces_required_capability_verdict_fields() {
13248        let registry = Arc::new(Registry::default());
13249        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13250            [
13251                ("consumer".to_string(), true),
13252                ("provider".to_string(), false),
13253            ],
13254            BTreeMap::new(),
13255        );
13256        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13257        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13258            provides: Vec::new(),
13259            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13260                capability: "credentials-provider/v1".to_string(),
13261                need: subc_protocol::manifest::CapabilityNeed::Required,
13262            }],
13263            must_never_reach: Vec::new(),
13264        });
13265        let hello = Frame::build(
13266            FrameType::Hello,
13267            control_flags(),
13268            0,
13269            0,
13270            78,
13271            serde_json::to_vec(&ModuleHelloBody {
13272                manifest: consumer,
13273                protocol_ver: PROTOCOL_VERSION,
13274                control_ops: None,
13275                launch_nonce: None,
13276            })
13277            .expect("HELLO serializes"),
13278        )
13279        .expect("HELLO frame builds");
13280        handler
13281            .handle_control(ConnectionId::new(78), hello)
13282            .expect("consumer registers");
13283        let describe = Frame::build(
13284            FrameType::Request,
13285            control_flags(),
13286            0,
13287            0,
13288            79,
13289            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13290                .expect("request serializes"),
13291        )
13292        .expect("describe frame builds");
13293        let response = handler
13294            .handle_server_describe(describe)
13295            .expect("server.describe succeeds");
13296        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13297        let requirement = &rendered["capability_requirements"][0];
13298        assert_eq!(requirement["consumer"], "consumer");
13299        assert_eq!(requirement["verdict"], "never_provided");
13300        assert_eq!(requirement["episode_seq"], 1);
13301        assert_eq!(requirement["config_satisfiable"], false);
13302        assert_eq!(requirement["runtime_available"], false);
13303        assert!(requirement["detail"]
13304            .as_str()
13305            .expect("detail string")
13306            .contains("credentials-provider/v1"));
13307    }
13308
13309    /// Register a consumer that requires `project-identity/v1` and the provider
13310    /// of it, optionally mark daemon shutdown as begun, then deregister the
13311    /// provider as its connection closes. Returns the `capability.requirement`
13312    /// events that deregistration logged and the verdict the evaluator then
13313    /// holds for the requirement (the one `route.open` refusals read).
13314    fn deregister_required_provider(
13315        daemon_shutdown_begun: bool,
13316    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13317        const CAPABILITY: &str = "project-identity/v1";
13318        let registry = Arc::new(Registry::default());
13319        let daemon_shutdown = DaemonShutdownFlag::default();
13320        let handler = ControlHandler::new(Arc::clone(&registry))
13321            .with_capability_config(
13322                [
13323                    ("consumer".to_string(), true),
13324                    ("provider".to_string(), true),
13325                ],
13326                BTreeMap::new(),
13327            )
13328            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13329        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13330        consumer.capabilities = Some(CapabilityDeclarations {
13331            provides: Vec::new(),
13332            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13333                capability: CAPABILITY.to_string(),
13334                need: subc_protocol::manifest::CapabilityNeed::Required,
13335            }],
13336            must_never_reach: Vec::new(),
13337        });
13338        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13339        let provider_conn = ConnectionId::new(182);
13340        for (conn, manifest, corr) in [
13341            (ConnectionId::new(181), consumer, 181),
13342            (provider_conn, provider, 182),
13343        ] {
13344            let hello = handler
13345                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13346                .expect("module registers");
13347            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13348        }
13349        assert_eq!(
13350            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13351            Some(CapabilityVerdict::Provided),
13352            "the registered provider must satisfy the requirement first"
13353        );
13354        if daemon_shutdown_begun {
13355            daemon_shutdown.set_for_test();
13356        }
13357
13358        let capture = EventCapture::default();
13359        let _subscriber =
13360            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13361        handler
13362            .cleanup_connection(provider_conn)
13363            .expect("provider deregisters");
13364        let events = capture
13365            .events()
13366            .into_iter()
13367            .filter(|event| {
13368                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13369            })
13370            .collect();
13371        (
13372            events,
13373            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13374        )
13375    }
13376
13377    #[test]
13378    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13379        let (events, verdict) = deregister_required_provider(true);
13380        assert_eq!(
13381            verdict,
13382            Some(CapabilityVerdict::NeverProvided),
13383            "shutdown must not change the verdict route.open refusals read"
13384        );
13385        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13386        let event = &events[0];
13387        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13388        assert_eq!(
13389            event.fields.get("cause").map(String::as_str),
13390            Some("\"daemon_shutdown\""),
13391            "{event:?}"
13392        );
13393        assert_eq!(
13394            event.fields.get("verdict").map(String::as_str),
13395            Some("\"never_provided\""),
13396            "{event:?}"
13397        );
13398    }
13399
13400    #[test]
13401    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13402        let (events, verdict) = deregister_required_provider(false);
13403        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13404        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13405        let event = &events[0];
13406        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13407        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13408        assert_eq!(
13409            event.fields.get("verdict").map(String::as_str),
13410            Some("\"never_provided\""),
13411            "{event:?}"
13412        );
13413    }
13414
13415    #[test]
13416    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13417        let registry = Arc::new(Registry::default());
13418        let handler = ControlHandler::new(Arc::clone(&registry));
13419        let hello = handler
13420            .handle_control(
13421                ConnectionId::new(101),
13422                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13423            )
13424            .expect("legacy HELLO registers");
13425        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13426
13427        let request = Frame::build(
13428            FrameType::Request,
13429            control_flags(),
13430            0,
13431            0,
13432            102,
13433            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13434                .expect("catalog request serializes"),
13435        )
13436        .expect("catalog request frame builds");
13437        let response = handler
13438            .handle_catalog_list(request, None)
13439            .expect("catalog list succeeds");
13440        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13441        assert!(
13442            body["modules"][0].get("capabilities").is_none(),
13443            "legacy manifest must retain an absent capabilities field on catalog.list"
13444        );
13445    }
13446
13447    #[test]
13448    fn hello_ack_omits_storage_when_no_storage_config() {
13449        let registry = Arc::new(Registry::default());
13450        let handler = ControlHandler::new(Arc::clone(&registry));
13451        let responses = handler
13452            .handle_control(
13453                ConnectionId::new(1),
13454                hello_frame("aft", PROTOCOL_VERSION, 7),
13455            )
13456            .unwrap();
13457        let ack = parse_ack(&responses[0]);
13458        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13459        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13460    }
13461
13462    #[tokio::test]
13463    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13464        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13465        let registry = Arc::new(Registry::default());
13466        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13467        let responses = handler
13468            .handle_control(
13469                ConnectionId::new(1),
13470                hello_frame("aft", PROTOCOL_VERSION, 7),
13471            )
13472            .unwrap();
13473        let ack = parse_ack(&responses[0]);
13474        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13475
13476        let described = handler
13477            .handle_control_frame(
13478                &route_ctx(ConnectionId::new(2)).0,
13479                Frame::build(
13480                    FrameType::Request,
13481                    control_flags(),
13482                    0,
13483                    0,
13484                    9,
13485                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13486                )
13487                .unwrap(),
13488            )
13489            .await
13490            .unwrap();
13491        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13492            serde_json::from_slice(&described[0].body).unwrap()
13493        else {
13494            panic!("server.describe answered with another shape");
13495        };
13496        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13497    }
13498
13499    #[test]
13500    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13501        // With a central sqlite storage policy, each registering module gets its
13502        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13503        let registry = Arc::new(Registry::default());
13504        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13505            crate::daemon_config::StorageConfig::Sqlite {
13506                data_home: std::path::PathBuf::from("/data"),
13507            },
13508        ));
13509
13510        let responses = handler
13511            .handle_control(
13512                ConnectionId::new(1),
13513                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13514            )
13515            .unwrap();
13516        let ack = parse_ack(&responses[0]);
13517        assert_eq!(
13518            ack.storage,
13519            Some(serde_json::json!({
13520                "module_id": "alfonso-routing",
13521                "storage_namespace": "default",
13522                "isolation": { "kind": "module" },
13523                "backend": {
13524                    "backend": "sqlite",
13525                    "path": "/data/cortexkit/alfonso-routing/store.db"
13526                }
13527            })),
13528            "the delivered descriptor is the module's own sqlite store path"
13529        );
13530    }
13531
13532    #[test]
13533    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13534        let registry = Arc::new(Registry::default());
13535        let handler = ControlHandler::new(Arc::clone(&registry));
13536        let conn = ConnectionId::new(1);
13537        let responses = handler
13538            .handle_control(
13539                conn,
13540                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13541            )
13542            .unwrap();
13543        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13544        let registration = registry.get_module("aft").unwrap().unwrap();
13545        assert_eq!(registration.control_ops, module_baseline_control_ops());
13546
13547        let frame =
13548            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13549        assert!(handler
13550            .guard_module_control_op(&frame, "aft", "route.bind")
13551            .unwrap()
13552            .is_none());
13553        let error = handler
13554            .guard_module_control_op(&frame, "aft", "test.synthetic")
13555            .unwrap()
13556            .expect("synthetic ungranted op should be rejected");
13557        assert_eq!(error.header.ty, FrameType::Error);
13558        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13559    }
13560
13561    #[test]
13562    fn hello_control_ops_some_adds_optional_grants() {
13563        let registry = Arc::new(Registry::default());
13564        let handler = ControlHandler::new(Arc::clone(&registry));
13565        handler
13566            .handle_control(
13567                ConnectionId::new(1),
13568                hello_frame_with_control_ops(
13569                    "aft",
13570                    PROTOCOL_VERSION,
13571                    7,
13572                    Some(vec![
13573                        "future.synthetic".to_string(),
13574                        "route.bind".to_string(),
13575                    ]),
13576                ),
13577            )
13578            .unwrap();
13579        let registration = registry.get_module("aft").unwrap().unwrap();
13580        assert_eq!(
13581            registration.control_ops,
13582            vec![
13583                "route.bind".to_string(),
13584                "route.status".to_string(),
13585                "future.synthetic".to_string(),
13586            ]
13587        );
13588        let frame =
13589            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13590        assert!(handler
13591            .guard_module_control_op(&frame, "aft", "future.synthetic")
13592            .unwrap()
13593            .is_none());
13594    }
13595
13596    #[tokio::test]
13597    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13598        let registry = Arc::new(Registry::default());
13599        let forwarding = Arc::new(ForwardingTable::default());
13600        let handler =
13601            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13602        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13603        hello_via_sink(
13604            &handler,
13605            &module_ctx,
13606            &mut module_rx,
13607            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13608        )
13609        .await;
13610
13611        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13612        let responses = handler
13613            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13614            .await
13615            .unwrap();
13616        assert_eq!(responses.len(), 1);
13617        assert_eq!(responses[0].header.ty, FrameType::Error);
13618        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13619        assert!(module_rx.try_recv().is_err());
13620    }
13621
13622    #[tokio::test]
13623    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13624        let registry = Arc::new(Registry::default());
13625        let forwarding = Arc::new(ForwardingTable::default());
13626        let handler =
13627            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13628        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13629        hello_via_sink(
13630            &handler,
13631            &module_ctx,
13632            &mut module_rx,
13633            hello_frame_with_control_ops(
13634                "aft",
13635                PROTOCOL_VERSION,
13636                7,
13637                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13638            ),
13639        )
13640        .await;
13641
13642        let project_root = unique_project_root("demux");
13643        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13644        let route_handler = handler.clone();
13645        let route_task = tokio::spawn(async move {
13646            route_handler
13647                .handle_control_frame(
13648                    &route_client_ctx,
13649                    route_open_frame(100, "aft", project_root),
13650                )
13651                .await
13652                .unwrap()
13653        });
13654        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13655            .await
13656            .unwrap()
13657            .unwrap();
13658        assert!(matches!(
13659            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13660            ModuleControlRequest::RouteBind { .. }
13661        ));
13662
13663        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13664        let health_handler = handler.clone();
13665        let health_task = tokio::spawn(async move {
13666            health_handler
13667                .handle_control_frame(
13668                    &health_client_ctx,
13669                    supervisor_health_probe_frame(101, "aft"),
13670                )
13671                .await
13672                .unwrap()
13673        });
13674        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13675            .await
13676            .unwrap()
13677            .unwrap();
13678        assert_eq!(
13679            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13680            ModuleControlRequest::HealthCheck {}
13681        );
13682
13683        handler
13684            .handle_control_frame(
13685                &module_ctx,
13686                health_response(health_frame.header.corr, HealthStatus::Degraded),
13687            )
13688            .await
13689            .unwrap();
13690        let health_response = health_task.await.unwrap();
13691        assert_eq!(health_response.len(), 1);
13692        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13693            ClientControlResponse::SupervisorHealthProbe {
13694                module_id,
13695                status,
13696                detail,
13697                metrics,
13698            } => {
13699                assert_eq!(module_id, "aft");
13700                assert_eq!(status, HealthStatus::Degraded);
13701                assert_eq!(detail.as_deref(), Some("warming"));
13702                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13703            }
13704            other => panic!("unexpected health response: {other:?}"),
13705        }
13706
13707        handler
13708            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13709            .await
13710            .unwrap();
13711        let route_response = route_task.await.unwrap();
13712        assert!(route_response.is_empty());
13713        let published = route_client_rx.recv().await.unwrap();
13714        assert!(matches!(
13715            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13716            ClientControlResponse::RouteOpen { .. }
13717        ));
13718    }
13719
13720    /// Start one `route.open` on `client_connection` and return its still-running
13721    /// handler task together with the `route.bind` the module received for it.
13722    /// The handler blocks until the module answers, so it has to run as a task
13723    /// while the test drives the module side.
13724    async fn relay_route_open(
13725        handler: &ControlHandler,
13726        client_connection: ConnectionId,
13727        client_egress: &FrameSink,
13728        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13729        corr: u64,
13730        module_id: &str,
13731        project_root_label: &str,
13732    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13733        let ctx = RouteCtx {
13734            connection_id: client_connection,
13735            egress: client_egress.clone(),
13736        };
13737        let handler = handler.clone();
13738        let project_root = unique_project_root(project_root_label);
13739        let module_id = module_id.to_string();
13740        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13741        let task = tokio::spawn(async move {
13742            let _guard = tracing::dispatcher::set_default(&dispatch);
13743            handler
13744                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13745                .await
13746                .unwrap()
13747        });
13748        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13749            .await
13750            .expect("module receives the relayed route.bind")
13751            .expect("module egress is open");
13752        (task, bind.frame)
13753    }
13754
13755    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13756        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13757            ModuleControlRequest::RouteBind {
13758                route_channel,
13759                epoch,
13760                ..
13761            } => (route_channel, epoch),
13762            other => panic!("expected a route.bind request, got {other:?}"),
13763        }
13764    }
13765
13766    fn published_route(frame: &Frame) -> (u16, u32) {
13767        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13768            ClientControlResponse::RouteOpen {
13769                route_channel,
13770                route_epoch,
13771                ..
13772            } => (route_channel, route_epoch),
13773            other => panic!("expected a route.open response, got {other:?}"),
13774        }
13775    }
13776
13777    /// Reproduction of a production outage. A client had `route.open`s in
13778    /// flight to a module and was already marked closing -- its egress had refused a
13779    /// module frame, so the daemon asked its connection to end -- while its sink
13780    /// was still open. When the module acked those binds, the daemon refused to
13781    /// commit a route for a closing client, and that refusal was returned from
13782    /// the MODULE connection's frame handler, where a router error that has no
13783    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13784    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13785    /// its tools for hours -- one client's teardown took down a connection
13786    /// carrying ~170 other routes.
13787    ///
13788    /// The window is opened here by calling the production path that opens it
13789    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13790    /// state that matters is "in `closing_connections`, sink still open, relay
13791    /// still pending", and it lasts only from the close request until the
13792    /// connection loop reacts to it; a socket-level test can flood a client into
13793    /// that escalation but cannot pin the module's ack inside the window. Closing
13794    /// the socket instead takes the other path entirely -- connection teardown
13795    /// removes the pending relay under the same lock, so the ack finds nothing.
13796    #[tokio::test]
13797    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13798        let registry = Arc::new(Registry::default());
13799        let forwarding = Arc::new(ForwardingTable::default());
13800        let handler =
13801            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13802
13803        let module_connection = ConnectionId::new(30);
13804        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13805        hello_via_sink(
13806            &handler,
13807            &module_ctx,
13808            &mut module_rx,
13809            hello_frame("aft", PROTOCOL_VERSION, 7),
13810        )
13811        .await;
13812
13813        let dying_client = ConnectionId::new(31);
13814        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13815
13816        // A published route on the dying client. The escalation below only marks
13817        // a connection closing for a route it has already published.
13818        let (first_task, first_bind) = relay_route_open(
13819            &handler,
13820            dying_client,
13821            &dying_ctx.egress,
13822            &mut module_rx,
13823            100,
13824            "aft",
13825            "closing-first",
13826        )
13827        .await;
13828        handler
13829            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13830            .await
13831            .unwrap();
13832        assert!(first_task.await.unwrap().is_empty());
13833        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13834
13835        // A second route.open from the same client, relayed and awaiting its ack.
13836        let (second_task, second_bind) = relay_route_open(
13837            &handler,
13838            dying_client,
13839            &dying_ctx.egress,
13840            &mut module_rx,
13841            101,
13842            "aft",
13843            "closing-second",
13844        )
13845        .await;
13846        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13847
13848        // The window: the client is closing, its sink is still open, and its
13849        // second bind is still pending.
13850        assert!(forwarding
13851            .escalate_client_delivery_failure(
13852                dying_client,
13853                first_channel,
13854                first_epoch,
13855                CloseReason::new(
13856                    "module_to_client_delivery_failed",
13857                    "client egress refused a module frame",
13858                ),
13859                crate::forwarding::UndeliveredFrame {
13860                    module_id: None,
13861                    sink: &dying_ctx.egress,
13862                },
13863            )
13864            .unwrap());
13865        assert!(!dying_ctx.egress.is_closed());
13866
13867        // The frame that used to end the module connection.
13868        let ack = handler
13869            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13870            .await;
13871        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13872        if module_loop_error.is_some() {
13873            // What the server's connection loop does with a router error that has
13874            // no ERROR-frame translation: end the connection, which releases the
13875            // module's registration and every route on it.
13876            handler.cleanup_connection(module_connection).unwrap();
13877        }
13878        // Read the module's next frame before opening the co-tenant's route, so
13879        // the GOODBYE assertion below is about THIS ack and not about later
13880        // traffic. `None` means the module was told nothing.
13881        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13882            .await
13883            .ok()
13884            .flatten();
13885
13886        // 1. The module connection is still registered.
13887        assert!(
13888            registry
13889                .get_module_by_connection(module_connection)
13890                .unwrap()
13891                .is_some(),
13892            "one client's closing connection ended the shared module connection: \
13893             {module_loop_error:?}"
13894        );
13895        // ...and still serving: another client can open and use a route on it.
13896        let cotenant = ConnectionId::new(32);
13897        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13898        let (cotenant_task, cotenant_bind) = relay_route_open(
13899            &handler,
13900            cotenant,
13901            &cotenant_ctx.egress,
13902            &mut module_rx,
13903            102,
13904            "aft",
13905            "closing-cotenant",
13906        )
13907        .await;
13908        handler
13909            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13910            .await
13911            .unwrap();
13912        assert!(cotenant_task.await.unwrap().is_empty());
13913        let (cotenant_channel, cotenant_epoch) =
13914            published_route(&cotenant_rx.recv().await.unwrap());
13915        assert!(matches!(
13916            forwarding
13917                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13918                .unwrap(),
13919            DataRoute::Client(DataRouteState::Bound(_))
13920        ));
13921
13922        // 2. The module was told to drop the binding it created for the route
13923        //    that will never be published.
13924        let goodbye = post_ack_module_frame
13925            .expect("module receives a GOODBYE for the abandoned route channel");
13926        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13927        assert_eq!(goodbye.header.channel, abandoned_channel);
13928        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13929
13930        // 3. The dying client received nothing: no route was ever published to
13931        //    it. Its route.open is answered as unavailable, which the connection
13932        //    loop would write to a socket that is already going away.
13933        assert!(dying_rx.try_recv().is_err());
13934        let second_response = second_task.await.unwrap();
13935        assert_eq!(second_response.len(), 1);
13936        assert_eq!(
13937            parse_error(&second_response[0])["code"],
13938            "target_unavailable"
13939        );
13940    }
13941
13942    /// One `catalog.list` as a client sees it: the generation and the listed
13943    /// module ids with their readiness.
13944    async fn catalog_snapshot(
13945        handler: &ControlHandler,
13946        client_ctx: &RouteCtx,
13947        corr: u64,
13948    ) -> (u64, Vec<(String, bool)>) {
13949        let body =
13950            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13951        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13952        let reply = handler
13953            .handle_control_frame(client_ctx, request)
13954            .await
13955            .unwrap()
13956            .pop()
13957            .unwrap();
13958        let ClientControlResponse::CatalogList {
13959            generation,
13960            modules,
13961            ..
13962        } = serde_json::from_slice(&reply.body).unwrap()
13963        else {
13964            panic!("not a catalog.list reply");
13965        };
13966        (
13967            generation,
13968            modules
13969                .into_iter()
13970                .map(|entry| (entry.module_id, entry.ready))
13971                .collect(),
13972        )
13973    }
13974
13975    /// A handler whose HELLO for module "aft" on connection 40 is parked
13976    /// between reserving its registry entry and installing its forwarding
13977    /// endpoint. Returns the handler, the two-party barrier (wait once to know
13978    /// the HELLO is parked, once more to release it), the HELLO's thread, and
13979    /// the module's context and receiver.
13980    fn hello_held_before_forwarding() -> (
13981        ControlHandler,
13982        Arc<std::sync::Barrier>,
13983        std::thread::JoinHandle<Vec<Frame>>,
13984        RouteCtx,
13985        mpsc::Receiver<crate::router::OutboundFrame>,
13986    ) {
13987        let hold = Arc::new(std::sync::Barrier::new(2));
13988        let handler = ControlHandler::with_forwarding(
13989            Arc::new(Registry::default()),
13990            Arc::new(ForwardingTable::default()),
13991        )
13992        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
13993        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
13994        let hello = {
13995            let handler = handler.clone();
13996            let module_ctx = module_ctx.clone();
13997            std::thread::spawn(move || {
13998                handler
13999                    .handle_hello(
14000                        module_ctx.connection_id,
14001                        Some(module_ctx.egress.clone()),
14002                        hello_frame("aft", PROTOCOL_VERSION, 7),
14003                    )
14004                    .unwrap()
14005            })
14006        };
14007        (handler, hold, hello, module_ctx, module_rx)
14008    }
14009
14010    /// If a lookup can acquire the registry while publication is parked, let
14011    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
14012    /// after the lookup has tried the lock. Both schedules avoid timing guesses
14013    /// and return the actual lookup result, including an unpublished snapshot
14014    /// when the publication lock is missing.
14015    fn lookup_during_hello_publication<T: Send + 'static>(
14016        registry: &Registry,
14017        hold: &std::sync::Barrier,
14018        lookup: impl FnOnce() -> T + Send + 'static,
14019    ) -> T {
14020        let attempted = registry.observe_next_lock_attempt();
14021        let reader = std::thread::spawn(lookup);
14022        if attempted.recv().unwrap() {
14023            let result = reader.join().unwrap();
14024            hold.wait();
14025            result
14026        } else {
14027            hold.wait();
14028            reader.join().unwrap()
14029        }
14030    }
14031
14032    #[test]
14033    fn catalog_read_after_hello_ack_waits_for_publication() {
14034        let registry = Arc::new(Registry::default());
14035        let hold = Arc::new(std::sync::Barrier::new(2));
14036        let mut handler = ControlHandler::with_forwarding(
14037            Arc::clone(&registry),
14038            Arc::new(ForwardingTable::default()),
14039        );
14040        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
14041        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14042        let hello = {
14043            let handler = handler.clone();
14044            std::thread::spawn(move || {
14045                handler
14046                    .handle_hello(
14047                        module_ctx.connection_id,
14048                        Some(module_ctx.egress),
14049                        hello_frame("aft", PROTOCOL_VERSION, 7),
14050                    )
14051                    .unwrap()
14052            })
14053        };
14054        hold.wait();
14055        assert_eq!(
14056            module_rx.try_recv().unwrap().frame.header.ty,
14057            FrameType::HelloAck
14058        );
14059        let replies = lookup_during_hello_publication(&registry, &hold, move || {
14060            // A different connection can issue catalog.list as soon as the
14061            // module has read its ACK, even while HELLO has not returned.
14062            let request = Frame::build(
14063                FrameType::Request,
14064                control_flags(),
14065                0,
14066                0,
14067                300,
14068                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
14069            )
14070            .unwrap();
14071            handler.handle_catalog_list(request, None).unwrap()
14072        });
14073        assert!(hello.join().unwrap().is_empty());
14074        let ClientControlResponse::CatalogList {
14075            generation,
14076            modules,
14077            ..
14078        } = serde_json::from_slice(&replies[0].body).unwrap()
14079        else {
14080            panic!("not a catalog.list reply");
14081        };
14082        assert_eq!(
14083            modules
14084                .iter()
14085                .map(|entry| entry.module_id.as_str())
14086                .collect::<Vec<_>>(),
14087            vec!["aft"]
14088        );
14089        assert_eq!(generation, 1);
14090    }
14091
14092    /// While a HELLO has reserved its registry entry but its forwarding
14093    /// endpoint is not installed yet, `route.open` to the module can only be
14094    /// refused. `catalog.list` must not list the module in that window: a
14095    /// client that opens a route as soon as it sees a module listed and ready
14096    /// would be refused for a module the daemon had just advertised. The
14097    /// refusal in the window stays the retryable `target_unavailable`, never
14098    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14099    /// Once the HELLO completes, the module is listed and a route to it opens.
14100    #[tokio::test]
14101    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14102        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14103        let client = ConnectionId::new(41);
14104        let (client_ctx, mut client_rx) = route_ctx(client);
14105
14106        hold.wait();
14107        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14108        assert!(handler.registry.get_module("aft").unwrap().is_some());
14109        assert!(!handler
14110            .forwarding
14111            .has_live_module_connection("aft")
14112            .unwrap());
14113        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14114        assert!(
14115            listed.is_empty(),
14116            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14117        );
14118        let refused = handler
14119            .handle_control_frame(
14120                &client_ctx,
14121                route_open_frame(301, "aft", unique_project_root("listed-window")),
14122            )
14123            .await
14124            .unwrap();
14125        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14126        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14127        let duplicate = handler
14128            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14129            .await
14130            .unwrap();
14131        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14132
14133        hold.wait();
14134        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14135        let ack = module_rx.try_recv().unwrap().frame;
14136        assert_eq!(ack.header.ty, FrameType::HelloAck);
14137        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14138        assert_eq!(listed, vec![("aft".to_string(), true)]);
14139
14140        let (open_task, bind) = relay_route_open(
14141            &handler,
14142            client,
14143            &client_ctx.egress,
14144            &mut module_rx,
14145            303,
14146            "aft",
14147            "listed-after",
14148        )
14149        .await;
14150        assert!(handler
14151            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14152            .await
14153            .unwrap()
14154            .is_empty());
14155        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14156        published_route(&client_rx.try_recv().unwrap().frame);
14157    }
14158
14159    /// A catalog watcher keys on the generation: when it changes, it re-reads
14160    /// the listing. So the generation must advance exactly when the module
14161    /// appears. If it advanced while the module was still hidden, a watcher
14162    /// would read the new generation without the module, and the module would
14163    /// later appear under that same generation with nothing telling the
14164    /// watcher to look again.
14165    #[tokio::test]
14166    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14167        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14168        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14169        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14170
14171        hold.wait();
14172        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14173        assert!(listed.is_empty());
14174        assert_eq!(
14175            during, before,
14176            "the generation moved while the module was not listed"
14177        );
14178
14179        hold.wait();
14180        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14181        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14182        assert_eq!(listed, vec![("aft".to_string(), true)]);
14183        assert_eq!(
14184            after,
14185            before + 1,
14186            "the module appeared without exactly one generation bump"
14187        );
14188    }
14189
14190    /// A HELLO whose forwarding endpoint cannot be installed (here the
14191    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14192    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14193    /// and the catalog generation where it was.
14194    #[tokio::test]
14195    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14196        let registry = Arc::new(Registry::default());
14197        let handler = ControlHandler::with_forwarding(
14198            Arc::clone(&registry),
14199            Arc::new(ForwardingTable::default()),
14200        );
14201        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14202        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14203        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14204        drop(module_rx);
14205
14206        let replies = handler
14207            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14208            .await
14209            .unwrap();
14210        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14211        assert!(registry.get_module("aft").unwrap().is_none());
14212        assert!(registry
14213            .get_module_by_connection(module_ctx.connection_id)
14214            .unwrap()
14215            .is_none());
14216        assert_eq!(
14217            catalog_snapshot(&handler, &client_ctx, 301).await,
14218            (before, Vec::new())
14219        );
14220    }
14221
14222    /// A handler whose `route.open` parks after queueing the route.bind and
14223    /// before marking it enqueued, with module "aft" registered on connection
14224    /// 40. Returns the two-party barrier that parks and releases it.
14225    async fn route_open_held_after_bind_send() -> (
14226        ControlHandler,
14227        Arc<tokio::sync::Barrier>,
14228        RouteCtx,
14229        mpsc::Receiver<crate::router::OutboundFrame>,
14230    ) {
14231        let hold = Arc::new(tokio::sync::Barrier::new(2));
14232        let handler = ControlHandler::with_forwarding(
14233            Arc::new(Registry::default()),
14234            Arc::new(ForwardingTable::default()),
14235        )
14236        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14237        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14238        hello_via_sink(
14239            &handler,
14240            &module_ctx,
14241            &mut module_rx,
14242            hello_frame("aft", PROTOCOL_VERSION, 7),
14243        )
14244        .await;
14245        (handler, hold, module_ctx, module_rx)
14246    }
14247
14248    /// A fast module acks the route.bind, and the reader commits the route,
14249    /// before `route.open` has marked the relay enqueued. The daemon used to
14250    /// read the missing relay as an abandoned bind and send the module a
14251    /// GOODBYE for the route it had just committed: the client was told its
14252    /// route was open, the module unbound the channel, and the client's first
14253    /// request was dropped on the module side as unbound.
14254    #[tokio::test]
14255    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14256        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14257        let client = ConnectionId::new(41);
14258        let (client_ctx, mut client_rx) = route_ctx(client);
14259
14260        let (open_task, bind) = relay_route_open(
14261            &handler,
14262            client,
14263            &client_ctx.egress,
14264            &mut module_rx,
14265            200,
14266            "aft",
14267            "acked-before-mark",
14268        )
14269        .await;
14270        let (module_channel, module_epoch) = route_bind_channel(&bind);
14271        // route.open is now parked between queueing the bind and marking it.
14272        hold.wait().await;
14273
14274        // The module answers inside that window, and the route commits.
14275        assert!(handler
14276            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14277            .await
14278            .unwrap()
14279            .is_empty());
14280        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14281
14282        hold.wait().await;
14283        assert!(
14284            open_task.await.unwrap().is_empty(),
14285            "route.open answers accepted"
14286        );
14287
14288        // Every frame route.open could have sent is already queued, because it
14289        // has returned; the module must have been sent nothing.
14290        match module_rx.try_recv() {
14291            Err(mpsc::error::TryRecvError::Empty) => {}
14292            Ok(outbound) => panic!(
14293                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14294                outbound.frame.header.ty,
14295                outbound.frame.header.channel,
14296                outbound.frame.header.epoch
14297            ),
14298            Err(err) => panic!("module egress closed: {err}"),
14299        }
14300
14301        // The client's first request on the route is the next thing the module
14302        // reads, on the binding it just created.
14303        let router = Router::with_control_handler(Arc::new(handler.clone()));
14304        let request = Frame::build(
14305            FrameType::Request,
14306            Flags::new(true, Priority::Interactive, false),
14307            client_channel,
14308            client_epoch,
14309            201,
14310            b"first request".to_vec(),
14311        )
14312        .unwrap();
14313        router
14314            .route_for_connection(&client_ctx, request)
14315            .await
14316            .unwrap();
14317        let delivered = module_rx.try_recv().unwrap().frame;
14318        assert_eq!(delivered.header.ty, FrameType::Request);
14319        assert_eq!(
14320            (delivered.header.channel, delivered.header.epoch),
14321            (module_channel, module_epoch)
14322        );
14323        assert_eq!(delivered.body, b"first request");
14324    }
14325
14326    /// The client goes away while `route.open` is still queueing the bind, so
14327    /// the relay is dropped with no module reply. The teardown cannot send the
14328    /// GOODBYE itself (it could reach the module ahead of the bind), so
14329    /// `route.open` must send it once the bind is queued; otherwise the module
14330    /// keeps a binding the daemon will never commit.
14331    #[tokio::test]
14332    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14333        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14334        let client = ConnectionId::new(42);
14335        let (client_ctx, _client_rx) = route_ctx(client);
14336
14337        let (open_task, bind) = relay_route_open(
14338            &handler,
14339            client,
14340            &client_ctx.egress,
14341            &mut module_rx,
14342            300,
14343            "aft",
14344            "released-before-mark",
14345        )
14346        .await;
14347        let (module_channel, module_epoch) = route_bind_channel(&bind);
14348        hold.wait().await;
14349
14350        handler.cleanup_connection(client).unwrap();
14351        assert!(
14352            module_rx.try_recv().is_err(),
14353            "client teardown must not GOODBYE a bind route.open is still queueing"
14354        );
14355
14356        hold.wait().await;
14357        let response = open_task.await.unwrap();
14358        assert_eq!(response.len(), 1);
14359        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14360
14361        let goodbye = module_rx
14362            .try_recv()
14363            .expect("module is told to drop the binding the daemon abandoned")
14364            .frame;
14365        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14366        assert_eq!(
14367            (goodbye.header.channel, goodbye.header.epoch),
14368            (module_channel, module_epoch)
14369        );
14370        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14371    }
14372
14373    /// The module acks inside the same window, but the client's egress closed
14374    /// first, so the reader refuses to commit. The ack proves the module holds
14375    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14376    /// send a second one.
14377    #[tokio::test]
14378    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14379        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14380        let client = ConnectionId::new(43);
14381        let (client_ctx, client_rx) = route_ctx(client);
14382
14383        let (open_task, bind) = relay_route_open(
14384            &handler,
14385            client,
14386            &client_ctx.egress,
14387            &mut module_rx,
14388            400,
14389            "aft",
14390            "gone-client-before-mark",
14391        )
14392        .await;
14393        let (module_channel, module_epoch) = route_bind_channel(&bind);
14394        hold.wait().await;
14395
14396        drop(client_rx);
14397        assert!(client_ctx.egress.is_closed());
14398        handler
14399            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14400            .await
14401            .unwrap();
14402
14403        hold.wait().await;
14404        let response = open_task.await.unwrap();
14405        assert_eq!(response.len(), 1);
14406        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14407
14408        let goodbye = module_rx
14409            .try_recv()
14410            .expect("module is told to drop the binding it acked")
14411            .frame;
14412        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14413        assert_eq!(
14414            (goodbye.header.channel, goodbye.header.epoch),
14415            (module_channel, module_epoch)
14416        );
14417        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14418        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14419    }
14420
14421    /// The fence at the module-loop boundary, stated as its own contract: which
14422    /// forwarding failures are allowed to end the module connection that is being
14423    /// served. A `ConnectionClosing` naming some client is about that client, and
14424    /// a module connection is shared; the same error naming the module's own
14425    /// connection is about this connection and must stay fatal, as must failures
14426    /// that are about the forwarding table itself.
14427    #[test]
14428    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14429        let handler = ControlHandler::default();
14430        let module_connection = ConnectionId::new(30);
14431        let client_connection = ConnectionId::new(31);
14432
14433        handler
14434            .refuse_to_end_module_connection_for_a_client(
14435                module_connection,
14436                77,
14437                ForwardingError::ConnectionClosing {
14438                    connection_id: client_connection,
14439                },
14440            )
14441            .expect("a closing client must never end the module connection");
14442
14443        assert!(matches!(
14444            handler.refuse_to_end_module_connection_for_a_client(
14445                module_connection,
14446                78,
14447                ForwardingError::ConnectionClosing {
14448                    connection_id: module_connection,
14449                },
14450            ),
14451            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14452                connection_id
14453            })) if connection_id == module_connection
14454        ));
14455        assert!(matches!(
14456            handler.refuse_to_end_module_connection_for_a_client(
14457                module_connection,
14458                79,
14459                ForwardingError::Poisoned,
14460            ),
14461            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14462        ));
14463        assert!(matches!(
14464            handler.refuse_to_end_module_connection_for_a_client(
14465                module_connection,
14466                80,
14467                ForwardingError::StaleModuleEndpoint,
14468            ),
14469            Err(RouterError::Forwarding(
14470                ForwardingError::StaleModuleEndpoint
14471            ))
14472        ));
14473    }
14474
14475    /// The spawn-attestation guard is what stops a connected module from claiming
14476    /// another module's identity and being stamped `Reserved` for it. Every other
14477    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14478    /// correct one is what the rest of the flow needs -- so the guard's rejection
14479    /// branch was never the subject of an assertion, only its acceptance branch.
14480    ///
14481    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14482    /// whole subc-core library suite green; only the forwarding integration tests
14483    /// notice, and they notice for unrelated reasons. This test exists so the
14484    /// refusal itself is asserted where the guard lives: it fails if the identity
14485    /// check stops refusing, which is the direction that matters, since a guard
14486    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14487    #[tokio::test]
14488    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14489        let registry = Arc::new(Registry::default());
14490        let forwarding = Arc::new(ForwardingTable::default());
14491        let supervisor = SupervisorHandle::new();
14492        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14493        let handler =
14494            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14495                .with_supervisor(supervisor);
14496
14497        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14498        hello_via_sink(
14499            &handler,
14500            &target_ctx,
14501            &mut target_rx,
14502            hello_frame("target", PROTOCOL_VERSION, 1),
14503        )
14504        .await;
14505
14506        // A real supervised module id presenting the wrong nonce. This is the
14507        // impersonation case: the attacker knows a privileged module_id, which is
14508        // public, and guesses at the nonce, which is not.
14509        let wrong_nonce = handler
14510            .handle_control_frame(
14511                &route_ctx(ConnectionId::new(91)).0,
14512                route_open_frame_with_admission_facts(
14513                    20,
14514                    "target",
14515                    unique_project_root("admission-facts"),
14516                    Some(subc_control::ConsumerIdentity {
14517                        module_id: "fed".to_string(),
14518                        launch_nonce: "not-the-real-nonce".to_string(),
14519                    }),
14520                    None,
14521                ),
14522            )
14523            .await
14524            .unwrap();
14525        assert_eq!(
14526            parse_error(&wrong_nonce[0])["code"],
14527            "bad_consumer_identity",
14528            "a mismatched launch nonce must be refused, not stamped Reserved"
14529        );
14530
14531        // A module id the supervisor never spawned at all, so no nonce exists to
14532        // compare against. An implementation that treats "no record" as "nothing
14533        // to check" fails open here while passing the case above.
14534        let never_spawned = handler
14535            .handle_control_frame(
14536                &route_ctx(ConnectionId::new(92)).0,
14537                route_open_frame_with_admission_facts(
14538                    21,
14539                    "target",
14540                    unique_project_root("admission-facts"),
14541                    Some(subc_control::ConsumerIdentity {
14542                        module_id: "never-spawned".to_string(),
14543                        launch_nonce: "any-nonce".to_string(),
14544                    }),
14545                    None,
14546                ),
14547            )
14548            .await
14549            .unwrap();
14550        assert_eq!(
14551            parse_error(&never_spawned[0])["code"],
14552            "bad_consumer_identity",
14553            "an unspawned module_id must be refused rather than accepted for lack of a record"
14554        );
14555    }
14556
14557    /// The refusal test above proves the guard says NO. Nothing proved it can say
14558    /// YES, and the difference is not academic: replacing the whole authorization
14559    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14560    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14561    /// library tests GREEN. The one that notices does so by HANGING, because it
14562    /// waits for a bind that can no longer happen.
14563    ///
14564    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14565    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14566    /// hangs too and gets blamed on the runner. So a total revocation of the
14567    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14568    /// to code.
14569    ///
14570    /// The bias is structural rather than accidental. A REFUSAL looks like a
14571    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14572    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14573    /// suite for that reason, and this one is the purest case in the daemon.
14574    ///
14575    /// This test asserts the EFFECT rather than the absence of an error: the module
14576    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14577    /// A guard that admitted nobody would produce no bind at all; one that admitted
14578    /// everybody would stamp the wrong principal, which the refusal test catches.
14579    #[tokio::test]
14580    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14581        let registry = Arc::new(Registry::default());
14582        let forwarding = Arc::new(ForwardingTable::default());
14583        let supervisor = SupervisorHandle::new();
14584        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14585        let handler =
14586            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14587                .with_supervisor(supervisor);
14588
14589        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14590        hello_via_sink(
14591            &handler,
14592            &target_ctx,
14593            &mut target_rx,
14594            hello_frame("target", PROTOCOL_VERSION, 1),
14595        )
14596        .await;
14597
14598        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14599        let route_handler = handler.clone();
14600        let route_task = tokio::spawn(async move {
14601            route_handler
14602                .handle_control_frame(
14603                    &client_ctx,
14604                    route_open_frame_with_admission_facts(
14605                        30,
14606                        "target",
14607                        unique_project_root("admission-facts"),
14608                        Some(subc_control::ConsumerIdentity {
14609                            module_id: "fed".to_string(),
14610                            launch_nonce: "fed-nonce".to_string(),
14611                        }),
14612                        None,
14613                    ),
14614                )
14615                .await
14616                .unwrap()
14617        });
14618
14619        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14620        // the very mutation it exists to catch -- a guard that admits nobody -- no
14621        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14622        // exact defect being fixed: a total revocation detected only as a stalled
14623        // suite, which reads as flakiness and invites a retry. An acceptance test
14624        // that waits for an effect must bound the wait, or a red becomes a hang.
14625        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14626            .await
14627            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14628            .expect("module control channel closed before route.bind");
14629        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14630        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14631            panic!("expected route.bind")
14632        };
14633        assert_eq!(
14634            principal,
14635            Some(Principal::Reserved {
14636                module_id: "fed".to_string()
14637            }),
14638            "a correctly attested consumer must be stamped Reserved for its own id"
14639        );
14640
14641        handler
14642            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14643            .await
14644            .unwrap();
14645        assert!(route_task.await.unwrap().is_empty());
14646        assert!(
14647            matches!(
14648                serde_json::from_slice::<ClientControlResponse>(
14649                    &client_rx.recv().await.unwrap().body
14650                )
14651                .unwrap(),
14652                ClientControlResponse::RouteOpen { .. }
14653            ),
14654            "the route must actually open, not merely avoid an error"
14655        );
14656    }
14657
14658    #[tokio::test(start_paused = true)]
14659    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14660        let registry = Arc::new(Registry::default());
14661        let forwarding = Arc::new(ForwardingTable::default());
14662        let supervisor = SupervisorHandle::new();
14663        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14664        let handler =
14665            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14666                .with_supervisor(supervisor);
14667
14668        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14669        hello_via_sink(
14670            &handler,
14671            &target_ctx,
14672            &mut target_rx,
14673            hello_frame("target", PROTOCOL_VERSION, 1),
14674        )
14675        .await;
14676
14677        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14678        let direct_handler = handler.clone();
14679        let direct_open = tokio::spawn(async move {
14680            direct_handler
14681                .handle_control_frame(
14682                    &direct_ctx,
14683                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14684                )
14685                .await
14686                .unwrap()
14687        });
14688        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14689            .await
14690            .expect("no direct route.bind within 5s")
14691            .expect("target control channel closed before direct route.bind");
14692        handler
14693            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14694            .await
14695            .unwrap();
14696        assert!(direct_open.await.unwrap().is_empty());
14697        let _ = direct_rx.recv().await.unwrap();
14698
14699        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14700        let reserved_handler = handler.clone();
14701        let reserved_open = tokio::spawn(async move {
14702            reserved_handler
14703                .handle_control_frame(
14704                    &reserved_ctx,
14705                    route_open_frame_with_admission_facts(
14706                        3,
14707                        "target",
14708                        unique_project_root("admission-facts"),
14709                        Some(ConsumerIdentity {
14710                            module_id: "fed".to_string(),
14711                            launch_nonce: "fed-nonce".to_string(),
14712                        }),
14713                        None,
14714                    ),
14715                )
14716                .await
14717                .unwrap()
14718        });
14719        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14720            .await
14721            .expect("no reserved route.bind within 5s")
14722            .expect("target control channel closed before reserved route.bind");
14723        handler
14724            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14725            .await
14726            .unwrap();
14727        assert!(reserved_open.await.unwrap().is_empty());
14728        let _ = reserved_rx.recv().await.unwrap();
14729
14730        forwarding
14731            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14732            .unwrap();
14733        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14734        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14735            module_id: Some("target".to_string()),
14736        })
14737        .unwrap();
14738        let census_frame =
14739            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14740        let response = handler
14741            .handle_control_frame(&census_ctx, census_frame)
14742            .await
14743            .unwrap()
14744            .pop()
14745            .unwrap();
14746        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14747        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14748        assert!(matches!(
14749            decoded,
14750            ClientControlResponse::SupervisorRoutes { .. }
14751        ));
14752        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14753        assert_eq!(routes.len(), 2);
14754        assert!(routes.iter().all(|route| route["draining"] == true));
14755        // The census carries WHY: the reason the drain was begun with, in the
14756        // route.closing vocabulary, on every draining route this drain marked.
14757        assert!(
14758            routes.iter().all(|route| route["drain_reason"] == "reload"),
14759            "draining routes must name the drain's reason: {routes:?}"
14760        );
14761        assert!(routes.iter().any(|route| {
14762            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14763        }));
14764        assert!(routes.iter().any(|route| {
14765            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14766        }));
14767
14768        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14769            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14770        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14771            std::fs::write(
14772                &golden_path,
14773                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14774            )
14775            .unwrap();
14776        }
14777        let expected: Value =
14778            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14779        assert_eq!(actual, expected);
14780    }
14781
14782    async fn query_live_roots(
14783        handler: &ControlHandler,
14784        module_ctx: &RouteCtx,
14785    ) -> ModuleControlResponseToModule {
14786        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14787        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14788        let response = handler
14789            .handle_control_frame(module_ctx, frame)
14790            .await
14791            .unwrap()
14792            .pop()
14793            .unwrap();
14794        serde_json::from_slice(&response.body).unwrap()
14795    }
14796
14797    #[tokio::test(start_paused = true)]
14798    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14799        let registry = Arc::new(Registry::default());
14800        let forwarding = Arc::new(ForwardingTable::default());
14801        let handler = ControlHandler::with_forwarding(registry, forwarding);
14802        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14803        hello_via_sink(
14804            &handler,
14805            &target_ctx,
14806            &mut target_rx,
14807            hello_frame("target", PROTOCOL_VERSION, 1),
14808        )
14809        .await;
14810        let root = unique_project_root("live-roots-known");
14811        let path = ProjectRootId::from_path_allowing_missing(root.path())
14812            .unwrap()
14813            .as_path()
14814            .to_path_buf();
14815        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14816        let open_handler = handler.clone();
14817        let opened = tokio::spawn(async move {
14818            open_handler
14819                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14820                .await
14821                .unwrap()
14822        });
14823        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14824            .await
14825            .unwrap()
14826            .unwrap();
14827        handler
14828            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14829            .await
14830            .unwrap();
14831        assert!(opened.await.unwrap().is_empty());
14832        let _ = client_rx.recv().await.unwrap();
14833
14834        let root = unique_project_root("live-roots-pending");
14835        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14836            .unwrap()
14837            .as_path()
14838            .to_path_buf();
14839        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14840        let open_handler = handler.clone();
14841        let pending = tokio::spawn(async move {
14842            open_handler
14843                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14844                .await
14845                .unwrap()
14846        });
14847        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14848            .await
14849            .unwrap()
14850            .unwrap();
14851        let actual = query_live_roots(&handler, &target_ctx).await;
14852        let ModuleControlResponseToModule::LiveRoots {
14853            roots,
14854            unknown_root_bindings,
14855            total_bindings,
14856        } = actual
14857        else {
14858            panic!("expected live roots")
14859        };
14860        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14861        assert_eq!(unknown_root_bindings, 0);
14862        assert_eq!(
14863            roots.len(),
14864            2,
14865            "root-known arm must retain each canonical root"
14866        );
14867        assert_eq!(
14868            total_bindings,
14869            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14870        );
14871        let counts = roots
14872            .iter()
14873            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14874            .collect::<Vec<_>>();
14875        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14876        expected.sort_by(|a, b| a.0.cmp(&b.0));
14877        assert_eq!(
14878            counts, expected,
14879            "roots must sort by path and count pending separately"
14880        );
14881        handler
14882            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14883            .await
14884            .unwrap();
14885        assert!(pending.await.unwrap().is_empty());
14886    }
14887
14888    #[tokio::test(start_paused = true)]
14889    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14890        let forwarding = Arc::new(ForwardingTable::default());
14891        let handler =
14892            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14893        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14894        hello_via_sink(
14895            &handler,
14896            &target_ctx,
14897            &mut target_rx,
14898            hello_frame("target", PROTOCOL_VERSION, 1),
14899        )
14900        .await;
14901        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14902        let pending = forwarding
14903            .begin_route_bind_relay_for_test(
14904                client_ctx.connection_id,
14905                client_ctx.egress.clone(),
14906                2,
14907                "target",
14908            )
14909            .unwrap();
14910        forwarding
14911            .complete_pending_relay(
14912                target_ctx.connection_id,
14913                pending.corr,
14914                RouteBindRelayOutcome::Accepted,
14915            )
14916            .unwrap();
14917        let actual = query_live_roots(&handler, &target_ctx).await;
14918        let ModuleControlResponseToModule::LiveRoots {
14919            roots,
14920            unknown_root_bindings,
14921            total_bindings,
14922        } = actual
14923        else {
14924            panic!("expected live roots")
14925        };
14926        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14927        assert_eq!(
14928            unknown_root_bindings, 1,
14929            "unknown-root arm must not read as no bindings"
14930        );
14931        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14932        assert_eq!(
14933            total_bindings,
14934            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14935        );
14936    }
14937
14938    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14939    /// so the ack has to be on its outbound queue before the module is
14940    /// routable. The connection loop writes a handler's replies only after the
14941    /// handler returns; this test stops in exactly that gap, runs a real
14942    /// route.open from another connection, and only then writes whatever the
14943    /// HELLO handler returned, the way the loop would. If the ack were still a
14944    /// reply, the route.bind request would reach the module first.
14945    #[tokio::test(start_paused = true)]
14946    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14947        let forwarding = Arc::new(ForwardingTable::default());
14948        let handler =
14949            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14950        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14951        let replies = handler
14952            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14953            .await
14954            .unwrap();
14955        let queued_by_hello = module_rx.len();
14956
14957        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14958        let open_handler = handler.clone();
14959        let open = tokio::spawn(async move {
14960            open_handler
14961                .handle_control_frame(
14962                    &client_ctx,
14963                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14964                )
14965                .await
14966                .unwrap()
14967        });
14968        // Let the route.open run until its route.bind is on the module's queue.
14969        let mut spins = 0;
14970        while module_rx.len() == queued_by_hello {
14971            spins += 1;
14972            assert!(spins < 10_000, "route.open never queued a route.bind");
14973            tokio::task::yield_now().await;
14974        }
14975
14976        // Now the connection loop's half: write the HELLO handler's replies.
14977        for reply in replies {
14978            module_ctx.egress.send(reply).await.unwrap();
14979        }
14980
14981        let first = module_rx.recv().await.unwrap().frame;
14982        assert_eq!(
14983            first.header.ty,
14984            FrameType::HelloAck,
14985            "the first frame a registering module reads must be its HELLO_ACK"
14986        );
14987        assert_eq!(first.header.corr, 7);
14988        let second = module_rx.recv().await.unwrap().frame;
14989        assert_eq!(second.header.ty, FrameType::Request);
14990        assert!(
14991            matches!(
14992                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
14993                ModuleControlRequest::RouteBind { .. }
14994            ),
14995            "the route.bind follows the ack"
14996        );
14997        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
14998
14999        handler
15000            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
15001            .await
15002            .unwrap();
15003        assert!(open.await.unwrap().is_empty());
15004        let _ = client_rx.recv().await.unwrap();
15005    }
15006
15007    #[tokio::test(start_paused = true)]
15008    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
15009        let handler = ControlHandler::with_forwarding(
15010            Arc::new(Registry::default()),
15011            Arc::new(ForwardingTable::default()),
15012        );
15013        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
15014        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
15015        hello_via_sink(
15016            &handler,
15017            &first_ctx,
15018            &mut first_rx,
15019            hello_frame("first", PROTOCOL_VERSION, 1),
15020        )
15021        .await;
15022        hello_via_sink(
15023            &handler,
15024            &second_ctx,
15025            &mut second_rx,
15026            hello_frame("second", PROTOCOL_VERSION, 2),
15027        )
15028        .await;
15029        let root = unique_project_root("second-only");
15030        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
15031        let cloned = handler.clone();
15032        let open = tokio::spawn(async move {
15033            cloned
15034                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
15035                .await
15036                .unwrap()
15037        });
15038        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
15039            .await
15040            .unwrap()
15041            .unwrap();
15042        let first = query_live_roots(&handler, &first_ctx).await;
15043        let second = query_live_roots(&handler, &second_ctx).await;
15044        assert!(
15045            matches!(
15046                first,
15047                ModuleControlResponseToModule::LiveRoots {
15048                    total_bindings: 0,
15049                    ..
15050                }
15051            ),
15052            "cross-module scope must not expose another module's roots"
15053        );
15054        assert!(
15055            matches!(
15056                second,
15057                ModuleControlResponseToModule::LiveRoots {
15058                    total_bindings: 1,
15059                    ..
15060                }
15061            ),
15062            "second module must see its pending route"
15063        );
15064        handler
15065            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
15066            .await
15067            .unwrap();
15068        assert!(open.await.unwrap().is_empty());
15069    }
15070
15071    #[tokio::test(start_paused = true)]
15072    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
15073        let handler = ControlHandler::with_forwarding(
15074            Arc::new(Registry::default()),
15075            Arc::new(ForwardingTable::default()),
15076        );
15077        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15078        hello_via_sink(
15079            &handler,
15080            &target_ctx,
15081            &mut target_rx,
15082            hello_frame("target", PROTOCOL_VERSION, 1),
15083        )
15084        .await;
15085        let actual = query_live_roots(&handler, &target_ctx).await;
15086        let ModuleControlResponseToModule::LiveRoots {
15087            roots,
15088            unknown_root_bindings,
15089            total_bindings,
15090        } = actual
15091        else {
15092            panic!("expected live roots")
15093        };
15094        assert!(roots.is_empty());
15095        assert_eq!(unknown_root_bindings, 0);
15096        assert_eq!(total_bindings, 0);
15097        assert_eq!(
15098            total_bindings,
15099            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15100        );
15101    }
15102
15103    /// Read the vendored fed corpus rather than hand-building a package.
15104    ///
15105    /// A hand-built object encodes what the test author believed the carrier
15106    /// emits. These vectors are what it actually emits, and one of them exists
15107    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15108    /// ignores additive unknown fields at the traversal emit terminus."
15109    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15110        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15111            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15112        let text = std::fs::read_to_string(&path)
15113            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15114        let vectors: Vec<(String, Value)> = text
15115            .lines()
15116            .filter(|line| !line.trim().is_empty())
15117            .map(|line| {
15118                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15119                let id = entry["corpus_id"]
15120                    .as_str()
15121                    .expect("every vector carries a corpus_id")
15122                    .to_string();
15123                (id, entry["package"].clone())
15124            })
15125            .collect();
15126        // Pin the count: a corpus that silently shrinks would take its coverage
15127        // with it, and a suite reading N-1 vectors reports the same clean pass
15128        // as one reading N.
15129        assert_eq!(
15130            vectors.len(),
15131            3,
15132            "vendored fed corpus changed size; re-sync from subc-federation"
15133        );
15134
15135        // Pin what makes the corpus DISCRIMINATING, not just present.
15136        //
15137        // The relay test below takes its expected value from the corpus, so the
15138        // corpus supplies the test's power to detect a lossy relay rather than
15139        // its correctness. A relay that dropped unrecognised fields would still
15140        // be caught -- but only by a package carrying fields it does not know.
15141        // Shrink every package to the handful of keys any implementation would
15142        // recognise and the test keeps passing over an input that can no longer
15143        // fail, which is the same clean green as a corpus that shrank away.
15144        //
15145        // So assert the precondition rather than duplicating the packages here:
15146        // at least one vector must carry a field beyond the small common set.
15147        // That is one claim to maintain instead of nine, and it fails loudly if
15148        // a re-sync ever flattens the corpus.
15149        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15150        let richest = vectors
15151            .iter()
15152            .filter_map(|(_, package)| package.as_object())
15153            .map(|object| {
15154                object
15155                    .keys()
15156                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15157                    .count()
15158            })
15159            .max()
15160            .unwrap_or(0);
15161        assert!(
15162            richest >= 2,
15163            "vendored corpus no longer carries a package with unmodelled fields, \
15164             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15165        );
15166
15167        vectors
15168    }
15169
15170    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15171    ///
15172    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15173    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15174    /// three-key object, so a relay that quietly dropped fields it did not
15175    /// recognise would satisfy it. These vectors carry nine keys including ones
15176    /// this crate has no type for, so a typed relay fails here and only here.
15177    #[tokio::test]
15178    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15179        for (corpus_id, package) in fed_admission_facts_vectors() {
15180            let registry = Arc::new(Registry::default());
15181            let forwarding = Arc::new(ForwardingTable::default());
15182            let supervisor = SupervisorHandle::new();
15183            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15184            let handler =
15185                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15186                    .with_supervisor(supervisor)
15187                    .with_admission_facts_config(
15188                        Some("fed".to_string()),
15189                        Some(vec!["target".to_string()]),
15190                    );
15191
15192            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15193            hello_via_sink(
15194                &handler,
15195                &target_ctx,
15196                &mut target_rx,
15197                hello_frame("target", PROTOCOL_VERSION, 1),
15198            )
15199            .await;
15200
15201            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15202            let route_handler = handler.clone();
15203            let expected = package.clone();
15204            let route_task = tokio::spawn(async move {
15205                route_handler
15206                    .handle_control_frame(
15207                        &client_ctx,
15208                        route_open_frame_with_admission_facts(
15209                            20,
15210                            "target",
15211                            unique_project_root("admission-facts"),
15212                            Some(subc_control::ConsumerIdentity {
15213                                module_id: "fed".to_string(),
15214                                launch_nonce: "fed-nonce".to_string(),
15215                            }),
15216                            Some(package),
15217                        ),
15218                    )
15219                    .await
15220                    .unwrap()
15221            });
15222
15223            let bind_frame = target_rx.recv().await.unwrap();
15224            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15225            let ModuleControlRequest::RouteBind {
15226                admission_facts, ..
15227            } = bind
15228            else {
15229                panic!("{corpus_id}: expected route.bind")
15230            };
15231            assert_eq!(
15232                admission_facts,
15233                Some(expected),
15234                "{corpus_id}: relay must not add, drop or reshape any field"
15235            );
15236
15237            handler
15238                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15239                .await
15240                .unwrap();
15241            route_task.await.unwrap();
15242        }
15243    }
15244
15245    #[tokio::test]
15246    async fn route_bind_never_relays_the_openers_build_class() {
15247        let registry = Arc::new(Registry::default());
15248        let forwarding = Arc::new(ForwardingTable::default());
15249        let handler =
15250            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15251        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15252        hello_via_sink(
15253            &handler,
15254            &target_ctx,
15255            &mut target_rx,
15256            hello_frame("target", PROTOCOL_VERSION, 1),
15257        )
15258        .await;
15259
15260        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15261        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15262        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15263            busy_refusals: None,
15264            target: RouteTarget::ToolProvider {
15265                module_id: "target".to_string(),
15266            },
15267            identity,
15268            consumer_identity: None,
15269            consumer_capabilities: None,
15270            role_versions: None,
15271            admission_facts: None,
15272            scope: None,
15273        })
15274        .unwrap();
15275        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15276
15277        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15278        let route_handler = handler.clone();
15279        let route_task = tokio::spawn(async move {
15280            route_handler
15281                .handle_control_frame(&client_ctx, open)
15282                .await
15283                .unwrap()
15284        });
15285        let bind_frame = target_rx.recv().await.unwrap();
15286        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15287        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15288            panic!("expected route.bind")
15289        };
15290        assert_eq!(
15291            identity.build_class, None,
15292            "route.bind carried the build class"
15293        );
15294        assert!(
15295            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15296            "the route.bind bytes still name build_class"
15297        );
15298        handler
15299            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15300            .await
15301            .unwrap();
15302        route_task.await.unwrap();
15303    }
15304
15305    #[tokio::test]
15306    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15307        let registry = Arc::new(Registry::default());
15308        let forwarding = Arc::new(ForwardingTable::default());
15309        let supervisor = SupervisorHandle::new();
15310        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15311        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15312        let handler =
15313            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15314                .with_supervisor(supervisor)
15315                .with_admission_facts_config(
15316                    Some("fed".to_string()),
15317                    Some(vec!["target".to_string()]),
15318                );
15319
15320        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15321        hello_via_sink(
15322            &handler,
15323            &target_ctx,
15324            &mut target_rx,
15325            hello_frame("target", PROTOCOL_VERSION, 1),
15326        )
15327        .await;
15328        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15329        hello_via_sink(
15330            &handler,
15331            &other_ctx,
15332            &mut other_rx,
15333            hello_frame("other", PROTOCOL_VERSION, 2),
15334        )
15335        .await;
15336
15337        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15338        let expected_facts = facts.clone();
15339        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15340        let route_handler = handler.clone();
15341        let route_task = tokio::spawn(async move {
15342            route_handler
15343                .handle_control_frame(
15344                    &client_ctx,
15345                    route_open_frame_with_admission_facts(
15346                        10,
15347                        "target",
15348                        unique_project_root("admission-facts"),
15349                        Some(subc_control::ConsumerIdentity {
15350                            module_id: "fed".to_string(),
15351                            launch_nonce: "fed-nonce".to_string(),
15352                        }),
15353                        Some(facts.clone()),
15354                    ),
15355                )
15356                .await
15357                .unwrap()
15358        });
15359        let bind_frame = target_rx.recv().await.unwrap();
15360        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15361        let ModuleControlRequest::RouteBind {
15362            admission_facts, ..
15363        } = bind
15364        else {
15365            panic!("expected route.bind")
15366        };
15367        assert_eq!(admission_facts, Some(expected_facts));
15368        handler
15369            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15370            .await
15371            .unwrap();
15372        assert!(route_task.await.unwrap().is_empty());
15373        assert!(matches!(
15374            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15375                .unwrap(),
15376            ClientControlResponse::RouteOpen { .. }
15377        ));
15378
15379        let direct = handler
15380            .handle_control_frame(
15381                &route_ctx(ConnectionId::new(73)).0,
15382                route_open_frame_with_admission_facts(
15383                    11,
15384                    "target",
15385                    unique_project_root("admission-facts"),
15386                    None,
15387                    Some(json!({"x": 1})),
15388                ),
15389            )
15390            .await
15391            .unwrap();
15392        assert_eq!(
15393            parse_error(&direct[0])["code"],
15394            "admission_facts_not_permitted"
15395        );
15396
15397        let different_reserved = handler
15398            .handle_control_frame(
15399                &route_ctx(ConnectionId::new(77)).0,
15400                route_open_frame_with_admission_facts(
15401                    15,
15402                    "target",
15403                    unique_project_root("admission-facts"),
15404                    Some(subc_control::ConsumerIdentity {
15405                        module_id: "other".to_string(),
15406                        launch_nonce: "other-nonce".to_string(),
15407                    }),
15408                    Some(json!({"x": 1})),
15409                ),
15410            )
15411            .await
15412            .unwrap();
15413        assert_eq!(
15414            parse_error(&different_reserved[0])["code"],
15415            "admission_facts_not_permitted"
15416        );
15417
15418        let other_target = handler
15419            .handle_control_frame(
15420                &route_ctx(ConnectionId::new(74)).0,
15421                route_open_frame_with_admission_facts(
15422                    12,
15423                    "other",
15424                    unique_project_root("admission-facts"),
15425                    Some(subc_control::ConsumerIdentity {
15426                        module_id: "fed".to_string(),
15427                        launch_nonce: "fed-nonce".to_string(),
15428                    }),
15429                    Some(json!({"x": 1})),
15430                ),
15431            )
15432            .await
15433            .unwrap();
15434        assert_eq!(
15435            parse_error(&other_target[0])["code"],
15436            "admission_facts_target_not_allowed"
15437        );
15438
15439        let nonexistent = handler
15440            .handle_control_frame(
15441                &route_ctx(ConnectionId::new(75)).0,
15442                route_open_frame_with_admission_facts(
15443                    13,
15444                    "missing",
15445                    unique_project_root("admission-facts"),
15446                    None,
15447                    Some(json!({"x": 1})),
15448                ),
15449            )
15450            .await
15451            .unwrap();
15452        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15453
15454        let described = handler
15455            .handle_control_frame(
15456                &route_ctx(ConnectionId::new(76)).0,
15457                Frame::build(
15458                    FrameType::Request,
15459                    control_flags(),
15460                    0,
15461                    0,
15462                    14,
15463                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15464                )
15465                .unwrap(),
15466            )
15467            .await
15468            .unwrap();
15469        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15470            serde_json::from_slice(&described[0].body).unwrap()
15471        else {
15472            panic!("expected server.describe response")
15473        };
15474        assert!(capabilities
15475            .iter()
15476            .any(|cap| cap == "admission_facts_relay_v1"));
15477    }
15478
15479    #[tokio::test]
15480    async fn admission_facts_without_configured_carrier_are_rejected() {
15481        let registry = Arc::new(Registry::default());
15482        let forwarding = Arc::new(ForwardingTable::default());
15483        let handler = ControlHandler::with_forwarding(registry, forwarding);
15484        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15485        hello_via_sink(
15486            &handler,
15487            &target_ctx,
15488            &mut target_rx,
15489            hello_frame("target", PROTOCOL_VERSION, 1),
15490        )
15491        .await;
15492
15493        let responses = handler
15494            .handle_control_frame(
15495                &route_ctx(ConnectionId::new(79)).0,
15496                route_open_frame_with_admission_facts(
15497                    16,
15498                    "target",
15499                    unique_project_root("admission-facts"),
15500                    None,
15501                    Some(json!({"x": 1})),
15502                ),
15503            )
15504            .await
15505            .unwrap();
15506        assert_eq!(
15507            parse_error(&responses[0])["code"],
15508            "admission_facts_not_permitted"
15509        );
15510    }
15511
15512    #[tokio::test]
15513    async fn route_open_relays_consumer_capabilities_verbatim() {
15514        let registry = Arc::new(Registry::default());
15515        let forwarding = Arc::new(ForwardingTable::default());
15516        let handler =
15517            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15518        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15519        hello_via_sink(
15520            &handler,
15521            &module_ctx,
15522            &mut module_rx,
15523            hello_frame("aft", PROTOCOL_VERSION, 7),
15524        )
15525        .await;
15526
15527        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15528        let expected_for_request = expected.clone();
15529        let project_root = unique_project_root("consumer-capabilities-present");
15530        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15531        let route_handler = handler.clone();
15532        let route_task = tokio::spawn(async move {
15533            route_handler
15534                .handle_control_frame(
15535                    &client_ctx,
15536                    route_open_frame_with_consumer_capabilities(
15537                        401,
15538                        "aft",
15539                        project_root,
15540                        Some(expected_for_request),
15541                    ),
15542                )
15543                .await
15544                .unwrap()
15545        });
15546        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15547            .await
15548            .unwrap()
15549            .unwrap();
15550        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15551        let ModuleControlRequest::RouteBind {
15552            consumer_capabilities,
15553            ..
15554        } = bind
15555        else {
15556            panic!("expected route.bind request, got {bind:?}");
15557        };
15558        assert_eq!(consumer_capabilities, Some(expected.clone()));
15559
15560        handler
15561            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15562            .await
15563            .unwrap();
15564        let route_response = route_task.await.unwrap();
15565        assert!(route_response.is_empty());
15566        let published = client_rx.recv().await.unwrap();
15567        assert!(matches!(
15568            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15569            ClientControlResponse::RouteOpen { .. }
15570        ));
15571    }
15572
15573    #[tokio::test]
15574    async fn route_open_without_consumer_capabilities_relays_none() {
15575        let registry = Arc::new(Registry::default());
15576        let forwarding = Arc::new(ForwardingTable::default());
15577        let handler =
15578            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15579        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15580        hello_via_sink(
15581            &handler,
15582            &module_ctx,
15583            &mut module_rx,
15584            hello_frame("aft", PROTOCOL_VERSION, 7),
15585        )
15586        .await;
15587
15588        let project_root = unique_project_root("consumer-capabilities-absent");
15589        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15590        let route_handler = handler.clone();
15591        let route_task = tokio::spawn(async move {
15592            route_handler
15593                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15594                .await
15595                .unwrap()
15596        });
15597        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15598            .await
15599            .unwrap()
15600            .unwrap();
15601        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15602        let ModuleControlRequest::RouteBind {
15603            consumer_capabilities,
15604            ..
15605        } = bind
15606        else {
15607            panic!("expected route.bind request, got {bind:?}");
15608        };
15609        assert_eq!(consumer_capabilities, None);
15610
15611        handler
15612            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15613            .await
15614            .unwrap();
15615        let route_response = route_task.await.unwrap();
15616        assert!(route_response.is_empty());
15617        let published = client_rx.recv().await.unwrap();
15618        assert!(matches!(
15619            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15620            ClientControlResponse::RouteOpen { .. }
15621        ));
15622    }
15623
15624    /// Opens a route to a freshly registered `aft` with `sent` as the
15625    /// route.open's role_versions, acks the bind, and returns the role_versions
15626    /// the module's bind carried.
15627    async fn bind_role_versions_for(
15628        sent: Option<BTreeMap<String, String>>,
15629        connection: u64,
15630    ) -> Option<BTreeMap<String, String>> {
15631        let registry = Arc::new(Registry::default());
15632        let forwarding = Arc::new(ForwardingTable::default());
15633        let handler =
15634            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15635        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15636        hello_via_sink(
15637            &handler,
15638            &module_ctx,
15639            &mut module_rx,
15640            hello_frame("aft", PROTOCOL_VERSION, 7),
15641        )
15642        .await;
15643        let project_root = unique_project_root("role-versions");
15644        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15645        let route_handler = handler.clone();
15646        let route_task = tokio::spawn(async move {
15647            route_handler
15648                .handle_control_frame(
15649                    &client_ctx,
15650                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15651                )
15652                .await
15653                .unwrap()
15654        });
15655        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15656            .await
15657            .expect("a well-formed route.open reaches the module as a bind")
15658            .unwrap();
15659        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15660        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15661            panic!("expected route.bind request, got {bind:?}");
15662        };
15663        handler
15664            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15665            .await
15666            .unwrap();
15667        assert!(route_task.await.unwrap().is_empty());
15668        let published = client_rx.recv().await.unwrap();
15669        assert!(matches!(
15670            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15671            ClientControlResponse::RouteOpen { .. }
15672        ));
15673        role_versions
15674    }
15675
15676    #[tokio::test]
15677    async fn route_open_relays_role_versions_verbatim() {
15678        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15679        assert_eq!(
15680            bind_role_versions_for(Some(sent.clone()), 141).await,
15681            Some(sent)
15682        );
15683    }
15684
15685    /// An empty map declares nothing, so the provider sees no field rather
15686    /// than an empty object it would have to treat as a second "none".
15687    #[tokio::test]
15688    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15689        assert_eq!(bind_role_versions_for(None, 143).await, None);
15690        assert_eq!(
15691            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15692            None
15693        );
15694    }
15695
15696    #[tokio::test]
15697    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15698        let registry = Arc::new(Registry::default());
15699        let forwarding = Arc::new(ForwardingTable::default());
15700        let handler =
15701            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15702        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15703        hello_via_sink(
15704            &handler,
15705            &module_ctx,
15706            &mut module_rx,
15707            hello_frame("aft", PROTOCOL_VERSION, 7),
15708        )
15709        .await;
15710
15711        let nine: BTreeMap<String, String> = (0..9)
15712            .map(|index| (format!("role-{index}"), "v1".to_string()))
15713            .collect();
15714        for (label, malformed) in [
15715            (
15716                "invalid role name",
15717                role_versions(&[("Tool_Provider", "v1")]),
15718            ),
15719            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15720            ("nine entries", nine),
15721        ] {
15722            // A refused open answers at once; one that reached the module
15723            // would wait for its bind ack and trip this timeout.
15724            let responses = tokio::time::timeout(
15725                Duration::from_secs(1),
15726                handler.handle_control_frame(
15727                    &route_ctx(ConnectionId::new(148)).0,
15728                    route_open_frame_with_role_versions(
15729                        404,
15730                        "aft",
15731                        unique_project_root("role-versions-malformed"),
15732                        Some(malformed),
15733                    ),
15734                ),
15735            )
15736            .await
15737            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15738            .unwrap();
15739            assert_eq!(responses.len(), 1, "{label}");
15740            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15741            let error = parse_error(&responses[0]);
15742            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15743            assert_eq!(
15744                error["detail"]["field"], "role_versions",
15745                "{label}: {error}"
15746            );
15747            assert!(
15748                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15749                "{label}: a malformed declaration is terminal"
15750            );
15751            assert!(
15752                module_rx.try_recv().is_err(),
15753                "{label}: the module must never see a bind"
15754            );
15755        }
15756    }
15757
15758    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15759    /// consumer can tell this daemon forwards the field from one that would
15760    /// drop it.
15761    #[tokio::test]
15762    async fn route_role_versions_capability_is_advertised() {
15763        let handler = ControlHandler::new(Arc::new(Registry::default()));
15764        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15765        let ack = hello_via_sink(
15766            &handler,
15767            &ctx,
15768            &mut rx,
15769            hello_frame("m", PROTOCOL_VERSION, 1),
15770        )
15771        .await;
15772        let ack = parse_ack(&ack);
15773        assert!(
15774            ack.subc_capabilities
15775                .iter()
15776                .any(|c| c == "route-role-versions/v1"),
15777            "{:?}",
15778            ack.subc_capabilities
15779        );
15780
15781        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15782        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15783        let reply = handler
15784            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15785            .await
15786            .unwrap()
15787            .pop()
15788            .unwrap();
15789        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15790            serde_json::from_slice(&reply.body).unwrap()
15791        else {
15792            panic!("not a server.describe reply");
15793        };
15794        assert!(
15795            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15796            "{capabilities:?}"
15797        );
15798    }
15799
15800    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15801    /// catalog entry without `events` (the module declares none) from a daemon
15802    /// that never reports declared events.
15803    #[tokio::test]
15804    async fn catalog_events_capability_is_advertised() {
15805        let handler = ControlHandler::new(Arc::new(Registry::default()));
15806        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15807        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15808        let reply = handler
15809            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
15810            .await
15811            .unwrap()
15812            .pop()
15813            .unwrap();
15814        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15815            serde_json::from_slice(&reply.body).unwrap()
15816        else {
15817            panic!("not a server.describe reply");
15818        };
15819        assert!(
15820            capabilities
15821                .iter()
15822                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
15823            "{capabilities:?}"
15824        );
15825    }
15826
15827    #[tokio::test]
15828    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15829        let handler = ControlHandler::new(Arc::new(Registry::default()));
15830        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15831        let ack = hello_via_sink(
15832            &handler,
15833            &module,
15834            &mut module_rx,
15835            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15836        )
15837        .await;
15838        let ack = parse_ack(&ack);
15839        assert!(
15840            ack.subc_capabilities
15841                .iter()
15842                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15843            "{:?}",
15844            ack.subc_capabilities
15845        );
15846        assert!(ack
15847            .subc_capabilities
15848            .iter()
15849            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15850
15851        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15852        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15853        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15854        let reply = handler
15855            .handle_control_frame(&client, frame)
15856            .await
15857            .unwrap()
15858            .pop()
15859            .unwrap();
15860        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15861            serde_json::from_slice(&reply.body).unwrap()
15862        else {
15863            panic!("not a server.describe reply");
15864        };
15865        assert!(
15866            capabilities
15867                .iter()
15868                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15869            "{capabilities:?}"
15870        );
15871        assert!(capabilities
15872            .iter()
15873            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15874    }
15875
15876    #[tokio::test]
15877    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15878        let handler = ControlHandler::new(Arc::new(Registry::default()));
15879        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15880        let ack = hello_via_sink(
15881            &handler,
15882            &module,
15883            &mut rx,
15884            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15885        )
15886        .await;
15887        assert!(parse_ack(&ack)
15888            .subc_capabilities
15889            .iter()
15890            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15891        assert!(parse_ack(&ack)
15892            .subc_capabilities
15893            .iter()
15894            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15895        assert!(parse_ack(&ack)
15896            .subc_capabilities
15897            .iter()
15898            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15899        let (client, _rx) = route_ctx(ConnectionId::new(157));
15900        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15901        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15902        let reply = handler
15903            .handle_control_frame(&client, frame)
15904            .await
15905            .unwrap()
15906            .pop()
15907            .unwrap();
15908        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15909            serde_json::from_slice(&reply.body).unwrap()
15910        else {
15911            panic!("server.describe reply")
15912        };
15913        assert!(capabilities
15914            .iter()
15915            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15916        assert!(capabilities
15917            .iter()
15918            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15919        assert!(capabilities
15920            .iter()
15921            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15922    }
15923
15924    #[tokio::test]
15925    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15926        let handler = ControlHandler::new(Arc::new(Registry::default()));
15927        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15928        let ack = hello_via_sink(
15929            &handler,
15930            &module,
15931            &mut rx,
15932            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15933        )
15934        .await;
15935        assert!(parse_ack(&ack)
15936            .subc_capabilities
15937            .iter()
15938            .any(|cap| cap == "scope-workdir/v1"));
15939        let (client, _rx) = route_ctx(ConnectionId::new(159));
15940        let frame = Frame::build(
15941            FrameType::Request,
15942            control_flags(),
15943            0,
15944            0,
15945            5,
15946            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15947        )
15948        .unwrap();
15949        let reply = handler
15950            .handle_control_frame(&client, frame)
15951            .await
15952            .unwrap()
15953            .remove(0);
15954        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15955            serde_json::from_slice(&reply.body).unwrap()
15956        else {
15957            panic!("server.describe reply")
15958        };
15959        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15960    }
15961
15962    #[tokio::test]
15963    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15964        let handler = ControlHandler::new(Arc::new(Registry::default()));
15965        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15966        let ack = hello_via_sink(
15967            &handler,
15968            &module,
15969            &mut rx,
15970            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15971        )
15972        .await;
15973        assert!(parse_ack(&ack)
15974            .subc_capabilities
15975            .iter()
15976            .any(|cap| cap == "worker-runs/v1"));
15977        let (client, _rx) = route_ctx(ConnectionId::new(161));
15978        let frame = Frame::build(
15979            FrameType::Request,
15980            control_flags(),
15981            0,
15982            0,
15983            5,
15984            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15985        )
15986        .unwrap();
15987        let reply = handler
15988            .handle_control_frame(&client, frame)
15989            .await
15990            .unwrap()
15991            .remove(0);
15992        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15993            serde_json::from_slice(&reply.body).unwrap()
15994        else {
15995            panic!("server.describe reply")
15996        };
15997        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
15998    }
15999
16000    #[tokio::test]
16001    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
16002        let handler = ControlHandler::new(Arc::new(Registry::default()));
16003        let (module, mut rx) = route_ctx(ConnectionId::new(154));
16004        let ack = hello_via_sink(
16005            &handler,
16006            &module,
16007            &mut rx,
16008            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
16009        )
16010        .await;
16011        assert!(parse_ack(&ack)
16012            .subc_capabilities
16013            .iter()
16014            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16015        let (client, _rx) = route_ctx(ConnectionId::new(155));
16016        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16017        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16018        let reply = handler
16019            .handle_control_frame(&client, frame)
16020            .await
16021            .unwrap()
16022            .pop()
16023            .unwrap();
16024        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16025            serde_json::from_slice(&reply.body).unwrap()
16026        else {
16027            panic!("not a server.describe reply")
16028        };
16029        assert!(capabilities
16030            .iter()
16031            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16032    }
16033
16034    #[tokio::test]
16035    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
16036        let registry = Arc::new(Registry::default());
16037        let forwarding = Arc::new(ForwardingTable::default());
16038        let handler =
16039            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
16040                .with_health_probe_timeout(Duration::from_secs(5));
16041        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
16042        hello_via_sink(
16043            &handler,
16044            &module_ctx,
16045            &mut module_rx,
16046            non_routable_hello_frame_with_control_ops(
16047                "mcp",
16048                300,
16049                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
16050            ),
16051        )
16052        .await;
16053        assert!(registry
16054            .get_module("mcp")
16055            .unwrap()
16056            .unwrap()
16057            .manifest
16058            .provides
16059            .is_empty());
16060
16061        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
16062        let route_response = handler
16063            .handle_control_frame(
16064                &route_client_ctx,
16065                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
16066            )
16067            .await
16068            .unwrap();
16069        assert_eq!(route_response[0].header.ty, FrameType::Error);
16070        assert_eq!(
16071            parse_error(&route_response[0])["code"],
16072            "target_unavailable"
16073        );
16074        assert!(parse_error(&route_response[0])["message"]
16075            .as_str()
16076            .unwrap()
16077            .contains("does not provide the requested target"));
16078        assert!(module_rx.try_recv().is_err());
16079
16080        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16081        let health_handler = handler.clone();
16082        let health_task = tokio::spawn(async move {
16083            health_handler
16084                .handle_control_frame(
16085                    &health_client_ctx,
16086                    supervisor_health_probe_frame(302, "mcp"),
16087                )
16088                .await
16089                .unwrap()
16090        });
16091        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16092            .await
16093            .unwrap()
16094            .unwrap();
16095        assert_eq!(
16096            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16097            ModuleControlRequest::HealthCheck {}
16098        );
16099        handler
16100            .handle_control_frame(
16101                &module_ctx,
16102                health_response(health_frame.header.corr, HealthStatus::Ok),
16103            )
16104            .await
16105            .unwrap();
16106        let health_response = health_task.await.unwrap();
16107        assert_eq!(health_response[0].header.ty, FrameType::Response);
16108        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16109            ClientControlResponse::SupervisorHealthProbe {
16110                module_id, status, ..
16111            } => {
16112                assert_eq!(module_id, "mcp");
16113                assert_eq!(status, HealthStatus::Ok);
16114            }
16115            other => panic!("unexpected health response: {other:?}"),
16116        }
16117
16118        // Exercise the forwarding cleanup path directly while leaving the registry
16119        // advertisement in place. If cleanup leaves a stale control sink behind,
16120        // the next probe will enqueue onto it and wait for the long probe timeout
16121        // instead of returning an immediate no-connection error.
16122        forwarding
16123            .cleanup_connection(module_ctx.connection_id)
16124            .unwrap();
16125        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16126        let cleanup_response = tokio::time::timeout(
16127            Duration::from_millis(200),
16128            handler.handle_control_frame(
16129                &cleanup_probe_ctx,
16130                supervisor_health_probe_frame(303, "mcp"),
16131            ),
16132        )
16133        .await
16134        .expect("probe should fail immediately when the control lane is gone")
16135        .unwrap();
16136        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16137        assert_eq!(
16138            parse_error(&cleanup_response[0])["code"],
16139            "target_unavailable"
16140        );
16141        assert!(parse_error(&cleanup_response[0])["message"]
16142            .as_str()
16143            .unwrap()
16144            .contains("no module connection"));
16145
16146        handler
16147            .cleanup_connection(module_ctx.connection_id)
16148            .unwrap();
16149    }
16150
16151    #[tokio::test]
16152    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16153        let registry = Arc::new(Registry::default());
16154        let supervisor_handle = SupervisorHandle::new();
16155        let supervisor =
16156            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16157                .with_handle(supervisor_handle.clone())
16158                .with_connection_file_path(
16159                    std::env::temp_dir()
16160                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16161                );
16162        let module = supervisor
16163            .supervise_configured(
16164                ModuleSpec {
16165                    script: None,
16166                    carry_containment: false,
16167                    module_id: "warming".to_string(),
16168                    program: fake_aft_stub_path(),
16169                    args: Vec::new(),
16170                    env: Vec::new(),
16171                    reserved: false,
16172                    reserved_prefixes: Vec::new(),
16173                    protocol: ModuleProtocol::Subc,
16174                    overlap: Default::default(),
16175                },
16176                true,
16177            )
16178            .unwrap();
16179        assert_eq!(module.state().unwrap(), ModuleState::Running);
16180
16181        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16182        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16183        let response = handler
16184            .handle_control_frame(
16185                &ctx,
16186                route_open_frame(304, "warming", unique_project_root("warming")),
16187            )
16188            .await
16189            .unwrap();
16190        module.stop().await.unwrap();
16191
16192        assert_eq!(response[0].header.ty, FrameType::Error);
16193        let error = parse_error(&response[0]);
16194        assert_eq!(error["code"], "module_warming");
16195        assert!(error["message"]
16196            .as_str()
16197            .unwrap()
16198            .contains("state=running, enabled=true, live=false"));
16199    }
16200
16201    #[test]
16202    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16203        let handler = ControlHandler::new(Arc::new(Registry::default()));
16204        let capture = EventCapture::default();
16205        let _subscriber =
16206            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16207        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16208        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16209        let pending = (0..limit).collect::<Vec<_>>();
16210        let response = handler
16211            .route_open_capacity_refusal(
16212                &ctx,
16213                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16214                "busy",
16215                pending.len(),
16216                limit,
16217            )
16218            .unwrap();
16219        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16220        let event = capture
16221            .events()
16222            .into_iter()
16223            .find(|event| {
16224                event.target == "control"
16225                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16226            })
16227            .expect("connection admission refusal event");
16228        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16229        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16230        // Refused before `handle_route_open` parses the request, so the caller
16231        // fields are read from the frame itself.
16232        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16233        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16234    }
16235
16236    #[test]
16237    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16238        let handler = ControlHandler::new(Arc::new(Registry::default()));
16239        let capture = EventCapture::default();
16240        let _subscriber =
16241            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16242        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16243        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16244        let guards = (0..limit)
16245            .map(|_| {
16246                handler
16247                    .route_bind_concurrency
16248                    .try_admit("busy", limit)
16249                    .unwrap()
16250            })
16251            .collect::<Vec<_>>();
16252        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16253            Err(in_flight) => in_flight,
16254            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16255        };
16256        let response = handler
16257            .route_open_target_capacity_refusal(
16258                &ctx,
16259                &RouteOpenCaller::unknown(),
16260                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16261                "busy",
16262                in_flight,
16263            )
16264            .unwrap();
16265        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16266        let event = capture
16267            .events()
16268            .into_iter()
16269            .find(|event| {
16270                event.target == "control"
16271                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16272            })
16273            .expect("target admission refusal event");
16274        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16275        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16276        drop(guards);
16277    }
16278
16279    #[cfg(unix)]
16280    #[tokio::test(start_paused = true)]
16281    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16282        let registry = Arc::new(Registry::default());
16283        let handle = SupervisorHandle::new();
16284        let supervisor =
16285            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16286                .with_handle(handle.clone());
16287        let module = supervisor
16288            .spawn(crate::ModuleSpec {
16289                script: None,
16290                carry_containment: false,
16291                module_id: "retry-list".into(),
16292                program: PathBuf::from("/bin/sh"),
16293                args: vec!["-c".into(), "exit 17".into()],
16294                env: vec![],
16295                reserved: false,
16296                reserved_prefixes: vec![],
16297                protocol: ModuleProtocol::None,
16298                overlap: Default::default(),
16299            })
16300            .unwrap();
16301        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16302        while module.state().unwrap() != crate::ModuleState::Failed {
16303            assert!(
16304                std::time::Instant::now() < deadline,
16305                "waiting for budget failure"
16306            );
16307            tokio::task::yield_now().await;
16308        }
16309        let handler = ControlHandler::new(registry).with_supervisor(handle);
16310        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16311        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16312        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16313        assert_eq!(body["modules"][0]["state"], "failed");
16314        let retry = body["modules"][0]["next_retry_at_ms"]
16315            .as_u64()
16316            .expect("scheduled retry on the wire");
16317        let now = std::time::SystemTime::now()
16318            .duration_since(std::time::UNIX_EPOCH)
16319            .unwrap()
16320            .as_millis() as u64;
16321        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16322        module.set_enabled(false).await.unwrap();
16323        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16324        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16325        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16326        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16327    }
16328
16329    #[tokio::test]
16330    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16331        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16332        let supervisor =
16333            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16334        let module = supervisor
16335            .spawn(crate::ModuleSpec {
16336                script: None,
16337                carry_containment: false,
16338                module_id: "pid-read-budget".into(),
16339                program: std::env::current_exe().unwrap(),
16340                args: vec![
16341                    "--exact".into(),
16342                    "control::tests::pid_resource_read_fixture".into(),
16343                ],
16344                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16345                    .into_iter()
16346                    .map(|key| (key.into(), dir.display().to_string()))
16347                    .chain(std::iter::once((
16348                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16349                        "1".into(),
16350                    )))
16351                    .collect(),
16352                reserved: false,
16353                reserved_prefixes: Vec::new(),
16354                protocol: ModuleProtocol::None,
16355                overlap: Default::default(),
16356            })
16357            .unwrap();
16358        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16359        while !matches!(
16360            module.child_resource_usage(),
16361            subc_control::ChildResourceUsage::Measured(_)
16362        ) {
16363            assert!(
16364                tokio::time::Instant::now() < ready_deadline,
16365                "fixture process was not measurable"
16366            );
16367            tokio::time::sleep(Duration::from_millis(10)).await;
16368        }
16369        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16370        let reading = {
16371            let _guard = crate::subtree_resources::fault_read_guard().await;
16372            crate::subtree_resources::read_process(module.clone()).await
16373        };
16374        stop_resource_fixture(&module, &dir).await;
16375        assert!(
16376            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16377            "{reading:?}"
16378        );
16379    }
16380
16381    #[test]
16382    fn pid_resource_read_fixture() {
16383        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16384            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16385            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16386            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16387                std::thread::sleep(Duration::from_millis(5));
16388            }
16389            std::fs::write(dir.join("module-stopped"), "").unwrap();
16390        }
16391    }
16392
16393    async fn stop_resource_fixture(
16394        module: &crate::supervise::SupervisedModule,
16395        dir: &std::path::Path,
16396    ) {
16397        let stopping = module.stop();
16398        tokio::pin!(stopping);
16399        tokio::select! {
16400            result = &mut stopping => result.unwrap(),
16401            () = async {
16402                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16403                    tokio::time::sleep(Duration::from_millis(5)).await;
16404                }
16405                std::fs::write(dir.join("stop-module"), "").unwrap();
16406            } => stopping.await.unwrap(),
16407        }
16408        #[cfg(windows)]
16409        assert!(
16410            dir.join("module-stopped").exists(),
16411            "the resource fixture must exit cooperatively, not wait for the drain kill"
16412        );
16413        assert_eq!(
16414            module.state().unwrap(),
16415            crate::supervise::ModuleState::Stopped
16416        );
16417    }
16418
16419    #[tokio::test]
16420    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16421        let registry = Arc::new(Registry::default());
16422        let handle = SupervisorHandle::new();
16423        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16424            .with_handle(handle.clone());
16425        supervisor
16426            .supervise_configured(
16427                crate::ModuleSpec {
16428                    script: None,
16429                    module_id: "disabled-resource-reading".into(),
16430                    program: std::env::current_exe().unwrap(),
16431                    args: Vec::new(),
16432                    env: Vec::new(),
16433                    reserved: false,
16434                    reserved_prefixes: Vec::new(),
16435                    protocol: ModuleProtocol::None,
16436                    overlap: Default::default(),
16437                    carry_containment: false,
16438                },
16439                false,
16440            )
16441            .unwrap();
16442        let handler = ControlHandler::new(registry).with_supervisor(handle);
16443        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16444        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16445        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16446        assert!(body["modules"][0].get("tree").is_none());
16447        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16448    }
16449
16450    #[tokio::test]
16451    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16452        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16453        let registry = Arc::new(Registry::default());
16454        let handle = SupervisorHandle::new();
16455        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16456            .with_handle(handle.clone());
16457        let module = supervisor
16458            .spawn(crate::ModuleSpec {
16459                script: None,
16460                carry_containment: false,
16461                module_id: "list-process-priority".into(),
16462                program: std::env::current_exe().unwrap(),
16463                args: vec![
16464                    "--exact".into(),
16465                    "control::tests::pid_resource_read_fixture".into(),
16466                ],
16467                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16468                    .into_iter()
16469                    .map(|key| (key.into(), dir.display().to_string()))
16470                    .chain(std::iter::once((
16471                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16472                        "1".into(),
16473                    )))
16474                    .collect(),
16475                reserved: false,
16476                reserved_prefixes: Vec::new(),
16477                protocol: ModuleProtocol::None,
16478                overlap: Default::default(),
16479            })
16480            .unwrap();
16481        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16482        loop {
16483            let image = module.running_image_agreement().await;
16484            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16485                break;
16486            }
16487            assert!(
16488                tokio::time::Instant::now() < ready_deadline,
16489                "the fixture process never became observable: {image:?}"
16490            );
16491            tokio::time::sleep(Duration::from_millis(10)).await;
16492        }
16493        let guard = crate::subtree_resources::fault_read_guard().await;
16494        let (target, release, _) = crate::subtree_resources::held();
16495        module.set_subtree_target_for_test(target);
16496        let handler = ControlHandler::new(registry).with_supervisor(handle);
16497        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16498        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16499        drop(release);
16500        drop(guard);
16501        stop_resource_fixture(&module, &dir).await;
16502        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16503        assert_eq!(
16504            body["modules"][0]["resources"]["status"], "measured",
16505            "the optional tree timeout must not discard the process reading: {body}"
16506        );
16507        assert!(body["modules"][0].get("tree").is_none());
16508        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16509        assert_eq!(
16510            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16511            "the tree timeout must not hide a completed image observation"
16512        );
16513    }
16514
16515    #[cfg(any(target_os = "linux", target_os = "macos"))]
16516    #[tokio::test]
16517    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16518        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16519            .with_daemon_provenance(
16520                std::process::id(),
16521                0,
16522                Some(std::env::current_exe().unwrap()),
16523                None,
16524                None,
16525            );
16526        let (probe, release, began) = ExecutableIdentityProbe::held();
16527        handler.daemon_provenance.probe = probe;
16528        let observe = |handler: ControlHandler, corr| {
16529            tokio::spawn(async move {
16530                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16531                let frame =
16532                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16533                        .unwrap();
16534                handler
16535                    .handle_supervisor_provenance(&ctx, frame, None)
16536                    .await
16537                    .unwrap()
16538            })
16539        };
16540        let explicit = observe(handler.clone(), 114);
16541        began.await.unwrap();
16542        let concurrent = observe(handler.clone(), 115);
16543        // Keep explicit provenance waiting on its first image observation beyond
16544        // the list deadline; release it only after the concurrent list replies.
16545        tokio::time::sleep(Duration::from_millis(300)).await;
16546        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16547        let list = tokio::time::timeout(
16548            Duration::from_secs(1),
16549            handler.handle_supervisor_list(frame),
16550        )
16551        .await;
16552        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16553        drop(release);
16554        let replies = explicit.await.unwrap();
16555        let concurrent_replies = concurrent.await.unwrap();
16556        assert!(
16557            explicit_was_pending,
16558            "explicit provenance must await the full observation"
16559        );
16560        let list = list
16561            .expect("a concurrent explicit probe must not stall list")
16562            .unwrap();
16563        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16564        assert_eq!(list_body["op"], "supervisor.list");
16565        for replies in [replies, concurrent_replies] {
16566            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16567            assert_eq!(
16568                body["daemon"]["daemon_observed"]["running_image"]["status"],
16569                "match"
16570            );
16571        }
16572    }
16573
16574    #[tokio::test]
16575    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16576        let registry = Arc::new(Registry::default());
16577        let handle = SupervisorHandle::new();
16578        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16579            .with_handle(handle.clone());
16580        let module = supervisor
16581            .supervise_configured(
16582                crate::ModuleSpec {
16583                    script: None,
16584                    carry_containment: false,
16585                    module_id: "memory-read".into(),
16586                    program: PathBuf::from("disabled-module"),
16587                    args: Vec::new(),
16588                    env: Vec::new(),
16589                    reserved: false,
16590                    reserved_prefixes: Vec::new(),
16591                    protocol: ModuleProtocol::Subc,
16592                    overlap: Default::default(),
16593                },
16594                true,
16595            )
16596            .unwrap();
16597        let _guard = crate::subtree_resources::fault_read_guard().await;
16598        let (target, release, began) = crate::subtree_resources::held();
16599        // Optional list work may be skipped when its deadline is already spent.
16600        // Establish the stalled fixture before asking the list to observe it.
16601        let stalled_target = target.clone();
16602        let stalled = tokio::task::spawn_blocking(move || {
16603            stalled_target.tree(&subc_os::ProcessTable::default())
16604        });
16605        began.await.unwrap();
16606        module.set_subtree_target_for_test(target);
16607        let handler = ControlHandler::new(registry).with_supervisor(handle);
16608        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16609        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16610        let replies = handler
16611            .handle_client_control_request(
16612                &ctx,
16613                frame,
16614                ClientControlRequest::SupervisorList {},
16615                &mut None,
16616            )
16617            .await
16618            .unwrap();
16619        assert!(
16620            replies.is_empty(),
16621            "list reply must be detached from the connection reader"
16622        );
16623        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16624        let replies = handler
16625            .handle_client_control_request(
16626                &ctx,
16627                frame,
16628                ClientControlRequest::SupervisorSpawnSnapshot {},
16629                &mut None,
16630            )
16631            .await
16632            .unwrap();
16633        assert_eq!(
16634            replies.len(),
16635            1,
16636            "another request must complete while the subtree read stalls"
16637        );
16638        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16639            .await
16640            .unwrap()
16641            .unwrap();
16642        release.send(()).unwrap();
16643        drop(release);
16644        stalled.await.unwrap();
16645        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16646        assert!(
16647            body["modules"][0].get("tree").is_none(),
16648            "an unknown tree reading must be omitted after the bounded read expires"
16649        );
16650        // Lists export completed work rather than measuring synchronously.
16651        // Complete a refresh after the fixture is released before asserting
16652        // that a later list contains its measured tree.
16653        handler
16654            .resource_tracker
16655            .read(handler.supervisor.list(), false, "released_tree_fixture")
16656            .await;
16657        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16658        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16659        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16660        assert_eq!(
16661            body["modules"][0]["tree"]["source"], "process_tree",
16662            "the next request must export the completed refresh"
16663        );
16664        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16665    }
16666
16667    #[tokio::test]
16668    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16669        use subc_control::{
16670            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16671            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16672            TreeReading, TreeSource,
16673        };
16674        let registry = Arc::new(Registry::default());
16675        let handle = SupervisorHandle::new();
16676        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16677            .with_handle(handle.clone());
16678        supervisor
16679            .supervise_configured(
16680                crate::ModuleSpec {
16681                    script: None,
16682                    carry_containment: false,
16683                    module_id: "budget-worker".into(),
16684                    program: PathBuf::from("disabled-module"),
16685                    args: Vec::new(),
16686                    env: Vec::new(),
16687                    reserved: false,
16688                    reserved_prefixes: Vec::new(),
16689                    protocol: ModuleProtocol::Subc,
16690                    overlap: Default::default(),
16691                },
16692                true,
16693            )
16694            .unwrap();
16695        let handler = ControlHandler::new(registry).with_supervisor(handle);
16696        let now = u64::try_from(
16697            std::time::SystemTime::now()
16698                .duration_since(std::time::UNIX_EPOCH)
16699                .unwrap()
16700                .as_millis(),
16701        )
16702        .unwrap();
16703        let measured = now - 1_000;
16704        let hour = CpuLastHour::new(100, 60_000);
16705        let daemon = DaemonResources::new(7, 1, "test")
16706            .with_measured_at_ms(Some(measured))
16707            .with_resources(Some(ChildResourceUsage::Measured(
16708                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16709            )))
16710            .with_cpu_last_hour(Some(hour.clone()));
16711        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16712            .with_measured_at_ms(Some(measured))
16713            .with_cpu_last_hour(Some(hour.clone()));
16714        let tree = TreeReading::new(
16715            150,
16716            50,
16717            ChildMemoryKind::ResidentSet,
16718            1,
16719            TreeSource::ProcessTree,
16720        )
16721        .with_measured_at_ms(Some(measured));
16722        handler.resource_tracker.seed_committed_for_test(
16723            &handler.supervisor.list(),
16724            crate::resource_totals::Readings {
16725                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16726                daemon: Some(daemon),
16727                agent_commands: Some(vec![agents]),
16728                ..Default::default()
16729            },
16730            now,
16731        );
16732        list_diagnostics::scope(async {
16733            tokio::time::sleep(Duration::from_millis(110)).await;
16734            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16735            let request =
16736                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16737            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16738            let ClientControlResponse::SupervisorList {
16739                modules,
16740                daemon,
16741                agent_commands,
16742                ..
16743            } = serde_json::from_slice(&replies[0].body).unwrap()
16744            else {
16745                panic!("expected a list response")
16746            };
16747            assert!(matches!(
16748                modules[0].resources,
16749                Some(ChildResourceUsage::Unavailable {
16750                    reason: ChildResourceUnavailableReason::Unreadable
16751                })
16752            ));
16753            assert_eq!(
16754                (
16755                    modules[0].tree.as_ref().unwrap().cpu_ms,
16756                    modules[0].tree.as_ref().unwrap().measured_at_ms
16757                ),
16758                (150, Some(measured))
16759            );
16760            let daemon = daemon.unwrap();
16761            let agents = agent_commands.unwrap();
16762            assert_eq!(daemon.measured_at_ms, Some(measured));
16763            assert_eq!(
16764                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16765                (1, 50, Some(measured))
16766            );
16767            for hour in [
16768                modules[0].cpu_last_hour.as_ref(),
16769                daemon.cpu_last_hour.as_ref(),
16770                agents[0].cpu_last_hour.as_ref(),
16771            ] {
16772                let hour = hour.unwrap();
16773                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16774            }
16775        })
16776        .await;
16777    }
16778
16779    #[tokio::test]
16780    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16781        let registry = Arc::new(Registry::default());
16782        let handle = SupervisorHandle::new();
16783        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16784            .with_handle(handle.clone());
16785        supervisor
16786            .supervise_configured(
16787                crate::ModuleSpec {
16788                    script: None,
16789                    carry_containment: false,
16790                    module_id: "drift".into(),
16791                    program: PathBuf::from("disabled-module"),
16792                    args: Vec::new(),
16793                    env: Vec::new(),
16794                    reserved: false,
16795                    reserved_prefixes: Vec::new(),
16796                    protocol: ModuleProtocol::Subc,
16797                    overlap: Default::default(),
16798                },
16799                false,
16800            )
16801            .unwrap();
16802        let handler = ControlHandler::new(registry).with_supervisor(handle);
16803        for configured in [None, Some(false), Some(true)] {
16804            handler.capability_evaluator.configure(
16805                configured.map(|enabled| ("drift".to_string(), enabled)),
16806                BTreeMap::new(),
16807            );
16808            let frame =
16809                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16810            let replies = handler
16811                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16812                .await
16813                .unwrap();
16814            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16815            assert!(body.get("configured_enabled").is_none());
16816            assert_eq!(body["op"], "supervisor.ack");
16817            let frame =
16818                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16819            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16820            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16821            assert_eq!(
16822                body["modules"][0].get("configured_enabled"),
16823                configured.map(Value::Bool).as_ref()
16824            );
16825            assert!(body["modules"][0].get("tree").is_none());
16826            assert!(body["modules"][0].get("subtree").is_none());
16827        }
16828    }
16829
16830    #[tokio::test(flavor = "current_thread")]
16831    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16832        let handler = ControlHandler::new(Arc::new(Registry::default()));
16833        let capture = EventCapture::default();
16834        let _subscriber =
16835            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16836        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16837        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16838
16839        let _ = handler
16840            .handle_client_control_request(
16841                &ctx,
16842                frame,
16843                ClientControlRequest::SupervisorSetEnabled {
16844                    module_id: "broca".to_string(),
16845                    enabled: false,
16846                },
16847                &mut None,
16848            )
16849            .await
16850            .unwrap();
16851
16852        let events = capture
16853            .events()
16854            .into_iter()
16855            .filter(|event| {
16856                event.target == "control"
16857                    && event.fields.get("message").map(String::as_str)
16858                        == Some("supervisor request received")
16859            })
16860            .collect::<Vec<_>>();
16861        assert_eq!(events.len(), 1, "one supervisor request log line");
16862        let event = &events[0];
16863        assert_eq!(event.level, tracing::Level::INFO);
16864        assert_eq!(
16865            event.fields.get("op"),
16866            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16867        );
16868        assert_eq!(
16869            event.fields.get("module_id"),
16870            Some(&"\"broca\"".to_string())
16871        );
16872        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16873        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16874        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16875    }
16876
16877    #[tokio::test(flavor = "current_thread")]
16878    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16879        let registry = Arc::new(Registry::default());
16880        let module_connection = ConnectionId::new(303);
16881        registry
16882            .register_with_control_ops(
16883                manifest("aft", PROTOCOL_VERSION),
16884                PROTOCOL_VERSION,
16885                module_connection,
16886                module_baseline_control_ops(),
16887            )
16888            .unwrap();
16889        let handler = ControlHandler::new(registry);
16890        let capture = EventCapture::default();
16891        let _subscriber =
16892            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16893        let (ctx, _rx) = route_ctx(module_connection);
16894        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16895
16896        let _ = handler
16897            .handle_client_control_request(
16898                &ctx,
16899                frame,
16900                ClientControlRequest::SupervisorSetEnabled {
16901                    module_id: "broca".to_string(),
16902                    enabled: false,
16903                },
16904                &mut None,
16905            )
16906            .await
16907            .unwrap();
16908
16909        let callers = capture
16910            .events()
16911            .into_iter()
16912            .filter(|event| {
16913                event.fields.get("message").map(String::as_str)
16914                    == Some("supervisor request received")
16915            })
16916            .map(|event| event.fields.get("caller").cloned())
16917            .collect::<Vec<_>>();
16918        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16919    }
16920
16921    #[tokio::test(flavor = "current_thread")]
16922    async fn supervisor_list_does_not_log_request_received() {
16923        let handler = ControlHandler::new(Arc::new(Registry::default()));
16924        let capture = EventCapture::default();
16925        let _subscriber =
16926            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16927        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16928        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16929
16930        handler
16931            .handle_client_control_request(
16932                &ctx,
16933                frame,
16934                ClientControlRequest::SupervisorList {},
16935                &mut None,
16936            )
16937            .await
16938            .unwrap();
16939
16940        assert!(capture.events().into_iter().all(|event| {
16941            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16942        }));
16943    }
16944
16945    #[tokio::test(flavor = "current_thread")]
16946    async fn supervisor_rescan_preview_does_not_log_request_received() {
16947        let handler = ControlHandler::new(Arc::new(Registry::default()));
16948        let capture = EventCapture::default();
16949        let _subscriber =
16950            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16951        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16952        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16953
16954        handler
16955            .handle_client_control_request(
16956                &ctx,
16957                frame,
16958                ClientControlRequest::SupervisorRescan { preview: true },
16959                &mut None,
16960            )
16961            .await
16962            .unwrap();
16963
16964        assert!(capture.events().into_iter().all(|event| {
16965            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16966        }));
16967    }
16968
16969    struct ApproveOperator;
16970    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16971        fn prompt(
16972            &self,
16973            _: &str,
16974            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16975        ) -> crate::operator_confirm::ProviderResult {
16976            crate::operator_confirm::ProviderResult::Approved
16977        }
16978    }
16979
16980    #[tokio::test]
16981    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
16982        assert_eq!(
16983            ControlHandler::default().privileged_operator_prompt,
16984            PrivilegedOperatorPrompt::Log
16985        );
16986        for (initial, changed, running) in [
16987            ("log", "enforce", PrivilegedOperatorPrompt::Log),
16988            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
16989        ] {
16990            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
16991            let path = dir.join("subc.jsonc");
16992            std::fs::write(
16993                &path,
16994                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
16995            )
16996            .unwrap();
16997            let config = crate::daemon_config::load(&path).unwrap().unwrap();
16998            let registry = Arc::new(Registry::default());
16999            let handle = SupervisorHandle::new();
17000            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
17001                .with_handle(handle.clone());
17002            let handler = ControlHandler::new(registry)
17003                .with_supervisor(handle)
17004                .with_privileged_operator_prompt(config.privileged_operator_prompt)
17005                .with_supervisor_rescan(supervisor, &path, config.port);
17006            handler.forwarding.operator_confirms().configure(
17007                Arc::new(ApproveOperator),
17008                crate::operator_confirm::OperatorLimits::default(),
17009            );
17010            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
17011
17012            for (disk_mode, needs_restart) in [
17013                (Some(initial), false),
17014                (Some(changed), true),
17015                (Some(changed), true),
17016                (None, running == PrivilegedOperatorPrompt::Enforce),
17017                (Some(initial), false),
17018            ] {
17019                let mut doc = json!({"version":1});
17020                if let Some(mode) = disk_mode {
17021                    doc["privileged_operator_prompt"] = json!(mode);
17022                }
17023                std::fs::write(&path, doc.to_string()).unwrap();
17024                for preview in [true, false] {
17025                    let request = ClientControlRequest::SupervisorRescan { preview };
17026                    let frame = Frame::build(
17027                        FrameType::Request,
17028                        control_flags(),
17029                        0,
17030                        0,
17031                        1,
17032                        serde_json::to_vec(&request).unwrap(),
17033                    )
17034                    .unwrap();
17035                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17036                    assert_eq!(frames.len(), 1);
17037                    let ClientControlResponse::SupervisorRescan { result } =
17038                        serde_json::from_slice(&frames[0].body).unwrap()
17039                    else {
17040                        panic!("expected a rescan response");
17041                    };
17042                    let expected = if needs_restart {
17043                        vec!["privileged_operator_prompt"]
17044                    } else {
17045                        Vec::new()
17046                    };
17047                    assert_eq!(result.restart_required, expected);
17048                    assert_eq!(handler.privileged_operator_prompt, running);
17049                    assert_eq!(
17050                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
17051                        running
17052                    );
17053                }
17054            }
17055        }
17056    }
17057
17058    #[tokio::test]
17059    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
17060        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
17061        let path = dir.join("subc.jsonc");
17062        let registry = Arc::new(Registry::default());
17063        let handle = SupervisorHandle::new();
17064        let supervisor =
17065            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
17066        let handler = ControlHandler::new(registry)
17067            .with_supervisor(handle)
17068            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
17069            .with_supervisor_rescan(supervisor, &path, None);
17070        handler.forwarding.operator_confirms().configure(
17071            Arc::new(ApproveOperator),
17072            crate::operator_confirm::OperatorLimits::default(),
17073        );
17074        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17075        for preview in [true, false] {
17076            std::fs::write(
17077                &path,
17078                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17079            )
17080            .unwrap();
17081            let request = ClientControlRequest::SupervisorRescan { preview };
17082            let frame = Frame::build(
17083                FrameType::Request,
17084                control_flags(),
17085                0,
17086                0,
17087                1,
17088                serde_json::to_vec(&request).unwrap(),
17089            )
17090            .unwrap();
17091            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17092            assert_eq!(frames.len(), 1);
17093            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17094            assert_eq!(
17095                handler.privileged_operator_prompt,
17096                PrivilegedOperatorPrompt::Enforce
17097            );
17098        }
17099    }
17100
17101    /// One wire code has several senders, so the refusal line names the check
17102    /// that refused. This drives the shared refusal path for ordinary refusals
17103    /// with an unregistered
17104    /// target and requires the branch label on the event.
17105    #[tokio::test]
17106    async fn route_open_refusal_names_the_check_that_refused() {
17107        let handler = ControlHandler::new(Arc::new(Registry::default()));
17108        let capture = EventCapture::default();
17109        let _subscriber =
17110            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17111        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17112        let response = handler
17113            .handle_control_frame(
17114                &ctx,
17115                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17116            )
17117            .await
17118            .unwrap();
17119
17120        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17121        let event = capture
17122            .events()
17123            .into_iter()
17124            .find(|event| {
17125                event.target == "control"
17126                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17127            })
17128            .expect("route.open refusal event");
17129        assert_eq!(
17130            event.fields.get("reason"),
17131            Some(&"\"not_registered\"".to_string())
17132        );
17133    }
17134
17135    #[tokio::test]
17136    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17137        let registry = Arc::new(Registry::default());
17138        let supervisor_handle = SupervisorHandle::new();
17139        let supervisor =
17140            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17141                .with_handle(supervisor_handle.clone())
17142                .with_connection_file_path(std::env::temp_dir().join(format!(
17143                    "subc-route-open-refusal-info-{}",
17144                    std::process::id()
17145                )));
17146        let module = supervisor
17147            .supervise_configured(
17148                ModuleSpec {
17149                    script: None,
17150                    carry_containment: false,
17151                    module_id: "warming".to_string(),
17152                    program: fake_aft_stub_path(),
17153                    args: Vec::new(),
17154                    env: Vec::new(),
17155                    reserved: false,
17156                    reserved_prefixes: Vec::new(),
17157                    protocol: ModuleProtocol::Subc,
17158                    overlap: Default::default(),
17159                },
17160                true,
17161            )
17162            .unwrap();
17163        assert_eq!(module.state().unwrap(), ModuleState::Running);
17164
17165        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17166        assert!(handler
17167            .counters()
17168            .snapshot()
17169            .get("route_open_refused_by_code")
17170            .is_none());
17171        let capture = EventCapture::default();
17172        let _subscriber =
17173            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17174        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17175        let response = handler
17176            .handle_control_frame(
17177                &ctx,
17178                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17179            )
17180            .await
17181            .unwrap();
17182        module.stop().await.unwrap();
17183
17184        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17185        let event = capture
17186            .events()
17187            .into_iter()
17188            .find(|event| {
17189                event.target == "control"
17190                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17191            })
17192            .expect("route.open refusal event");
17193        assert_eq!(
17194            event.fields.get("module_id"),
17195            Some(&"\"warming\"".to_string())
17196        );
17197        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17198        assert_eq!(
17199            event.fields.get("reason"),
17200            Some(&"\"supervised_not_registered\"".to_string())
17201        );
17202        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17203        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17204        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17205        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17206        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17207        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17208        assert_eq!(
17209            handler.counters().snapshot()["route_open_refused_by_code"],
17210            json!({ "module_warming": 1 })
17211        );
17212    }
17213
17214    const OUTAGE_START: &str = "route.open refusing module: not serving";
17215    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17216
17217    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17218        capture
17219            .events()
17220            .into_iter()
17221            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17222            .collect()
17223    }
17224
17225    fn supervise_stub(
17226        registry: &Arc<Registry>,
17227        module_id: &str,
17228        enabled: bool,
17229    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17230        let supervisor_handle = SupervisorHandle::new();
17231        let supervisor =
17232            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17233                .with_handle(supervisor_handle.clone())
17234                .with_connection_file_path(std::env::temp_dir().join(format!(
17235                    "subc-route-outage-{module_id}-{}",
17236                    std::process::id()
17237                )));
17238        let module = supervisor
17239            .supervise_configured(
17240                ModuleSpec {
17241                    script: None,
17242                    carry_containment: false,
17243                    module_id: module_id.to_string(),
17244                    program: fake_aft_stub_path(),
17245                    args: Vec::new(),
17246                    env: Vec::new(),
17247                    reserved: false,
17248                    reserved_prefixes: Vec::new(),
17249                    protocol: ModuleProtocol::Subc,
17250                    overlap: Default::default(),
17251                },
17252                enabled,
17253            )
17254            .unwrap();
17255        (supervisor_handle, module)
17256    }
17257
17258    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17259        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17260            module_id: module_id.to_string(),
17261            drain_timeout_ms: Some(50),
17262        })
17263        .unwrap();
17264        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17265    }
17266
17267    /// Two handlers built over one forwarding table must share one outage
17268    /// tracker; separate trackers would each log their own opening line for
17269    /// the same outage.
17270    #[test]
17271    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17272        let registry = Arc::new(Registry::default());
17273        let forwarding = Arc::new(ForwardingTable::default());
17274        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17275        let second = ControlHandler::with_forwarding(registry, forwarding);
17276        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17277    }
17278
17279    /// A client can name any module id it likes. Refusing an unknown one,
17280    /// however often, must not create outage state or outage lines, or the
17281    /// tracker would be a memory sink any client could fill.
17282    #[tokio::test(flavor = "current_thread")]
17283    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17284        let handler = ControlHandler::new(Arc::new(Registry::default()));
17285        let capture = EventCapture::default();
17286        let _subscriber =
17287            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17288        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17289        for corr in 0..8 {
17290            let response = handler
17291                .handle_control_frame(
17292                    &ctx,
17293                    route_open_frame(
17294                        380 + corr,
17295                        &format!("nobody-{corr}"),
17296                        unique_project_root("outage-unknown"),
17297                    ),
17298                )
17299                .await
17300                .unwrap();
17301            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17302        }
17303
17304        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17305        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17306        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17307    }
17308
17309    /// Drives the refusal path end to end: a supervised module that served
17310    /// before and stopped being registered with no instruction to stop is a
17311    /// WARN, and the same module refused after an operator `supervisor.restart`
17312    /// is an INFO.
17313    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17314    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17315        let registry = Arc::new(Registry::default());
17316        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17317        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17318        let capture = EventCapture::default();
17319        let _subscriber =
17320            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17321        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17322        // The stub never registers, so pretend it served once: otherwise every
17323        // refusal would fall in its startup window.
17324        handler.route_outages.record_accepted("outage-restart");
17325
17326        let response = handler
17327            .handle_control_frame(
17328                &ctx,
17329                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17330            )
17331            .await
17332            .unwrap();
17333        assert_eq!(response[0].header.ty, FrameType::Error);
17334        let starts = outage_lines(&capture, OUTAGE_START);
17335        assert_eq!(starts.len(), 1, "{starts:?}");
17336        assert_eq!(starts[0].level, tracing::Level::WARN);
17337        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17338        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17339        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17340        handler.route_outages.record_accepted("outage-restart");
17341        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17342
17343        // The missing connection file makes the stub exit immediately. Restart
17344        // is deliberately deferred while that exit is being recorded; Failed
17345        // means the zero restart budget and terminal record have been published.
17346        tokio::time::timeout(Duration::from_secs(10), async {
17347            while module.state().unwrap() != crate::ModuleState::Failed {
17348                tokio::task::yield_now().await;
17349            }
17350        })
17351        .await
17352        .expect("stub exit must be recorded before the operator restart");
17353
17354        let restart = handler
17355            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17356            .await
17357            .unwrap();
17358        assert_eq!(
17359            restart[0].header.ty,
17360            FrameType::Response,
17361            "{:?}",
17362            parse_error(&restart[0])
17363        );
17364        handler
17365            .handle_control_frame(
17366                &ctx,
17367                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17368            )
17369            .await
17370            .unwrap();
17371        module.stop().await.unwrap();
17372
17373        let starts = outage_lines(&capture, OUTAGE_START);
17374        assert_eq!(starts.len(), 2, "{starts:?}");
17375        assert_eq!(starts[1].level, tracing::Level::INFO);
17376        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17377    }
17378
17379    /// A restart refused before it touched the module (here: the module is
17380    /// disabled) must clear its operator mark, so the next real outage is
17381    /// still reported as a warning.
17382    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17383    async fn failed_operator_restart_leaves_no_operator_mark() {
17384        let registry = Arc::new(Registry::default());
17385        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17386        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17387        let capture = EventCapture::default();
17388        let _subscriber =
17389            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17390        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17391        handler.route_outages.record_accepted("outage-disabled");
17392
17393        let restart = handler
17394            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17395            .await
17396            .unwrap();
17397        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17398        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17399
17400        handler
17401            .handle_control_frame(
17402                &ctx,
17403                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17404            )
17405            .await
17406            .unwrap();
17407        let starts = outage_lines(&capture, OUTAGE_START);
17408        assert_eq!(starts.len(), 1, "{starts:?}");
17409        assert_eq!(starts[0].level, tracing::Level::WARN);
17410    }
17411
17412    #[tokio::test(flavor = "current_thread")]
17413    async fn route_open_unknown_module_escapes_target_module_id() {
17414        let handler = ControlHandler::new(Arc::new(Registry::default()));
17415        let capture = EventCapture::default();
17416        let _subscriber =
17417            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17418        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17419        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17420        let response = handler
17421            .handle_control_frame(
17422                &ctx,
17423                route_open_frame(
17424                    395,
17425                    hostile_module_id,
17426                    unique_project_root("hostile-target-module-id"),
17427                ),
17428            )
17429            .await
17430            .unwrap();
17431
17432        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17433        let event = capture
17434            .events()
17435            .into_iter()
17436            .find(|event| {
17437                event.target == "control"
17438                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17439            })
17440            .expect("route.open unknown-module refusal event");
17441        let logged = event.fields.get("module_id").expect("module_id field");
17442        assert!(!logged.bytes().any(|byte| byte < 0x20));
17443        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17444    }
17445
17446    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17447    /// the daemon-origin bit on the frame the client receives.
17448    #[tokio::test(flavor = "current_thread")]
17449    async fn route_open_refusal_carries_daemon_origin() {
17450        let handler = ControlHandler::new(Arc::new(Registry::default()));
17451        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17452        let response = handler
17453            .handle_control_frame(
17454                &ctx,
17455                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17456            )
17457            .await
17458            .unwrap();
17459
17460        assert_eq!(response.len(), 1);
17461        assert_eq!(response[0].header.ty, FrameType::Error);
17462        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17463        assert!(
17464            response[0].header.flags.is_daemon_origin(),
17465            "route.open refusal must carry daemon origin: {:?}",
17466            response[0].header.flags
17467        );
17468    }
17469
17470    /// The drain `module_reloading` refusal is daemon-synthesized for an
17471    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17472    /// frame the client receives.
17473    #[tokio::test(flavor = "current_thread")]
17474    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17475        let registry = Arc::new(Registry::default());
17476        let forwarding = Arc::new(ForwardingTable::default());
17477        let handler =
17478            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17479        let module_connection = ConnectionId::new(95);
17480        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17481        hello_via_sink(
17482            &handler,
17483            &module_ctx,
17484            &mut module_rx,
17485            hello_frame("aft", PROTOCOL_VERSION, 395),
17486        )
17487        .await;
17488        forwarding
17489            .begin_module_drain("aft", RouteCloseReason::Restart)
17490            .unwrap()
17491            .expect("the module endpoint drains");
17492
17493        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17494        let response = handler
17495            .handle_control_frame(
17496                &client_ctx,
17497                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17498            )
17499            .await
17500            .unwrap();
17501
17502        assert_eq!(response.len(), 1);
17503        assert_eq!(response[0].header.ty, FrameType::Error);
17504        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17505        assert!(
17506            response[0].header.flags.is_daemon_origin(),
17507            "drain module_reloading must carry daemon origin: {:?}",
17508            response[0].header.flags
17509        );
17510    }
17511
17512    /// A module that refuses a bind with a daemon code still cannot mint a
17513    /// daemon refusal: the relayed `module_reloading` body reaches the client
17514    /// with the daemon-origin bit clear.
17515    #[tokio::test(flavor = "current_thread")]
17516    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17517        let registry = Arc::new(Registry::default());
17518        let forwarding = Arc::new(ForwardingTable::default());
17519        let handler =
17520            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17521        let module_connection = ConnectionId::new(95);
17522        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17523        hello_via_sink(
17524            &handler,
17525            &module_ctx,
17526            &mut module_rx,
17527            hello_frame("aft", PROTOCOL_VERSION, 395),
17528        )
17529        .await;
17530
17531        let client_connection = ConnectionId::new(96);
17532        let (client_ctx, _client_rx) = route_ctx(client_connection);
17533        let (route_task, bind) = relay_route_open(
17534            &handler,
17535            client_connection,
17536            &client_ctx.egress,
17537            &mut module_rx,
17538            396,
17539            "aft",
17540            "spoofed-reloading",
17541        )
17542        .await;
17543        // The module sets the origin bit on its own rejection too: neither
17544        // the bit nor the daemon code may survive the relay as daemon-owned.
17545        let rejection = Frame::build(
17546            FrameType::Error,
17547            crate::router::daemon_error_flags(),
17548            0,
17549            0,
17550            bind.header.corr,
17551            serde_json::to_vec(&ErrorBody::new(
17552                "module_reloading",
17553                "module refused route.bind",
17554            ))
17555            .unwrap(),
17556        )
17557        .unwrap();
17558        handler
17559            .handle_control_frame(&module_ctx, rejection)
17560            .await
17561            .unwrap();
17562
17563        let response = route_task.await.unwrap();
17564        assert_eq!(response.len(), 1);
17565        assert_eq!(response[0].header.ty, FrameType::Error);
17566        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17567        assert!(
17568            !response[0].header.flags.is_daemon_origin(),
17569            "a module's own rejection must not carry daemon origin: {:?}",
17570            response[0].header.flags
17571        );
17572    }
17573
17574    #[tokio::test(flavor = "current_thread")]
17575    async fn route_open_module_rejection_uses_daemon_counter_key() {
17576        let registry = Arc::new(Registry::default());
17577        let forwarding = Arc::new(ForwardingTable::default());
17578        let handler =
17579            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17580        let module_connection = ConnectionId::new(95);
17581        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17582        hello_via_sink(
17583            &handler,
17584            &module_ctx,
17585            &mut module_rx,
17586            hello_frame("aft", PROTOCOL_VERSION, 395),
17587        )
17588        .await;
17589
17590        let client_connection = ConnectionId::new(96);
17591        let (client_ctx, _client_rx) = route_ctx(client_connection);
17592        let capture = EventCapture::default();
17593        // tracing-core decides once per callsite whether its events are enabled,
17594        // and caches the answer. If a parallel test with no subscriber reaches
17595        // this callsite first, the cached answer is "disabled" and this test's
17596        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17597        // ask every live subscriber instead, while only this test's default
17598        // receives the events.
17599        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17600        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17601        let _subscriber =
17602            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17603        let (route_task, bind) = relay_route_open(
17604            &handler,
17605            client_connection,
17606            &client_ctx.egress,
17607            &mut module_rx,
17608            396,
17609            "aft",
17610            "hostile-module-code",
17611        )
17612        .await;
17613        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17614        let rejection = Frame::build(
17615            FrameType::Error,
17616            control_flags(),
17617            0,
17618            0,
17619            bind.header.corr,
17620            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17621        )
17622        .unwrap();
17623        handler
17624            .handle_control_frame(&module_ctx, rejection)
17625            .await
17626            .unwrap();
17627
17628        let response = route_task.await.unwrap();
17629        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17630        let counters = handler.counters().snapshot();
17631        assert_eq!(
17632            counters["route_open_refused_by_code"],
17633            json!({ "module_rejected": 1 })
17634        );
17635        assert!(counters["route_open_refused_by_code"]
17636            .get(hostile_code)
17637            .is_none());
17638
17639        let event = capture
17640            .events()
17641            .into_iter()
17642            .find(|event| {
17643                event.target == "control"
17644                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17645            })
17646            .expect("route.open module-rejection refusal event");
17647        let logged = event.fields.get("module_code").expect("module_code field");
17648        assert!(!logged.bytes().any(|byte| byte < 0x20));
17649        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17650    }
17651
17652    #[tokio::test]
17653    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17654        let registry = Arc::new(Registry::default());
17655        let supervisor_handle = SupervisorHandle::new();
17656        let missing_program = std::env::temp_dir().join(format!(
17657            "subc-route-open-missing-program-{}",
17658            std::process::id()
17659        ));
17660        let supervisor =
17661            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17662                .with_handle(supervisor_handle.clone());
17663        let module = supervisor
17664            .supervise_configured(
17665                ModuleSpec {
17666                    script: None,
17667                    carry_containment: false,
17668                    module_id: "failed".to_string(),
17669                    program: missing_program,
17670                    args: Vec::new(),
17671                    env: Vec::new(),
17672                    reserved: false,
17673                    reserved_prefixes: Vec::new(),
17674                    protocol: ModuleProtocol::Subc,
17675                    overlap: Default::default(),
17676                },
17677                true,
17678            )
17679            .unwrap();
17680        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17681
17682        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17683        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17684        let response = handler
17685            .handle_control_frame(
17686                &ctx,
17687                route_open_frame(305, "failed", unique_project_root("failed")),
17688            )
17689            .await
17690            .unwrap();
17691
17692        assert_eq!(response[0].header.ty, FrameType::Error);
17693        let error = parse_error(&response[0]);
17694        assert_eq!(error["code"], "target_unavailable");
17695        assert!(error["message"]
17696            .as_str()
17697            .unwrap()
17698            .contains("state=failed, enabled=true, live=false"));
17699    }
17700
17701    #[tokio::test]
17702    async fn route_open_role_mismatch_remains_target_unavailable() {
17703        let registry = Arc::new(Registry::default());
17704        let handler = ControlHandler::new(Arc::clone(&registry));
17705        handler
17706            .handle_control(
17707                ConnectionId::new(41),
17708                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17709            )
17710            .unwrap();
17711
17712        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17713        let response = handler
17714            .handle_control_frame(
17715                &ctx,
17716                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17717            )
17718            .await
17719            .unwrap();
17720
17721        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17722        assert!(parse_error(&response[0])["message"]
17723            .as_str()
17724            .unwrap()
17725            .contains("does not provide the requested target"));
17726    }
17727
17728    #[tokio::test]
17729    async fn route_open_inactive_registration_remains_target_unavailable() {
17730        let registry = Arc::new(Registry::default());
17731        let handler = ControlHandler::new(Arc::clone(&registry));
17732        handler
17733            .handle_control(
17734                ConnectionId::new(43),
17735                hello_frame("inactive", PROTOCOL_VERSION, 308),
17736            )
17737            .unwrap();
17738        assert!(registry
17739            .set_module_state_for_test("inactive", ChannelState::Closed)
17740            .unwrap());
17741
17742        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17743        let response = handler
17744            .handle_control_frame(
17745                &ctx,
17746                route_open_frame(309, "inactive", unique_project_root("inactive")),
17747            )
17748            .await
17749            .unwrap();
17750
17751        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17752        assert!(parse_error(&response[0])["message"]
17753            .as_str()
17754            .unwrap()
17755            .contains("is not active"));
17756    }
17757
17758    #[tokio::test]
17759    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17760        let registry = Arc::new(Registry::default());
17761        let forwarding = Arc::new(ForwardingTable::default());
17762        let supervisor_handle = SupervisorHandle::new();
17763        let supervisor =
17764            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17765                .with_forwarding(Arc::clone(&forwarding))
17766                .with_handle(supervisor_handle.clone());
17767        let module = supervisor
17768            .supervise_configured(
17769                crate::ModuleSpec {
17770                    script: None,
17771                    carry_containment: false,
17772                    module_id: "late-health-response".to_string(),
17773                    program: PathBuf::from("disabled-module"),
17774                    args: Vec::new(),
17775                    env: Vec::new(),
17776                    reserved: false,
17777                    reserved_prefixes: Vec::new(),
17778                    protocol: ModuleProtocol::Subc,
17779                    overlap: Default::default(),
17780                },
17781                false,
17782            )
17783            .unwrap();
17784        let handler =
17785            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17786                .with_supervisor(supervisor_handle);
17787        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17788        handler
17789            .handle_control_frame(
17790                &module_ctx,
17791                hello_frame_with_control_ops(
17792                    "late-health-response",
17793                    PROTOCOL_VERSION,
17794                    7,
17795                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17796                ),
17797            )
17798            .await
17799            .unwrap();
17800        let probe_started_at = Instant::now() - Duration::from_millis(80);
17801        let pending = forwarding
17802            .begin_health_probe_rpc_for(
17803                "late-health-response",
17804                MODULE_CONTROL_OP_HEALTH_CHECK,
17805                probe_started_at,
17806                Instant::now() - Duration::from_millis(1),
17807            )
17808            .unwrap();
17809        assert!(forwarding
17810            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17811            .unwrap());
17812
17813        let responses = handler
17814            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17815            .await
17816            .unwrap();
17817
17818        assert!(responses.is_empty());
17819        let health = module.status().unwrap().health;
17820        assert_eq!(health.late_answer_count, 1);
17821        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17822    }
17823
17824    #[tokio::test]
17825    async fn health_probe_timeout_and_module_death_are_typed() {
17826        let registry = Arc::new(Registry::default());
17827        let forwarding = Arc::new(ForwardingTable::default());
17828        let handler =
17829            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17830                .with_health_probe_timeout(Duration::from_millis(50));
17831        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17832        hello_via_sink(
17833            &handler,
17834            &module_ctx,
17835            &mut module_rx,
17836            hello_frame_with_control_ops(
17837                "aft",
17838                PROTOCOL_VERSION,
17839                7,
17840                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17841            ),
17842        )
17843        .await;
17844
17845        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17846        let responses = handler
17847            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17848            .await
17849            .unwrap();
17850        assert_eq!(responses[0].header.ty, FrameType::Error);
17851        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17852        let _ = module_rx.try_recv();
17853
17854        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17855        let health_handler = handler.clone();
17856        let death_task = tokio::spawn(async move {
17857            health_handler
17858                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17859                .await
17860                .unwrap()
17861        });
17862        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17863            .await
17864            .unwrap()
17865            .unwrap();
17866        handler
17867            .cleanup_connection(module_ctx.connection_id)
17868            .unwrap();
17869        let responses = death_task.await.unwrap();
17870        assert_eq!(responses[0].header.ty, FrameType::Error);
17871        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17872    }
17873
17874    #[test]
17875    fn hello_requires_exact_protocol_version() {
17876        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17877            let registry = Arc::new(Registry::default());
17878            let handler = ControlHandler::new(Arc::clone(&registry));
17879            let responses = handler
17880                .handle_control(
17881                    ConnectionId::new(connection),
17882                    hello_frame("aft", offered, 9),
17883                )
17884                .unwrap();
17885
17886            assert_eq!(responses.len(), 1);
17887            assert_eq!(responses[0].header.ty, FrameType::Error);
17888            let error = parse_error(&responses[0]);
17889            assert_eq!(error["code"], "version_unsupported");
17890            assert!(registry.get_module("aft").unwrap().is_none());
17891            assert_eq!(registry.active_registration_count().unwrap(), 0);
17892        }
17893    }
17894
17895    #[test]
17896    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17897        let registry = Arc::new(Registry::default());
17898        let forwarding = Arc::new(ForwardingTable::default());
17899        let handler =
17900            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17901        let module_connection = ConnectionId::new(301);
17902        let registration = registry
17903            .register_with_control_ops(
17904                manifest("aft-push", PROTOCOL_VERSION),
17905                PROTOCOL_VERSION,
17906                module_connection,
17907                module_baseline_control_ops(),
17908            )
17909            .unwrap();
17910        let (module_tx, _module_rx) = mpsc::channel(8);
17911        let endpoint = forwarding
17912            .register_module_connection(
17913                module_connection,
17914                "aft-push".to_string(),
17915                PROTOCOL_VERSION,
17916                manifest_concurrency(&registration.manifest),
17917                FrameSink::new(module_tx),
17918            )
17919            .unwrap();
17920
17921        // A push op this version does not know is ignored (forward-compat), not errored.
17922        let unknown = Frame::build(
17923            FrameType::Push,
17924            control_flags(),
17925            0,
17926            0,
17927            5,
17928            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17929        )
17930        .unwrap();
17931        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17932        assert!(
17933            out.is_empty(),
17934            "unknown push op must be ignored, got {out:?}"
17935        );
17936
17937        // A malformed body for a KNOWN op is a real error worth surfacing.
17938        let malformed = Frame::build(
17939            FrameType::Push,
17940            control_flags(),
17941            0,
17942            0,
17943            6,
17944            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17945        )
17946        .unwrap();
17947        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17948        assert_eq!(out.len(), 1);
17949        assert_eq!(out[0].header.ty, FrameType::Error);
17950        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17951    }
17952
17953    #[test]
17954    fn hello_rejected_when_connection_already_owns_client_routes() {
17955        let registry = Arc::new(Registry::default());
17956        let forwarding = Arc::new(ForwardingTable::default());
17957        let handler =
17958            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17959        // Commits a client route on connection 202 (bound to a module on conn 101).
17960        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17961        let client_connection = ConnectionId::new(202);
17962
17963        // That same connection now tries to register as a module: rejected, so one
17964        // connection never holds both client-route and module-endpoint state.
17965        let responses = handler
17966            .handle_control(
17967                client_connection,
17968                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17969            )
17970            .unwrap();
17971        assert_eq!(responses[0].header.ty, FrameType::Error);
17972        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17973        assert!(registry.get_module("aft-second").unwrap().is_none());
17974    }
17975
17976    #[tokio::test]
17977    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17978        let registry = Arc::new(Registry::default());
17979        let forwarding = Arc::new(ForwardingTable::default());
17980        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
17981        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
17982        hello_via_sink(
17983            &handler,
17984            &module_ctx,
17985            &mut module_rx,
17986            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
17987        )
17988        .await;
17989        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
17990        let pending = forwarding
17991            .begin_route_bind_relay_for_test(
17992                client_ctx.connection_id,
17993                client_ctx.egress.clone(),
17994                2,
17995                "alpha",
17996            )
17997            .unwrap();
17998        forwarding
17999            .complete_pending_relay(
18000                module_ctx.connection_id,
18001                pending.corr,
18002                RouteBindRelayOutcome::Accepted,
18003            )
18004            .unwrap();
18005        client_rx.try_recv().unwrap();
18006        for module_id in ["beta", "alpha"] {
18007            let replies = handler
18008                .handle_control_frame(
18009                    &module_ctx,
18010                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
18011                )
18012                .await
18013                .unwrap();
18014            assert_eq!(replies.len(), 1, "second HELLO must be refused");
18015            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
18016        }
18017        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
18018        assert!(registry.get_module("beta").unwrap().is_none());
18019        assert!(matches!(
18020            forwarding
18021                .lookup_data_route(
18022                    client_ctx.connection_id,
18023                    pending.client_channel,
18024                    pending.client_epoch,
18025                )
18026                .unwrap(),
18027            DataRoute::Client(DataRouteState::Bound(_))
18028        ));
18029        assert!(handler
18030            .hello_launch_nonces
18031            .lock()
18032            .unwrap()
18033            .presented(module_ctx.connection_id, Some("alpha-nonce")));
18034        assert!(module_rx.try_recv().is_err());
18035    }
18036
18037    #[test]
18038    fn reserved_module_hello_requires_matching_launch_nonce() {
18039        let registry = Arc::new(Registry::default());
18040        let supervisor = SupervisorHandle::new();
18041        // The supervisor recorded the nonce it injected when it spawned the reserved
18042        // module; the HELLO verifier checks against the same shared handle.
18043        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
18044        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18045
18046        // A HELLO with NO nonce is rejected.
18047        let no_nonce = handler
18048            .handle_control(
18049                ConnectionId::new(1),
18050                hello_frame("vault", PROTOCOL_VERSION, 1),
18051            )
18052            .unwrap();
18053        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
18054        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
18055        assert!(registry.get_module("vault").unwrap().is_none());
18056
18057        // A HELLO with the WRONG nonce is rejected.
18058        let wrong = handler
18059            .handle_control(
18060                ConnectionId::new(2),
18061                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
18062            )
18063            .unwrap();
18064        assert_eq!(wrong[0].header.ty, FrameType::Error);
18065        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
18066        assert!(registry.get_module("vault").unwrap().is_none());
18067
18068        // A HELLO with the CORRECT nonce registers.
18069        let ok = handler
18070            .handle_control(
18071                ConnectionId::new(3),
18072                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
18073            )
18074            .unwrap();
18075        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18076        assert!(registry.get_module("vault").unwrap().is_some());
18077    }
18078
18079    #[test]
18080    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18081        let registry = Arc::new(Registry::default());
18082        let supervisor = SupervisorHandle::new();
18083        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18084        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18085        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18086
18087        let squat = handler
18088            .handle_control(
18089                ConnectionId::new(1),
18090                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18091            )
18092            .unwrap();
18093        assert_eq!(squat[0].header.ty, FrameType::Error);
18094        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18095        assert!(parse_error(&squat[0])["message"]
18096            .as_str()
18097            .unwrap()
18098            .contains("fed:"));
18099
18100        let accepted_peer = handler
18101            .handle_control(
18102                ConnectionId::new(2),
18103                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18104            )
18105            .unwrap();
18106        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18107
18108        let accepted_short = handler
18109            .handle_control(
18110                ConnectionId::new(3),
18111                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18112            )
18113            .unwrap();
18114        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18115
18116        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18117            let response = handler
18118                .handle_control(
18119                    ConnectionId::new(conn),
18120                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18121                )
18122                .unwrap();
18123            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18124        }
18125    }
18126
18127    #[test]
18128    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18129        let registry = Arc::new(Registry::default());
18130        let supervisor = SupervisorHandle::new();
18131        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18132        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18133        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18134        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18135
18136        let owner_nonce = handler
18137            .handle_control(
18138                ConnectionId::new(1),
18139                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18140            )
18141            .unwrap();
18142        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18143        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18144        assert!(registry.get_module("fed:special").unwrap().is_none());
18145
18146        let exact_nonce = handler
18147            .handle_control(
18148                ConnectionId::new(2),
18149                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18150            )
18151            .unwrap();
18152        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18153        assert!(registry.get_module("fed:special").unwrap().is_some());
18154    }
18155
18156    #[test]
18157    fn non_reserved_module_ignores_launch_nonce() {
18158        let registry = Arc::new(Registry::default());
18159        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18160        // registration succeeds whether a spawned process echoes a nonce or not.
18161        let handler = ControlHandler::new(Arc::clone(&registry));
18162        let no_nonce = handler
18163            .handle_control(
18164                ConnectionId::new(1),
18165                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18166            )
18167            .unwrap();
18168        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18169        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18170
18171        let echoed_nonce = handler
18172            .handle_control(
18173                ConnectionId::new(2),
18174                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18175            )
18176            .unwrap();
18177        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18178        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18179    }
18180
18181    #[test]
18182    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18183        let handler = ControlHandler::default();
18184        let conn = ConnectionId::new(1);
18185        let malformed = Frame::build(
18186            FrameType::Hello,
18187            control_flags(),
18188            0,
18189            0,
18190            3,
18191            b"{not json".to_vec(),
18192        )
18193        .unwrap();
18194
18195        let error = handler.handle_control(conn, malformed).unwrap();
18196        assert_eq!(error[0].header.ty, FrameType::Error);
18197        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18198
18199        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18200        let pong = handler.handle_control(conn, ping).unwrap();
18201        assert_eq!(pong[0].header.ty, FrameType::Pong);
18202        assert_eq!(pong[0].header.corr, 4);
18203    }
18204
18205    #[test]
18206    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18207        let registry = Arc::new(Registry::default());
18208        let handler = ControlHandler::new(Arc::clone(&registry));
18209
18210        handler
18211            .handle_control(
18212                ConnectionId::new(1),
18213                hello_frame("aft", PROTOCOL_VERSION, 1),
18214            )
18215            .unwrap();
18216        let duplicate = handler
18217            .handle_control(
18218                ConnectionId::new(2),
18219                hello_frame("aft", PROTOCOL_VERSION, 2),
18220            )
18221            .unwrap();
18222
18223        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18224        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18225        let registration = registry.get_module("aft").unwrap().unwrap();
18226        assert_eq!(registration.connection_id, ConnectionId::new(1));
18227    }
18228
18229    #[test]
18230    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18231        let registry = Arc::new(Registry::default());
18232        let forwarding = Arc::new(ForwardingTable::default());
18233        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18234        let handler =
18235            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18236                .with_process_liveness(process_liveness);
18237        let (ctx, route_channel, route_epoch) =
18238            bind_liveness_route(&registry, &forwarding, "aft-dead");
18239        let responses = handler
18240            .handle_route_poll(
18241                &ctx,
18242                route_poll_frame(41, PollKind::Liveness, route_channel),
18243                route_channel,
18244                route_epoch,
18245                PollKind::Liveness,
18246            )
18247            .unwrap();
18248
18249        assert_eq!(responses.len(), 1);
18250        assert_eq!(responses[0].header.ty, FrameType::Response);
18251        assert_route_poll_liveness(&responses[0], false);
18252    }
18253
18254    #[test]
18255    fn liveness_poll_without_process_source_uses_bound_route() {
18256        let registry = Arc::new(Registry::default());
18257        let forwarding = Arc::new(ForwardingTable::default());
18258        let handler =
18259            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18260        let (ctx, route_channel, route_epoch) =
18261            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18262        let responses = handler
18263            .handle_route_poll(
18264                &ctx,
18265                route_poll_frame(42, PollKind::Liveness, route_channel),
18266                route_channel,
18267                route_epoch,
18268                PollKind::Liveness,
18269            )
18270            .unwrap();
18271
18272        assert_route_poll_liveness(&responses[0], true);
18273    }
18274
18275    #[test]
18276    fn liveness_poll_untracked_process_source_uses_bound_route() {
18277        let registry = Arc::new(Registry::default());
18278        let forwarding = Arc::new(ForwardingTable::default());
18279        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18280        let handler =
18281            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18282                .with_process_liveness(process_liveness);
18283        let (ctx, route_channel, route_epoch) =
18284            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18285        let responses = handler
18286            .handle_route_poll(
18287                &ctx,
18288                route_poll_frame(43, PollKind::Liveness, route_channel),
18289                route_channel,
18290                route_epoch,
18291                PollKind::Liveness,
18292            )
18293            .unwrap();
18294
18295        assert_route_poll_liveness(&responses[0], true);
18296    }
18297
18298    #[tokio::test]
18299    async fn unknown_op_returns_unknown_control_op() {
18300        let handler = ControlHandler::default();
18301        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18302        let request = Frame::build(
18303            FrameType::Request,
18304            control_flags(),
18305            0,
18306            0,
18307            55,
18308            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18309        )
18310        .unwrap();
18311
18312        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18313
18314        assert_eq!(response.len(), 1);
18315        assert_eq!(response[0].header.ty, FrameType::Error);
18316        assert_eq!(response[0].header.corr, 55);
18317        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18318    }
18319
18320    #[tokio::test]
18321    async fn supervisor_provenance_rejects_unknown_exact_module() {
18322        let handler = ControlHandler::default();
18323        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18324        let request = Frame::build(
18325            FrameType::Request,
18326            control_flags(),
18327            0,
18328            0,
18329            57,
18330            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18331        )
18332        .unwrap();
18333
18334        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18335
18336        assert_eq!(response.len(), 1);
18337        assert_eq!(response[0].header.ty, FrameType::Error);
18338        assert_eq!(response[0].header.corr, 57);
18339        let error = parse_error(&response[0]);
18340        assert_eq!(error["code"], "unknown_module");
18341        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18342    }
18343
18344    #[test]
18345    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18346        let expected = subc_control::RunningImageAgreement::Unavailable {
18347            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18348        };
18349        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18350        assert_eq!(handler.provenance_probe_override, Some(expected));
18351    }
18352
18353    #[test]
18354    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18355        let verdict = reload_verdict(
18356            std::path::Path::new("/bin/new"),
18357            Some(std::path::Path::new("/bin/old")),
18358            subc_control::RunningImageAgreement::Unavailable {
18359                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18360            },
18361        );
18362        assert!(matches!(
18363            verdict.path,
18364            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18365                if configured == std::path::Path::new("/bin/new")
18366                    && spawned_from == std::path::Path::new("/bin/old")
18367        ));
18368    }
18369
18370    #[test]
18371    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18372        use subc_control::{
18373            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18374        };
18375        let configured = crate::supervise::ModuleSpec {
18376            script: None,
18377            carry_containment: false,
18378            module_id: "legacy".into(),
18379            program: "/module".into(),
18380            args: Vec::new(),
18381            env: Vec::new(),
18382            reserved: false,
18383            reserved_prefixes: Vec::new(),
18384            protocol: subc_control::ModuleProtocol::Subc,
18385            overlap: Default::default(),
18386        };
18387        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18388        assert_eq!(
18389            launch_spec_agreement(&configured, false, Some(&digest)),
18390            Agreement::Unavailable {
18391                reason: Reason::NotRunning
18392            }
18393        );
18394        assert_eq!(
18395            launch_spec_agreement(&configured, true, None),
18396            Agreement::Unavailable {
18397                reason: Reason::SpawnedSpecUnavailable
18398            }
18399        );
18400        assert_eq!(
18401            launch_spec_agreement(&configured, true, Some(&digest)),
18402            Agreement::Match
18403        );
18404    }
18405
18406    #[cfg(windows)]
18407    #[test]
18408    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18409        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18410        let configured = dir.join("module.exe");
18411        std::fs::write(&configured, b"executable path fixture").unwrap();
18412        let spawned = std::fs::canonicalize(&configured).unwrap();
18413        assert_ne!(
18414            configured, spawned,
18415            "fixture must exercise different path spellings"
18416        );
18417        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18418        let lower_case = configured.to_string_lossy().to_lowercase();
18419        for spelling in [
18420            &configured,
18421            Path::new(&forward_slashes),
18422            Path::new(&lower_case),
18423        ] {
18424            let verdict = reload_verdict(
18425                spelling,
18426                Some(&spawned),
18427                subc_control::RunningImageAgreement::Unavailable {
18428                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18429                },
18430            );
18431            assert_eq!(
18432                verdict.path,
18433                ReloadPathAgreement::Match,
18434                "configured {spelling:?}, spawned {spawned:?}"
18435            );
18436        }
18437    }
18438
18439    #[cfg(windows)]
18440    #[test]
18441    fn windows_reload_path_keeps_different_existing_program_pending() {
18442        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18443        let old = dir.join("old.exe");
18444        let new = dir.join("new.exe");
18445        std::fs::write(&old, b"same executable content").unwrap();
18446        std::fs::copy(&old, &new).unwrap();
18447        let spawned = std::fs::canonicalize(&old).unwrap();
18448        let image = subc_control::RunningImageAgreement::Unavailable {
18449            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18450        };
18451        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18452        assert!(
18453            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18454            if configured == new && spawned_from == spawned)
18455        );
18456        let missing = dir.join("missing.exe");
18457        assert!(matches!(
18458            reload_verdict(&missing, Some(&spawned), image).path,
18459            ReloadPathAgreement::Mismatch { .. }
18460        ));
18461    }
18462
18463    #[test]
18464    fn reload_verdict_detects_replaced_image_at_same_path() {
18465        let image = subc_control::RunningImageAgreement::Mismatch {
18466            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18467                digest: "old".into(),
18468            },
18469            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18470                digest: "new".into(),
18471            },
18472        };
18473        let verdict = reload_verdict(
18474            std::path::Path::new("/bin/same"),
18475            Some(std::path::Path::new("/bin/same")),
18476            image.clone(),
18477        );
18478        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18479        assert_eq!(verdict.image, image);
18480    }
18481
18482    #[test]
18483    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18484        let image = subc_control::RunningImageAgreement::Unavailable {
18485            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18486        };
18487        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18488        assert_eq!(
18489            verdict.path,
18490            subc_control::ReloadPathAgreement::Unavailable {
18491                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18492            }
18493        );
18494        assert_eq!(verdict.image, image);
18495
18496        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18497            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18498        };
18499        let verdict = reload_verdict(
18500            std::path::Path::new("/bin/same"),
18501            Some(std::path::Path::new("/bin/same")),
18502            unconfirmed.clone(),
18503        );
18504        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18505        assert_eq!(verdict.image, unconfirmed);
18506    }
18507
18508    #[test]
18509    fn reload_verdict_preserves_each_image_unavailability_reason() {
18510        use subc_control::RunningImageUnavailableReason as Reason;
18511
18512        for reason in [
18513            Reason::NotRunning,
18514            Reason::UnsupportedPlatform,
18515            Reason::RunningExecutableUnreadable,
18516            Reason::SpawnedPathUnreadable,
18517            Reason::HashFailed,
18518            Reason::ProcessIdentityUnconfirmed,
18519            Reason::Unknown("future_probe_reason".to_string()),
18520        ] {
18521            let image = subc_control::RunningImageAgreement::Unavailable {
18522                reason: reason.clone(),
18523            };
18524            let verdict = reload_verdict(
18525                std::path::Path::new("/bin/same"),
18526                Some(std::path::Path::new("/bin/same")),
18527                image.clone(),
18528            );
18529            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18530            assert_eq!(verdict.image, image, "{reason:?}");
18531        }
18532    }
18533
18534    #[tokio::test]
18535    async fn malformed_control_bodies_return_invalid_control_body() {
18536        let handler = ControlHandler::default();
18537        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18538
18539        for (corr, body) in [
18540            (56, br#"{"route_channel":1}"#.as_slice()),
18541            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18542            (
18543                58,
18544                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18545            ),
18546        ] {
18547            let request = Frame::build(
18548                FrameType::Request,
18549                control_flags(),
18550                0,
18551                0,
18552                corr,
18553                body.to_vec(),
18554            )
18555            .unwrap();
18556            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18557
18558            assert_eq!(response.len(), 1);
18559            assert_eq!(response[0].header.ty, FrameType::Error);
18560            assert_eq!(response[0].header.corr, corr);
18561            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18562        }
18563    }
18564
18565    #[tokio::test]
18566    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18567        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18568        let registry = Arc::new(Registry::default());
18569        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18570        let router = Router::with_control_handler(Arc::clone(&control));
18571        let connection = router.begin_connection();
18572        let (ctx, mut rx) = route_ctx(connection.id());
18573
18574        router
18575            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18576            .await
18577            .unwrap();
18578        let response = rx.recv().await.unwrap();
18579        let ack = parse_ack(&response);
18580        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18581        let channel = 1;
18582
18583        let goodbye =
18584            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18585        router.route_for_connection(&ctx, goodbye).await.unwrap();
18586        assert!(rx.try_recv().is_err());
18587        assert!(registry.get_module("aft").unwrap().is_none());
18588
18589        router
18590            .route_for_connection(&ctx, channel_request(channel, 13))
18591            .await
18592            .unwrap();
18593        let error_frame = rx.recv().await.unwrap();
18594        assert_eq!(error_frame.header.ty, FrameType::Error);
18595        assert_eq!(error_frame.header.channel, channel);
18596        let captured = crate::router::test_log::captured_logs(&logs);
18597        assert_eq!(
18598            captured
18599                .lines()
18600                .filter(|line| {
18601                    line.contains("module_id=aft")
18602                        && line.contains("reason=explicit_goodbye")
18603                        && line.contains("module registration ended")
18604                })
18605                .count(),
18606            1,
18607            "unexpected GOODBYE registry log: {captured}"
18608        );
18609    }
18610
18611    #[tokio::test]
18612    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18613        let registry = Arc::new(Registry::default());
18614        let handler = ControlHandler::new(registry).with_capability_config(
18615            [("prov".to_string(), true), ("cons".to_string(), true)],
18616            BTreeMap::new(),
18617        );
18618        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18619        register_capability_manifest(
18620            &handler,
18621            &provider_ctx,
18622            &mut provider_rx,
18623            capability_manifest("prov", &["thing/v1"], &[]),
18624            1,
18625        )
18626        .await;
18627        let mut consumer = capability_manifest("cons", &[], &[]);
18628        consumer.capabilities.as_mut().unwrap().requires.push(
18629            subc_protocol::manifest::CapabilityRequirement {
18630                capability: "thing/v1".to_string(),
18631                need: subc_protocol::manifest::CapabilityNeed::Required,
18632            },
18633        );
18634        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18635        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18636        assert_eq!(
18637            handler.capability_evaluator.verdict("cons", "thing/v1"),
18638            Some(CapabilityVerdict::Provided)
18639        );
18640        let (mut client_rx, _) = open_route_for_capability_test(
18641            &handler,
18642            &provider_ctx,
18643            &mut provider_rx,
18644            703,
18645            3,
18646            "prov",
18647            None,
18648        )
18649        .await;
18650        let goodbye =
18651            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18652        handler
18653            .handle_control_frame(&provider_ctx, goodbye)
18654            .await
18655            .unwrap();
18656        assert_eq!(
18657            handler.capability_evaluator.verdict("cons", "thing/v1"),
18658            Some(CapabilityVerdict::NeverProvided)
18659        );
18660        let closed = client_rx
18661            .try_recv()
18662            .expect("GOODBYE pushes route.closed before route GOODBYE");
18663        assert!(
18664            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18665            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18666        );
18667        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18668        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18669    }
18670
18671    struct RouteClosedFixture {
18672        handler: ControlHandler,
18673        #[cfg(unix)]
18674        supervisor: Supervisor,
18675        module_ctx: RouteCtx,
18676        #[cfg(unix)]
18677        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18678        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18679        route: Arc<crate::forwarding::RouteBinding>,
18680    }
18681
18682    async fn route_closed_fixture() -> RouteClosedFixture {
18683        let registry = Arc::new(Registry::default());
18684        let handler = ControlHandler::new(Arc::clone(&registry));
18685        #[cfg(unix)]
18686        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18687            .with_forwarding(Arc::clone(&handler.forwarding));
18688        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18689        register_capability_manifest(
18690            &handler,
18691            &module_ctx,
18692            &mut module_rx,
18693            capability_manifest("prov", &[], &[]),
18694            1,
18695        )
18696        .await;
18697        let (client_rx, bind) = open_route_for_capability_test(
18698            &handler,
18699            &module_ctx,
18700            &mut module_rx,
18701            702,
18702            2,
18703            "prov",
18704            None,
18705        )
18706        .await;
18707        let ModuleControlRequest::RouteBind {
18708            route_channel: channel,
18709            epoch: route_epoch,
18710            ..
18711        } = bind
18712        else {
18713            panic!("expected route.bind");
18714        };
18715        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18716            handler
18717                .forwarding
18718                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18719                .unwrap()
18720        else {
18721            panic!("the acknowledged route must be bound");
18722        };
18723        RouteClosedFixture {
18724            handler,
18725            #[cfg(unix)]
18726            supervisor,
18727            module_ctx,
18728            #[cfg(unix)]
18729            module_rx,
18730            client_rx,
18731            route,
18732        }
18733    }
18734
18735    impl RouteClosedFixture {
18736        #[cfg(unix)]
18737        async fn cut(&mut self) {
18738            let notices = async {
18739                let mut draining = self.module_rx.recv().await.unwrap();
18740                assert!(matches!(
18741                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18742                        &draining.body
18743                    )
18744                    .unwrap(),
18745                    subc_protocol::session::ModuleControlCommand::Draining {
18746                        reason: RouteCloseReason::Disable,
18747                        ..
18748                    }
18749                ));
18750                draining.flushed.take().unwrap().send(()).unwrap();
18751                let mut closing = self.client_rx.recv().await.unwrap();
18752                assert!(matches!(
18753                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18754                    ClientControlPush::RouteClosing {
18755                        reason: RouteCloseReason::Restart,
18756                        ..
18757                    }
18758                ));
18759                closing.flushed.take().unwrap().send(()).unwrap();
18760            };
18761            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18762            result.unwrap();
18763        }
18764
18765        fn disconnect(&mut self) -> ClientControlPush {
18766            self.handler
18767                .cleanup_connection(self.module_ctx.connection_id)
18768                .unwrap();
18769            let closed = self.client_rx.try_recv().unwrap();
18770            assert_eq!(closed.header.ty, FrameType::Push);
18771            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18772            assert!(matches!(
18773                &push,
18774                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18775                    if channels == &[self.route.client_channel]
18776            ));
18777            assert_eq!(
18778                self.client_rx.try_recv().unwrap().header.ty,
18779                FrameType::Goodbye
18780            );
18781            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18782            push
18783        }
18784    }
18785
18786    #[cfg(unix)]
18787    #[tokio::test(start_paused = true)]
18788    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18789        let mut fixture = route_closed_fixture().await;
18790        fixture.cut().await;
18791        assert!(matches!(
18792            fixture.disconnect(),
18793            ClientControlPush::RouteClosed {
18794                reason: RouteCloseReason::Restart,
18795                drained: true,
18796                ..
18797            }
18798        ));
18799    }
18800
18801    #[cfg(unix)]
18802    #[tokio::test(start_paused = true)]
18803    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18804        let mut fixture = route_closed_fixture().await;
18805        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18806        let started = tokio::time::Instant::now();
18807        fixture.cut().await;
18808        assert!(started.elapsed() >= Duration::from_secs(2));
18809        assert_eq!(fixture.route.flow.in_flight(), 1);
18810        assert!(matches!(
18811            fixture.disconnect(),
18812            ClientControlPush::RouteClosed {
18813                reason: RouteCloseReason::Restart,
18814                drained: false,
18815                ..
18816            }
18817        ));
18818    }
18819
18820    #[tokio::test]
18821    async fn module_connection_crash_reports_crash_and_not_drained() {
18822        let mut fixture = route_closed_fixture().await;
18823        // The server calls cleanup_connection on module EOF. Without a planned
18824        // daemon shutdown, that disconnect must remain a crash with no prior
18825        // route.closing notice, even when the route has no in-flight calls.
18826        assert!(matches!(
18827            fixture.disconnect(),
18828            ClientControlPush::RouteClosed {
18829                reason: RouteCloseReason::Crash,
18830                drained: false,
18831                ..
18832            }
18833        ));
18834    }
18835
18836    #[tokio::test]
18837    async fn dropping_router_connection_releases_registration() {
18838        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18839        let registry = Arc::new(Registry::default());
18840        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18841        let router = Router::with_control_handler(Arc::clone(&control));
18842        let connection = router.begin_connection();
18843        let connection_id = connection.id();
18844        let (ctx, mut rx) = route_ctx(connection_id);
18845
18846        router
18847            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18848            .await
18849            .unwrap();
18850        let response = rx.recv().await.unwrap();
18851        let ack = parse_ack(&response);
18852        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18853        assert!(registry.get_module("aft").unwrap().is_some());
18854
18855        drop(connection);
18856
18857        assert!(registry.get_module("aft").unwrap().is_none());
18858        assert_eq!(registry.active_registration_count().unwrap(), 0);
18859
18860        control
18861            .cleanup_connection(ConnectionId::new(u64::MAX))
18862            .unwrap();
18863        let captured = crate::router::test_log::captured_logs(&logs);
18864        println!("captured registry lifecycle logs:\n{captured}");
18865        let events: Vec<_> = captured
18866            .lines()
18867            .filter(|line| {
18868                line.contains("module registered module_id=aft ")
18869                    || line.contains("module registration ended")
18870            })
18871            .collect();
18872        assert_eq!(
18873            events.len(),
18874            2,
18875            "unexpected registry lifecycle logs: {captured}"
18876        );
18877        assert!(events[0].contains("module registered module_id=aft "));
18878        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18879        assert!(events[1].contains(&format!(
18880            "module_id=aft connection_id={}",
18881            connection_id.get()
18882        )));
18883        assert!(events[1].contains("reason=connection_closed"));
18884        assert!(events[1].contains("module registration ended"));
18885        assert_eq!(
18886            captured
18887                .lines()
18888                .filter(|line| line.contains("module registered module_id=aft "))
18889                .count(),
18890            1,
18891            "legacy registration admission line must appear once: {captured}"
18892        );
18893    }
18894
18895    #[tokio::test]
18896    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18897        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18898        let registry = Arc::new(Registry::default());
18899        let control = ControlHandler::new(Arc::clone(&registry));
18900        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18901        hello_via_sink(
18902            &control,
18903            &ctx,
18904            &mut rx,
18905            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18906        )
18907        .await;
18908
18909        let captured = crate::router::test_log::captured_logs(&logs);
18910        let admissions: Vec<_> = captured
18911            .lines()
18912            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18913            .collect();
18914        assert_eq!(
18915            admissions.len(),
18916            1,
18917            "legacy admission line must remain exactly once: {captured}"
18918        );
18919        assert!(admissions[0].contains("routable_provider=true"));
18920        assert!(admissions[0].contains("connection_id=777"));
18921    }
18922
18923    fn capability_manifest(
18924        module_id: &str,
18925        provides: &[&str],
18926        must_never_reach: &[&str],
18927    ) -> ModuleManifest {
18928        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18929        manifest.capabilities = Some(CapabilityDeclarations {
18930            provides: provides
18931                .iter()
18932                .map(|capability| (*capability).to_string())
18933                .collect(),
18934            requires: Vec::new(),
18935            must_never_reach: must_never_reach
18936                .iter()
18937                .map(|capability| (*capability).to_string())
18938                .collect(),
18939        });
18940        manifest
18941    }
18942
18943    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18944        Frame::build(
18945            FrameType::Hello,
18946            control_flags(),
18947            0,
18948            0,
18949            corr,
18950            serde_json::to_vec(&ModuleHelloBody {
18951                protocol_ver: manifest.protocol_ver,
18952                manifest,
18953                control_ops: None,
18954                launch_nonce: None,
18955            })
18956            .expect("capability test HELLO serializes"),
18957        )
18958        .expect("capability test HELLO frame builds")
18959    }
18960
18961    fn catalog_update_with_capabilities_frame(
18962        corr: u64,
18963        capabilities: CapabilityDeclarations,
18964    ) -> Frame {
18965        Frame::build(
18966            FrameType::Request,
18967            control_flags(),
18968            0,
18969            0,
18970            corr,
18971            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18972                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18973                capabilities: Some(capabilities),
18974                ready: None,
18975            })
18976            .expect("capability catalog.update serializes"),
18977        )
18978        .expect("capability catalog.update frame builds")
18979    }
18980
18981    async fn register_capability_manifest(
18982        handler: &ControlHandler,
18983        ctx: &RouteCtx,
18984        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18985        manifest: ModuleManifest,
18986        corr: u64,
18987    ) {
18988        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
18989    }
18990
18991    async fn open_route_for_capability_test(
18992        handler: &ControlHandler,
18993        target_ctx: &RouteCtx,
18994        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18995        client_connection_id: u64,
18996        corr: u64,
18997        target_module_id: &str,
18998        consumer_identity: Option<ConsumerIdentity>,
18999    ) -> (
19000        mpsc::Receiver<crate::router::OutboundFrame>,
19001        ModuleControlRequest,
19002    ) {
19003        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
19004        let route_handler = handler.clone();
19005        let target_module_id = target_module_id.to_string();
19006        let route_task = tokio::spawn(async move {
19007            route_handler
19008                .handle_control_frame(
19009                    &client_ctx,
19010                    route_open_frame_with_admission_facts(
19011                        corr,
19012                        &target_module_id,
19013                        unique_project_root("admission-facts"),
19014                        consumer_identity,
19015                        None,
19016                    ),
19017                )
19018                .await
19019                .expect("capability test route.open succeeds")
19020        });
19021        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
19022            .await
19023            .expect("capability test route.open must reach route.bind")
19024            .expect("target control receiver stays open");
19025        let bind_request: ModuleControlRequest =
19026            serde_json::from_slice(&bind.body).expect("route.bind decodes");
19027        handler
19028            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
19029            .await
19030            .expect("capability test route.bind ACK succeeds");
19031        assert!(route_task.await.expect("route.open task joins").is_empty());
19032        let opened = client_rx
19033            .recv()
19034            .await
19035            .expect("successful route.open publishes a response");
19036        assert!(matches!(
19037            serde_json::from_slice::<ClientControlResponse>(&opened.body),
19038            Ok(ClientControlResponse::RouteOpen { .. })
19039        ));
19040        (client_rx, bind_request)
19041    }
19042
19043    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
19044        assert_eq!(frame.header.ty, FrameType::Push);
19045        assert_eq!(frame.header.channel, 0);
19046        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
19047            .expect("route.closed control push decodes");
19048        let ClientControlPush::RouteClosed { channels, .. } = &push else {
19049            panic!("expected route.closed");
19050        };
19051        assert_eq!(channels.len(), 1, "exactly one violating route closed");
19052        let closed_channel = channels[0];
19053        let channels = channels.clone();
19054        assert_eq!(
19055            push,
19056            ClientControlPush::RouteClosed {
19057                module_id: target_module_id.to_string(),
19058                channels,
19059                reason: RouteCloseReason::CapabilityDenied,
19060                drained: false,
19061                abandoned: 0,
19062                excluded_subscriptions: 0,
19063                terminal: Some(false),
19064            }
19065        );
19066        closed_channel
19067    }
19068
19069    #[tokio::test]
19070    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
19071        let registry = Arc::new(Registry::default());
19072        let forwarding = Arc::new(ForwardingTable::default());
19073        let supervisor = SupervisorHandle::new();
19074        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19075        let handler =
19076            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19077                .with_supervisor(supervisor);
19078        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19079        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19080        register_capability_manifest(
19081            &handler,
19082            &target_ctx,
19083            &mut target_rx,
19084            capability_manifest("target", &["credentials-provider/v1"], &[]),
19085            1,
19086        )
19087        .await;
19088        register_capability_manifest(
19089            &handler,
19090            &opener_ctx,
19091            &mut opener_rx,
19092            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19093            2,
19094        )
19095        .await;
19096
19097        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19098        let replies = handler
19099            .handle_control_frame(
19100                &client_ctx,
19101                route_open_frame_with_admission_facts(
19102                    3,
19103                    "target",
19104                    unique_project_root("admission-facts"),
19105                    Some(ConsumerIdentity {
19106                        module_id: "opener".to_string(),
19107                        launch_nonce: "opener-nonce".to_string(),
19108                    }),
19109                    None,
19110                ),
19111            )
19112            .await
19113            .expect("denied route.open returns a typed frame");
19114        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19115        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19116        assert!(
19117            target_rx.try_recv().is_err(),
19118            "forbidden route.open must not relay route.bind"
19119        );
19120    }
19121
19122    #[tokio::test]
19123    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19124        let registry = Arc::new(Registry::default());
19125        let forwarding = Arc::new(ForwardingTable::default());
19126        let supervisor = SupervisorHandle::new();
19127        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19128        let handler =
19129            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19130                .with_supervisor(supervisor);
19131        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19132        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19133        register_capability_manifest(
19134            &handler,
19135            &target_ctx,
19136            &mut target_rx,
19137            capability_manifest("target", &["credentials-provider/v1"], &[]),
19138            1,
19139        )
19140        .await;
19141        register_capability_manifest(
19142            &handler,
19143            &old_opener_ctx,
19144            &mut old_opener_rx,
19145            capability_manifest("opener", &[], &[]),
19146            2,
19147        )
19148        .await;
19149        let (mut client_rx, _) = open_route_for_capability_test(
19150            &handler,
19151            &target_ctx,
19152            &mut target_rx,
19153            712,
19154            3,
19155            "target",
19156            Some(ConsumerIdentity {
19157                module_id: "opener".to_string(),
19158                launch_nonce: "opener-nonce".to_string(),
19159            }),
19160        )
19161        .await;
19162        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19163
19164        handler
19165            .cleanup_connection(old_opener_ctx.connection_id)
19166            .expect("old opener registration cleans up");
19167        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19168        register_capability_manifest(
19169            &handler,
19170            &new_opener_ctx,
19171            &mut new_opener_rx,
19172            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19173            4,
19174        )
19175        .await;
19176
19177        let closed_channel = assert_capability_denied_push(
19178            client_rx
19179                .try_recv()
19180                .expect("HELLO deny addition must emit route.closed")
19181                .frame,
19182            "target",
19183        );
19184        let goodbye = client_rx
19185            .try_recv()
19186            .expect("HELLO deny addition must send the client a route GOODBYE")
19187            .frame;
19188        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19189        assert_eq!(goodbye.header.channel, closed_channel);
19190        assert_ne!(goodbye.header.channel, 0);
19191        assert_ne!(goodbye.header.epoch, 0);
19192        assert!(client_rx.try_recv().is_err());
19193        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19194        assert!(matches!(
19195            target_rx.try_recv(),
19196            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19197        ));
19198    }
19199
19200    #[tokio::test]
19201    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19202        let registry = Arc::new(Registry::default());
19203        let forwarding = Arc::new(ForwardingTable::default());
19204        let supervisor = SupervisorHandle::new();
19205        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19206        let handler =
19207            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19208                .with_supervisor(supervisor);
19209        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19210        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19211        register_capability_manifest(
19212            &handler,
19213            &target_ctx,
19214            &mut target_rx,
19215            capability_manifest("target", &[], &[]),
19216            1,
19217        )
19218        .await;
19219        register_capability_manifest(
19220            &handler,
19221            &opener_ctx,
19222            &mut opener_rx,
19223            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19224            2,
19225        )
19226        .await;
19227        let (mut client_rx, _) = open_route_for_capability_test(
19228            &handler,
19229            &target_ctx,
19230            &mut target_rx,
19231            722,
19232            3,
19233            "target",
19234            Some(ConsumerIdentity {
19235                module_id: "opener".to_string(),
19236                launch_nonce: "opener-nonce".to_string(),
19237            }),
19238        )
19239        .await;
19240        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19241
19242        let replies = handler
19243            .handle_control_frame(
19244                &target_ctx,
19245                catalog_update_with_capabilities_frame(
19246                    4,
19247                    CapabilityDeclarations {
19248                        provides: vec!["credentials-provider/v1".to_string()],
19249                        requires: Vec::new(),
19250                        must_never_reach: Vec::new(),
19251                    },
19252                ),
19253            )
19254            .await
19255            .expect("claim catalog.update succeeds");
19256        assert!(matches!(
19257            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19258            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19259        ));
19260        let closed_channel = assert_capability_denied_push(
19261            client_rx
19262                .try_recv()
19263                .expect("claim addition must emit route.closed")
19264                .frame,
19265            "target",
19266        );
19267        let goodbye = client_rx
19268            .try_recv()
19269            .expect("claim addition must send the client a route GOODBYE")
19270            .frame;
19271        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19272        assert_eq!(goodbye.header.channel, closed_channel);
19273        assert_ne!(goodbye.header.channel, 0);
19274        assert_ne!(goodbye.header.epoch, 0);
19275        assert!(client_rx.try_recv().is_err());
19276        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19277        assert!(matches!(
19278            target_rx.try_recv(),
19279            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19280        ));
19281    }
19282
19283    #[tokio::test]
19284    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19285        let registry = Arc::new(Registry::default());
19286        let forwarding = Arc::new(ForwardingTable::default());
19287        let supervisor = SupervisorHandle::new();
19288        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19289        let handler =
19290            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19291                .with_supervisor(supervisor);
19292        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19293        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19294        register_capability_manifest(
19295            &handler,
19296            &target_ctx,
19297            &mut target_rx,
19298            capability_manifest("target", &["credentials-provider/v1"], &[]),
19299            1,
19300        )
19301        .await;
19302        register_capability_manifest(
19303            &handler,
19304            &opener_ctx,
19305            &mut opener_rx,
19306            capability_manifest("opener", &[], &[]),
19307            2,
19308        )
19309        .await;
19310        let (mut client_rx, _) = open_route_for_capability_test(
19311            &handler,
19312            &target_ctx,
19313            &mut target_rx,
19314            732,
19315            3,
19316            "target",
19317            Some(ConsumerIdentity {
19318                module_id: "opener".to_string(),
19319                launch_nonce: "opener-nonce".to_string(),
19320            }),
19321        )
19322        .await;
19323        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19324
19325        handler
19326            .handle_control_frame(
19327                &target_ctx,
19328                catalog_update_with_capabilities_frame(
19329                    4,
19330                    CapabilityDeclarations {
19331                        provides: Vec::new(),
19332                        requires: Vec::new(),
19333                        must_never_reach: Vec::new(),
19334                    },
19335                ),
19336            )
19337            .await
19338            .expect("claim removal catalog.update succeeds");
19339        assert_eq!(
19340            forwarding.active_binding_count().unwrap(),
19341            1,
19342            "removing an attested target claim must leave the route census unchanged"
19343        );
19344        assert!(
19345            client_rx.try_recv().is_err(),
19346            "claim removal must not emit route.closed or a client route GOODBYE"
19347        );
19348        assert!(
19349            target_rx.try_recv().is_err(),
19350            "claim removal must not send the target a route GOODBYE"
19351        );
19352    }
19353
19354    /// A direct client may open a route to a denied capability provider; this
19355    /// policy applies only to attested supervised module origins, not to direct clients.
19356    #[tokio::test]
19357    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19358        let registry = Arc::new(Registry::default());
19359        let forwarding = Arc::new(ForwardingTable::default());
19360        let supervisor = SupervisorHandle::new();
19361        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19362        let handler =
19363            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19364                .with_supervisor(supervisor);
19365        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19366        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19367        register_capability_manifest(
19368            &handler,
19369            &target_ctx,
19370            &mut target_rx,
19371            capability_manifest("target", &["credentials-provider/v1"], &[]),
19372            1,
19373        )
19374        .await;
19375        register_capability_manifest(
19376            &handler,
19377            &opener_ctx,
19378            &mut opener_rx,
19379            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19380            2,
19381        )
19382        .await;
19383
19384        let (_client_rx, bind) = open_route_for_capability_test(
19385            &handler,
19386            &target_ctx,
19387            &mut target_rx,
19388            742,
19389            3,
19390            "target",
19391            None,
19392        )
19393        .await;
19394        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19395            panic!("direct scope-honesty route must bind");
19396        };
19397        assert_eq!(principal, Some(Principal::Direct));
19398        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19399    }
19400
19401    /// A module that denies a capability receives no self-route exemption when it
19402    /// also attestedly provides that capability.
19403    #[tokio::test]
19404    async fn must_never_reach_self_route_is_capability_forbidden() {
19405        let registry = Arc::new(Registry::default());
19406        let forwarding = Arc::new(ForwardingTable::default());
19407        let supervisor = SupervisorHandle::new();
19408        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19409        let handler =
19410            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19411                .with_supervisor(supervisor);
19412        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19413        register_capability_manifest(
19414            &handler,
19415            &self_ctx,
19416            &mut self_rx,
19417            capability_manifest(
19418                "self-provider",
19419                &["credentials-provider/v1"],
19420                &["credentials-provider/v1"],
19421            ),
19422            1,
19423        )
19424        .await;
19425
19426        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19427        let replies = handler
19428            .handle_control_frame(
19429                &client_ctx,
19430                route_open_frame_with_admission_facts(
19431                    2,
19432                    "self-provider",
19433                    unique_project_root("admission-facts"),
19434                    Some(ConsumerIdentity {
19435                        module_id: "self-provider".to_string(),
19436                        launch_nonce: "self-nonce".to_string(),
19437                    }),
19438                    None,
19439                ),
19440            )
19441            .await
19442            .expect("self-route refusal returns a typed frame");
19443        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19444        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19445        assert!(
19446            self_rx.try_recv().is_err(),
19447            "self denial must not relay route.bind"
19448        );
19449    }
19450
19451    #[test]
19452    fn unsupported_channel_zero_frame_returns_error() {
19453        let handler = ControlHandler::default();
19454        let request = Frame::build(
19455            FrameType::Request,
19456            control_flags(),
19457            0,
19458            0,
19459            21,
19460            b"opaque".to_vec(),
19461        )
19462        .unwrap();
19463
19464        let response = handler
19465            .handle_control(ConnectionId::new(1), request)
19466            .unwrap();
19467
19468        assert_eq!(response[0].header.ty, FrameType::Error);
19469        assert_eq!(
19470            parse_error(&response[0])["code"],
19471            "unsupported_control_frame"
19472        );
19473    }
19474
19475    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19476    /// a swap is not wired yet, so the candidate is registered here directly
19477    /// into the registry and forwarding candidate slots, the way the swap's
19478    /// HELLO admission will.
19479    mod swap {
19480        use super::*;
19481
19482        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19483        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19484
19485        struct Swap {
19486            registry: Arc<Registry>,
19487            forwarding: Arc<ForwardingTable>,
19488            handler: ControlHandler,
19489            incumbent_ctx: RouteCtx,
19490            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19491            candidate_ctx: RouteCtx,
19492            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19493        }
19494
19495        async fn swap_with_incumbent() -> Swap {
19496            let registry = Arc::new(Registry::default());
19497            let forwarding = Arc::new(ForwardingTable::default());
19498            let handler =
19499                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19500            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19501            hello_via_sink(
19502                &handler,
19503                &incumbent_ctx,
19504                &mut incumbent_rx,
19505                hello_frame("aft", PROTOCOL_VERSION, 7),
19506            )
19507            .await;
19508            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19509            Swap {
19510                registry,
19511                forwarding,
19512                handler,
19513                incumbent_ctx,
19514                incumbent_rx,
19515                candidate_ctx,
19516                candidate_rx,
19517            }
19518        }
19519
19520        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19521            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19522            candidate_manifest.ready = ready;
19523            let registration = swap
19524                .registry
19525                .register_candidate_with_control_ops(
19526                    candidate_manifest,
19527                    PROTOCOL_VERSION,
19528                    CANDIDATE,
19529                    module_baseline_control_ops(),
19530                )
19531                .unwrap();
19532            swap.forwarding
19533                .register_candidate_module_connection(
19534                    CANDIDATE,
19535                    "aft".to_string(),
19536                    PROTOCOL_VERSION,
19537                    manifest_concurrency(&registration.manifest),
19538                    swap.candidate_ctx.egress.clone(),
19539                )
19540                .unwrap();
19541        }
19542
19543        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19544            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19545            swap.registry.promote_candidate("aft").unwrap().unwrap();
19546            cutover.incumbent.unwrap()
19547        }
19548
19549        /// A swap candidate's HELLO reserves its candidate registry entry
19550        /// before installing its candidate forwarding endpoint. The swap
19551        /// supervisor promotes a ready candidate as soon as it reads it as
19552        /// registered, and promotion cuts forwarding over to the candidate
19553        /// endpoint, so the lookup the supervisor reads
19554        /// (`Registry::published_registration`) must not return the candidate
19555        /// until that endpoint exists. Otherwise the cutover finds no candidate
19556        /// endpoint and the swap fails as if the candidate had disconnected.
19557        #[tokio::test]
19558        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19559            let mut swap = swap_with_incumbent().await;
19560            let hold = Arc::new(std::sync::Barrier::new(2));
19561            let handler = swap
19562                .handler
19563                .clone()
19564                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19565            handler
19566                .supervisor
19567                .open_swap("aft", "candidate-nonce".to_string());
19568            let hello = {
19569                let handler = handler.clone();
19570                let candidate_ctx = swap.candidate_ctx.clone();
19571                std::thread::spawn(move || {
19572                    handler
19573                        .handle_hello(
19574                            candidate_ctx.connection_id,
19575                            Some(candidate_ctx.egress.clone()),
19576                            hello_frame_with_nonce(
19577                                "aft",
19578                                PROTOCOL_VERSION,
19579                                8,
19580                                Some("candidate-nonce"),
19581                            ),
19582                        )
19583                        .unwrap()
19584                })
19585            };
19586
19587            hold.wait();
19588            // Parked: the candidate slot is claimed but not published, and
19589            // forwarding has no candidate endpoint.
19590            assert!(swap
19591                .registry
19592                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19593                .unwrap()
19594                .is_some());
19595            assert!(swap
19596                .registry
19597                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19598                .unwrap()
19599                .is_none());
19600            assert!(swap
19601                .forwarding
19602                .module_endpoint_for_connection(CANDIDATE)
19603                .unwrap()
19604                .is_none());
19605
19606            hold.wait();
19607            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19608            assert_eq!(
19609                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19610                FrameType::HelloAck
19611            );
19612            let published = swap
19613                .registry
19614                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19615                .unwrap()
19616                .expect("candidate is published once its HELLO completes");
19617            assert_eq!(published.connection_id, CANDIDATE);
19618            assert!(swap
19619                .forwarding
19620                .module_endpoint_for_connection(CANDIDATE)
19621                .unwrap()
19622                .is_some());
19623        }
19624
19625        #[tokio::test]
19626        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19627            let mut swap = swap_with_incumbent().await;
19628            let hold = Arc::new(std::sync::Barrier::new(2));
19629            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19630            swap.handler
19631                .supervisor
19632                .open_swap("aft", "candidate-nonce".to_string());
19633            let hello = {
19634                let handler = swap.handler.clone();
19635                let candidate_ctx = swap.candidate_ctx.clone();
19636                std::thread::spawn(move || {
19637                    handler
19638                        .handle_hello(
19639                            CANDIDATE,
19640                            Some(candidate_ctx.egress),
19641                            hello_frame_with_nonce(
19642                                "aft",
19643                                PROTOCOL_VERSION,
19644                                8,
19645                                Some("candidate-nonce"),
19646                            ),
19647                        )
19648                        .unwrap()
19649                })
19650            };
19651            hold.wait();
19652            assert_eq!(
19653                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19654                FrameType::HelloAck
19655            );
19656            let reader_registry = Arc::clone(&swap.registry);
19657            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19658                reader_registry
19659                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19660                    .unwrap()
19661            });
19662            assert!(hello.join().unwrap().is_empty());
19663            assert_eq!(
19664                published
19665                    .expect("ACK makes candidate publication visible")
19666                    .connection_id,
19667                CANDIDATE
19668            );
19669            assert_eq!(
19670                swap.registry.generation().unwrap(),
19671                1,
19672                "candidate is not a second catalog entry"
19673            );
19674        }
19675
19676        #[tokio::test]
19677        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19678            let mut swap = swap_with_incumbent().await;
19679            let hold = Arc::new(std::sync::Barrier::new(2));
19680            let handler = swap
19681                .handler
19682                .clone()
19683                .with_hello_registry_to_forwarding_hold(hold.clone());
19684            handler
19685                .supervisor
19686                .open_swap("aft", "candidate-nonce".into());
19687            let hello = {
19688                let handler = handler.clone();
19689                let ctx = swap.candidate_ctx.clone();
19690                std::thread::spawn(move || {
19691                    handler
19692                        .handle_hello(
19693                            CANDIDATE,
19694                            Some(ctx.egress),
19695                            hello_frame_with_nonce(
19696                                "aft",
19697                                PROTOCOL_VERSION,
19698                                8,
19699                                Some("candidate-nonce"),
19700                            ),
19701                        )
19702                        .unwrap()
19703                })
19704            };
19705            hold.wait();
19706            assert_eq!(
19707                swap.registry
19708                    .deregister_connection(CANDIDATE)
19709                    .unwrap()
19710                    .len(),
19711                1
19712            );
19713            hold.wait();
19714            assert!(hello.join().unwrap().is_empty());
19715            assert_eq!(
19716                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19717                FrameType::HelloAck
19718            );
19719            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19720            assert_eq!(
19721                handler
19722                    .supervisor
19723                    .swap_hello_admission("aft", Some("candidate-nonce")),
19724                SwapHelloAdmission::Candidate,
19725                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19726            );
19727            handler.supervisor.close_swap("aft");
19728        }
19729
19730        fn keyed_total(counters: &Value, key: &str) -> u64 {
19731            counters[key]
19732                .as_object()
19733                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19734                .unwrap_or(0)
19735        }
19736
19737        #[tokio::test]
19738        async fn replacement_logs_old_end_and_new_admission_once() {
19739            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19740            let mut swap = swap_with_incumbent().await;
19741            swap.handler
19742                .supervisor
19743                .open_swap("aft", "candidate-nonce".to_string());
19744            hello_via_sink(
19745                &swap.handler,
19746                &swap.candidate_ctx,
19747                &mut swap.candidate_rx,
19748                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19749            )
19750            .await;
19751            cutover(&swap);
19752            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19753
19754            let captured = crate::router::test_log::captured_logs(&logs);
19755            println!("captured replacement registry logs:\n{captured}");
19756            let new_admissions: Vec<_> = captured
19757                .lines()
19758                .filter(|line| {
19759                    line.contains("connection_id=40")
19760                        && line.contains("swap candidate registered; not routable until cutover")
19761                })
19762                .collect();
19763            assert_eq!(
19764                new_admissions.len(),
19765                1,
19766                "unexpected admission logs: {captured}"
19767            );
19768            assert!(new_admissions[0].contains("module_id=aft"));
19769            assert!(new_admissions[0].contains("connection_id=40"));
19770            assert!(
19771                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19772            );
19773            assert!(new_admissions[0].contains("ready=true"));
19774
19775            let old_admissions: Vec<_> = captured
19776                .lines()
19777                .filter(|line| {
19778                    line.contains("module registered module_id=aft ")
19779                        && line.contains("connection_id=30")
19780                })
19781                .collect();
19782            assert_eq!(
19783                old_admissions.len(),
19784                1,
19785                "unexpected incumbent admission: {captured}"
19786            );
19787
19788            let old_ends: Vec<_> = captured
19789                .lines()
19790                .filter(|line| {
19791                    line.contains("connection_id=30") && line.contains("module registration ended")
19792                })
19793                .collect();
19794            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19795            assert!(old_ends[0].contains("module_id=aft"));
19796            assert!(old_ends[0].contains("connection_id=30"));
19797            assert!(old_ends[0].contains("reason=replaced"));
19798            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19799            assert_eq!(
19800                captured
19801                    .lines()
19802                    .filter(|line| line.contains("module registration promoted"))
19803                    .count(),
19804                1,
19805                "unexpected promotion logs: {captured}"
19806            );
19807        }
19808
19809        /// An ack from the incumbent for a bind it was sent before cutover,
19810        /// arriving before the incumbent is drained. The incumbent is the live
19811        /// connection carrying every other client's routes, so the ack must
19812        /// not end it: the waiting client is told to retry, the reservation is
19813        /// given back, and the incumbent is told to drop just that binding.
19814        #[tokio::test]
19815        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19816            let mut swap = swap_with_incumbent().await;
19817            let handler = swap.handler.clone();
19818
19819            // A co-tenant route, bound on the incumbent before the swap.
19820            let cotenant = ConnectionId::new(31);
19821            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19822            let (cotenant_task, cotenant_bind) = relay_route_open(
19823                &handler,
19824                cotenant,
19825                &cotenant_ctx.egress,
19826                &mut swap.incumbent_rx,
19827                100,
19828                "aft",
19829                "swap-cotenant",
19830            )
19831            .await;
19832            handler
19833                .handle_control_frame(
19834                    &swap.incumbent_ctx,
19835                    route_bind_ack(cotenant_bind.header.corr),
19836                )
19837                .await
19838                .unwrap();
19839            assert!(cotenant_task.await.unwrap().is_empty());
19840            let (cotenant_channel, cotenant_epoch) =
19841                published_route(&cotenant_rx.recv().await.unwrap());
19842
19843            // A second route.open, relayed to the incumbent and not yet acked.
19844            let caller = ConnectionId::new(32);
19845            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19846            let (caller_task, caller_bind) = relay_route_open(
19847                &handler,
19848                caller,
19849                &caller_ctx.egress,
19850                &mut swap.incumbent_rx,
19851                101,
19852                "aft",
19853                "swap-caller",
19854            )
19855            .await;
19856            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19857
19858            register_candidate(&swap, None);
19859            cutover(&swap);
19860
19861            // The incumbent acks after promotion and before any drain.
19862            let ack = handler
19863                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19864                .await;
19865            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19866            if module_loop_error.is_some() {
19867                // What the connection loop does with an untranslated router
19868                // error: end the connection, releasing every route on it.
19869                handler.cleanup_connection(INCUMBENT).unwrap();
19870            }
19871
19872            // 1. The incumbent's other routes survive.
19873            assert!(
19874                cotenant_rx.try_recv().is_err(),
19875                "the co-tenant route on the incumbent was torn down by one late ack: \
19876                 {module_loop_error:?}"
19877            );
19878            assert!(matches!(
19879                swap.forwarding
19880                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19881                    .unwrap(),
19882                DataRoute::Client(DataRouteState::Bound(_))
19883            ));
19884            assert_eq!(module_loop_error, None);
19885            assert!(swap
19886                .registry
19887                .get_module_by_connection(INCUMBENT)
19888                .unwrap()
19889                .is_some());
19890
19891            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19892            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19893                .await
19894                .expect("the incumbent is told to drop the abandoned binding")
19895                .unwrap()
19896                .frame;
19897            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19898            assert_eq!(goodbye.header.channel, abandoned_channel);
19899            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19900            assert!(swap.incumbent_rx.try_recv().is_err());
19901
19902            // 3. The waiting client gets a retryable refusal and no route.
19903            let response = caller_task.await.unwrap();
19904            assert_eq!(response.len(), 1);
19905            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19906            assert!(caller_rx.try_recv().is_err());
19907
19908            // 4. The reservation pair is given back, and the pending bind
19909            //    settled exactly once: one accepted open (the co-tenant) and one
19910            //    refused open (the caller), nothing counted twice.
19911            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19912            let counters = handler.counters().snapshot();
19913            assert_eq!(
19914                keyed_total(&counters, "route_open_accepted_by_principal"),
19915                1
19916            );
19917            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19918            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19919        }
19920
19921        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19922        /// id would resolve to the promoted candidate and every new route.open
19923        /// would be refused as reloading, leaving neither process routable.
19924        #[tokio::test]
19925        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19926            let mut swap = swap_with_incumbent().await;
19927            register_candidate(&swap, None);
19928            let incumbent = cutover(&swap);
19929            swap.forwarding
19930                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19931                .unwrap()
19932                .expect("the incumbent is still registered");
19933
19934            let client = ConnectionId::new(33);
19935            let (client_ctx, mut client_rx) = route_ctx(client);
19936            let route_handler = swap.handler.clone();
19937            let open_ctx = RouteCtx {
19938                connection_id: client,
19939                egress: client_ctx.egress.clone(),
19940            };
19941            let mut route_task = tokio::spawn(async move {
19942                route_handler
19943                    .handle_control_frame(
19944                        &open_ctx,
19945                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19946                    )
19947                    .await
19948                    .unwrap()
19949            });
19950            let bind = tokio::select! {
19951                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19952                response = &mut route_task => {
19953                    let response = response.unwrap();
19954                    panic!(
19955                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19956                        parse_error(&response[0])["code"]
19957                    );
19958                }
19959            };
19960            swap.handler
19961                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19962                .await
19963                .unwrap();
19964            assert!(route_task.await.unwrap().is_empty());
19965            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19966            match swap
19967                .forwarding
19968                .lookup_data_route(client, channel, epoch)
19969                .unwrap()
19970            {
19971                DataRoute::Client(DataRouteState::Bound(route)) => {
19972                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19973                }
19974                other => panic!("expected a bound route on the candidate, got {other:?}"),
19975            }
19976            assert!(swap.incumbent_rx.try_recv().is_err());
19977        }
19978
19979        /// A candidate declares itself ready with `catalog.update` on its own
19980        /// connection. If the connection-keyed registry lookups searched only the
19981        /// active slot, this would answer `not_registered` and the candidate
19982        /// would never become ready.
19983        #[tokio::test]
19984        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
19985            let swap = swap_with_incumbent().await;
19986            register_candidate(&swap, Some(false));
19987            let update = Frame::build(
19988                FrameType::Request,
19989                control_flags(),
19990                0,
19991                0,
19992                55,
19993                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
19994                    provides: manifest("aft", PROTOCOL_VERSION).provides,
19995                    capabilities: None,
19996                    ready: Some(true),
19997                })
19998                .unwrap(),
19999            )
20000            .unwrap();
20001
20002            let replies = swap
20003                .handler
20004                .handle_control_frame(&swap.candidate_ctx, update)
20005                .await
20006                .unwrap();
20007
20008            assert_eq!(replies.len(), 1);
20009            assert_eq!(
20010                replies[0].header.ty,
20011                FrameType::Response,
20012                "candidate catalog.update was refused: {:?}",
20013                serde_json::from_slice::<Value>(&replies[0].body).ok()
20014            );
20015            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
20016            assert_eq!(
20017                swap.registry
20018                    .get_module("aft")
20019                    .unwrap()
20020                    .unwrap()
20021                    .connection_id,
20022                INCUMBENT
20023            );
20024        }
20025    }
20026
20027    /// The HELLO gate while the supervisor has a swap open: only the nonce it
20028    /// minted for the candidate admits a second process, into the candidate
20029    /// slot, and that check runs ahead of the reserved-module gate.
20030    mod swap_admission {
20031        use super::*;
20032
20033        const INCUMBENT_NONCE: &str = "incumbent-nonce";
20034        const CANDIDATE_NONCE: &str = "candidate-nonce";
20035
20036        fn handler_with_incumbent(
20037            module_id: &str,
20038            reserved: bool,
20039        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
20040            let registry = Arc::new(Registry::default());
20041            let supervisor = SupervisorHandle::new();
20042            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
20043            if reserved {
20044                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
20045            }
20046            let handler =
20047                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
20048            let incumbent = handler
20049                .handle_control(
20050                    ConnectionId::new(1),
20051                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
20052                )
20053                .unwrap();
20054            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
20055            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
20056            (registry, supervisor, handler)
20057        }
20058
20059        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
20060        /// admits every nonce, so while a swap is open the swap gate is the only
20061        /// thing between a key-holder and the candidate slot. A nonce the
20062        /// supervisor did not mint, or none at all, is refused, and neither the
20063        /// incumbent's registration nor the candidate slot moves.
20064        #[test]
20065        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
20066            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
20067
20068            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
20069                let replies = handler
20070                    .handle_control(
20071                        ConnectionId::new(connection),
20072                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
20073                    )
20074                    .unwrap();
20075                assert_eq!(replies[0].header.ty, FrameType::Error);
20076                assert_eq!(
20077                    parse_error(&replies[0])["code"],
20078                    "swap_token_invalid",
20079                    "nonce {nonce:?}"
20080                );
20081            }
20082            assert!(registry.get_candidate("aft").unwrap().is_none());
20083            assert_eq!(
20084                registry.get_module("aft").unwrap().unwrap().connection_id,
20085                ConnectionId::new(1)
20086            );
20087
20088            // Control: the minted token is admitted, into the candidate slot,
20089            // and only once.
20090            let admitted = handler
20091                .handle_control(
20092                    ConnectionId::new(4),
20093                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20094                )
20095                .unwrap();
20096            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20097            assert_eq!(
20098                registry
20099                    .get_candidate("aft")
20100                    .unwrap()
20101                    .unwrap()
20102                    .connection_id,
20103                ConnectionId::new(4)
20104            );
20105            assert_eq!(
20106                registry.get_module("aft").unwrap().unwrap().connection_id,
20107                ConnectionId::new(1),
20108                "the candidate must not take the active slot"
20109            );
20110            let replayed = handler
20111                .handle_control(
20112                    ConnectionId::new(5),
20113                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20114                )
20115                .unwrap();
20116            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20117
20118            // The case only this gate covers: the incumbent has died mid-swap,
20119            // so its duplicate refusal is gone too, and without the gate a
20120            // key-holder would take the id's ACTIVE slot.
20121            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20122            let squatter = handler
20123                .handle_control(
20124                    ConnectionId::new(6),
20125                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20126                )
20127                .unwrap();
20128            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20129            assert!(
20130                registry.get_module("aft").unwrap().is_none(),
20131                "a squatter took the active slot of an id being swapped"
20132            );
20133        }
20134
20135        /// Design mutation arm (iii). A reserved module's candidate presents a
20136        /// nonce the reserved gate has never seen (that gate holds the
20137        /// incumbent's), so the swap gate must run first or the candidate is
20138        /// refused `reserved_module` and a reserved module can never be swapped.
20139        #[test]
20140        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20141            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20142
20143            let replies = handler
20144                .handle_control(
20145                    ConnectionId::new(2),
20146                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20147                )
20148                .unwrap();
20149
20150            assert_eq!(
20151                replies[0].header.ty,
20152                FrameType::HelloAck,
20153                "reserved candidate refused: {:?}",
20154                serde_json::from_slice::<Value>(&replies[0].body).ok()
20155            );
20156            assert_eq!(
20157                registry
20158                    .get_candidate("vault")
20159                    .unwrap()
20160                    .unwrap()
20161                    .connection_id,
20162                ConnectionId::new(2)
20163            );
20164        }
20165
20166        /// With no swap open the gate is inert: the incumbent's reserved gate
20167        /// and duplicate refusal behave exactly as before.
20168        #[test]
20169        fn without_an_open_swap_the_ordinary_gates_decide() {
20170            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20171            supervisor.close_swap("vault");
20172
20173            let candidate = handler
20174                .handle_control(
20175                    ConnectionId::new(2),
20176                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20177                )
20178                .unwrap();
20179            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20180            let duplicate = handler
20181                .handle_control(
20182                    ConnectionId::new(3),
20183                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20184                )
20185                .unwrap();
20186            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20187            assert!(registry.get_candidate("vault").unwrap().is_none());
20188        }
20189    }
20190
20191    /// `scope.sync` and `scope.describe` through the real control handler: who
20192    /// may sync is decided by the registration and launch nonce of the module
20193    /// connection, never by the request body.
20194    mod scopes {
20195        mod close_reasons {
20196            include!("route_close_reason_tests.rs");
20197        }
20198        mod idle_tests {
20199            use super::*;
20200            include!("scope_idle_tests.rs");
20201        }
20202        mod route_open_timings {
20203            use super::*;
20204            include!("route_open_timing_tests.rs");
20205        }
20206        mod route_open_refusal_log {
20207            use super::*;
20208            include!("route_open_refusal_log_tests.rs");
20209        }
20210        mod activity {
20211            include!("activity_scope_tests.rs");
20212        }
20213        mod delta {
20214            include!("scope_handler_delta_tests.rs");
20215        }
20216        mod watch {
20217            include!("scope_watch_tests.rs");
20218        }
20219        mod call_modes {
20220            include!("scope_call_mode_tests.rs");
20221        }
20222        mod federated {
20223            include!("scope_federated_tests.rs");
20224        }
20225        mod authorize {
20226            include!("route_authorize_tests.rs");
20227        }
20228        #[tokio::test]
20229        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20230            let rig = rig().await;
20231            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20232                "s".into(),
20233                1,
20234                "tool".into(),
20235            ))
20236            .unwrap();
20237            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20238            let (direct, _rx) = wide_ctx(999);
20239            for (ctx, expected) in [
20240                (&rig.owner, FrameType::Response),
20241                (&direct, FrameType::Error),
20242            ] {
20243                let frame =
20244                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20245                        .unwrap();
20246                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20247                assert_eq!(replies[0].header.ty, expected);
20248                if expected == FrameType::Response {
20249                    let reply: subc_control::ScopeServedByReply =
20250                        serde_json::from_slice(&replies[0].body).unwrap();
20251                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20252                } else {
20253                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20254                }
20255            }
20256            let reply = call(
20257                &rig.handler,
20258                &rig.owner,
20259                &ModuleControlRequestFromModule::ScopeDescribe {
20260                    owner: Principal::Reserved {
20261                        module_id: OWNER.into(),
20262                    },
20263                    scope_ref: "s".into(),
20264                },
20265            )
20266            .await;
20267            assert!(matches!(
20268                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20269                ModuleControlResponseToModule::ScopeDescribe { .. }
20270            ));
20271        }
20272
20273        use subc_protocol::scope::{
20274            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20275            ScopeStatus,
20276        };
20277
20278        use super::*;
20279
20280        const OWNER: &str = "prefrontal-core";
20281
20282        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20283            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20284        }
20285
20286        async fn call(
20287            handler: &ControlHandler,
20288            ctx: &RouteCtx,
20289            request: &ModuleControlRequestFromModule,
20290        ) -> Frame {
20291            let body = serde_json::to_vec(request).unwrap();
20292            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20293            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20294            assert_eq!(replies.len(), 1, "{replies:?}");
20295            replies.pop().unwrap()
20296        }
20297
20298        async fn sync(
20299            handler: &ControlHandler,
20300            ctx: &RouteCtx,
20301            generation: u64,
20302            scopes: Vec<ScopeRecord>,
20303        ) -> Result<ModuleControlResponseToModule, String> {
20304            let reply = call(
20305                handler,
20306                ctx,
20307                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20308            )
20309            .await;
20310            match reply.header.ty {
20311                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20312                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20313            }
20314        }
20315
20316        async fn describe(
20317            handler: &ControlHandler,
20318            ctx: &RouteCtx,
20319            owner: &str,
20320            scope_ref: &str,
20321        ) -> ModuleControlResponseToModule {
20322            let reply = call(
20323                handler,
20324                ctx,
20325                &ModuleControlRequestFromModule::ScopeDescribe {
20326                    owner: Principal::Reserved {
20327                        module_id: owner.to_string(),
20328                    },
20329                    scope_ref: scope_ref.to_string(),
20330                },
20331            )
20332            .await;
20333            assert_eq!(
20334                reply.header.ty,
20335                FrameType::Response,
20336                "{:?}",
20337                parse_error(&reply)
20338            );
20339            serde_json::from_slice(&reply.body).unwrap()
20340        }
20341
20342        #[tokio::test]
20343        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20344            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20345            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20346            let mut rig = rig().await;
20347            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20348                .await;
20349            let _bound = rig
20350                .bound(
20351                    Some(AFT),
20352                    PLEXUS,
20353                    Some(
20354                        rig.selector("s", Some(1))
20355                            .with_bind_proof(Some(PROOF.into())),
20356                    ),
20357                )
20358                .await;
20359            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20360            let output = serde_json::to_string(&reply).unwrap();
20361            assert!(output.contains("\"status\":\"live\""));
20362            assert!(!output.contains(PROOF));
20363            assert!(!output.contains(HASH));
20364        }
20365
20366        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20367        async fn module(
20368            handler: &ControlHandler,
20369            connection: u64,
20370            module_id: &str,
20371            nonce: Option<&str>,
20372        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20373            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20374            hello_via_sink(
20375                handler,
20376                &ctx,
20377                &mut rx,
20378                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20379            )
20380            .await;
20381            (ctx, rx)
20382        }
20383
20384        /// `direct` and every other client connection has no registration, so
20385        /// it can neither sync nor own a scope.
20386        #[tokio::test]
20387        async fn a_client_connection_cannot_sync_or_describe() {
20388            let handler = ControlHandler::new(Arc::new(Registry::default()));
20389            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20390            for request in [
20391                ModuleControlRequestFromModule::ScopeSync {
20392                    generation: 1,
20393                    scopes: vec![head("s", 1)],
20394                },
20395                ModuleControlRequestFromModule::ScopeDescribe {
20396                    owner: Principal::Direct,
20397                    scope_ref: "s".to_string(),
20398                },
20399            ] {
20400                let reply = call(&handler, &ctx, &request).await;
20401                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20402            }
20403            assert!(
20404                !handler
20405                    .scopes
20406                    .read()
20407                    .unwrap()
20408                    .describe(
20409                        &Principal::Reserved {
20410                            module_id: OWNER.to_string()
20411                        },
20412                        "s"
20413                    )
20414                    .owner_synced
20415            );
20416        }
20417
20418        /// A module the supervisor did not spawn registers without a launch
20419        /// nonce, so it is never an owner's current launch.
20420        #[tokio::test]
20421        async fn a_module_without_a_supervised_launch_cannot_sync() {
20422            let handler = ControlHandler::new(Arc::new(Registry::default()));
20423            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20424            assert_eq!(
20425                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20426                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20427            );
20428        }
20429
20430        #[tokio::test]
20431        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20432            let supervisor = SupervisorHandle::new();
20433            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20434            let handler = ControlHandler::new(Arc::new(Registry::default()))
20435                .with_supervisor(supervisor.clone());
20436            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20437            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20438                .await
20439                .expect("the current launch syncs");
20440
20441            // A swap candidate registers with the swap token and is refused
20442            // while the incumbent keeps syncing.
20443            supervisor.open_swap(OWNER, "n2".to_string());
20444            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20445            assert_eq!(
20446                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20447                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20448            );
20449            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20450                .await
20451                .expect("the serving owner syncs during the swap");
20452
20453            // The swap fails and is rolled back. The candidate never held sync
20454            // authority, and still cannot sync.
20455            supervisor.close_swap(OWNER);
20456            assert_eq!(
20457                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20458                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20459            );
20460            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20461                .await
20462                .expect("the serving owner syncs after the rollback");
20463            handler.cleanup_connection(candidate.connection_id).unwrap();
20464
20465            // A swap that cuts over. Promotion records the candidate's nonce as
20466            // the module's spawn nonce, which is what `set_spawn_nonce` does
20467            // here; the promoted connection then takes authority at any
20468            // generation and the superseded incumbent is refused.
20469            supervisor.open_swap(OWNER, "n3".to_string());
20470            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20471            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20472            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20473                .await
20474                .expect("the promoted launch takes authority");
20475            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20476                panic!("unexpected reply {reply:?}");
20477            };
20478            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20479            assert_eq!(
20480                sync(&handler, &incumbent, 4, Vec::new()).await,
20481                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20482            );
20483        }
20484
20485        /// Authority dies with its connection: the cleanup path releases it,
20486        /// so the owner's next connection takes it at any generation.
20487        #[tokio::test]
20488        async fn closing_the_authority_connection_frees_sync_authority() {
20489            let supervisor = SupervisorHandle::new();
20490            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20491            let handler = ControlHandler::new(Arc::new(Registry::default()))
20492                .with_supervisor(supervisor.clone());
20493            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20494            sync(&handler, &first, 10, vec![head("s", 1)])
20495                .await
20496                .unwrap();
20497            handler.cleanup_connection(first.connection_id).unwrap();
20498
20499            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20500            sync(&handler, &second, 1, vec![head("s", 1)])
20501                .await
20502                .expect("the next connection takes the released authority");
20503        }
20504
20505        #[tokio::test]
20506        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20507            let supervisor = SupervisorHandle::new();
20508            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20509            let handler =
20510                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20511            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20512            sync(&handler, &first, 10, vec![head("s", 1)])
20513                .await
20514                .unwrap();
20515            handler
20516                .handle_control_frame(
20517                    &first,
20518                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20519                )
20520                .await
20521                .unwrap();
20522            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20523            sync(&handler, &second, 1, vec![head("s", 1)])
20524                .await
20525                .expect("GOODBYE releases authority even if the old socket remains open");
20526        }
20527
20528        #[tokio::test]
20529        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20530            let registry = Arc::new(Registry::default());
20531            let supervisor_handle = SupervisorHandle::new();
20532            let supervisor =
20533                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20534                    .with_handle(supervisor_handle.clone())
20535                    .with_daemon_incarnation("incarnation-7".to_string());
20536            // Configured with enabled: false, so the supervisor lists the
20537            // module without spawning a process for it.
20538            supervisor
20539                .supervise_configured(
20540                    ModuleSpec {
20541                        script: None,
20542                        carry_containment: false,
20543                        module_id: OWNER.to_string(),
20544                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20545                        args: Vec::new(),
20546                        env: Vec::new(),
20547                        reserved: false,
20548                        reserved_prefixes: Vec::new(),
20549                        protocol: ModuleProtocol::Subc,
20550                        overlap: Default::default(),
20551                    },
20552                    false,
20553                )
20554                .unwrap();
20555            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20556            let handler =
20557                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20558            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20559
20560            // Configured but not yet synced: a reader waits for the owner.
20561            let ModuleControlResponseToModule::ScopeDescribe {
20562                status,
20563                daemon_incarnation,
20564                owner_synced,
20565                owner_configured,
20566                scope,
20567                ..
20568            } = describe(&handler, &reader, OWNER, "s").await
20569            else {
20570                panic!("not a describe reply");
20571            };
20572            assert_eq!(status, ScopeStatus::NotLive);
20573            assert_eq!(daemon_incarnation, "incarnation-7");
20574            assert!(!owner_synced);
20575            assert!(owner_configured);
20576            assert!(scope.is_none());
20577
20578            // Not a supervised module: the owner will never sync, and a reader
20579            // refuses rather than waits.
20580            let ModuleControlResponseToModule::ScopeDescribe {
20581                status,
20582                owner_configured,
20583                ..
20584            } = describe(&handler, &reader, "ghost", "s").await
20585            else {
20586                panic!("not a describe reply");
20587            };
20588            assert_eq!(status, ScopeStatus::NotLive);
20589            assert!(!owner_configured);
20590
20591            // Live, with the stamp fields and the computed owner_authorized.
20592            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20593            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20594            let ModuleControlResponseToModule::ScopeDescribe {
20595                status,
20596                scope_epoch,
20597                owner_synced,
20598                scope,
20599                ..
20600            } = describe(&handler, &reader, OWNER, "s").await
20601            else {
20602                panic!("not a describe reply");
20603            };
20604            assert_eq!(status, ScopeStatus::Live);
20605            assert_eq!(scope_epoch, Some(4));
20606            assert!(owner_synced);
20607            let stamp = scope.expect("a live scope carries its stamp");
20608            assert!(
20609                stamp.owner_authorized,
20610                "prefrontal-core is the default authority"
20611            );
20612            assert_eq!(stamp.kind, ScopeKind::Head);
20613        }
20614
20615        #[tokio::test]
20616        async fn scope_authority_owners_decides_owner_authorized() {
20617            let supervisor = SupervisorHandle::new();
20618            supervisor.set_spawn_nonce("broca", "b1".to_string());
20619            let handler = ControlHandler::new(Arc::new(Registry::default()))
20620                .with_supervisor(supervisor)
20621                .with_scope_authority_owners(vec!["broca".to_string()]);
20622            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20623            let mut gated = head("s", 1);
20624            gated.attributes.agent_id = Some("agent".to_string());
20625            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20626            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20627                describe(&handler, &broca, "broca", "s").await
20628            else {
20629                panic!("not a describe reply");
20630            };
20631            assert!(scope.unwrap().owner_authorized);
20632        }
20633
20634        /// With route admission, the stamp, the commit re-check and drains in
20635        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20636        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20637        #[tokio::test]
20638        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20639            let handler = ControlHandler::new(Arc::new(Registry::default()));
20640            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20641            let ack = hello_via_sink(
20642                &handler,
20643                &ctx,
20644                &mut rx,
20645                hello_frame("m", PROTOCOL_VERSION, 1),
20646            )
20647            .await;
20648            let ack = parse_ack(&ack);
20649            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20650                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20651            }
20652            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20653
20654            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20655            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20656            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20657            let reply = handler
20658                .handle_control_frame(&client, frame)
20659                .await
20660                .unwrap()
20661                .pop()
20662                .unwrap();
20663            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20664                serde_json::from_slice(&reply.body).unwrap()
20665            else {
20666                panic!("not a server.describe reply");
20667            };
20668            assert!(
20669                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20670                "{capabilities:?}"
20671            );
20672        }
20673
20674        // ---- route admission, stamps, commit re-check and drains ----------
20675
20676        const PLEXUS: &str = "plexus";
20677        const OTHER: &str = "other";
20678        const AFT: &str = "aft";
20679        const BROCA: &str = "broca";
20680        const MAGIC: &str = "magic-context";
20681
20682        fn nonce(module_id: &str) -> String {
20683            format!("nonce-{module_id}")
20684        }
20685
20686        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20687            let (tx, rx) = mpsc::channel(64);
20688            (
20689                RouteCtx {
20690                    connection_id: ConnectionId::new(connection),
20691                    egress: FrameSink::new(tx),
20692                },
20693                rx,
20694            )
20695        }
20696
20697        /// A daemon with a configured owner (prefrontal-core) registered on its
20698        /// own module connection, two routable targets (plexus, other), and
20699        /// launch nonces minted for the modules that open routes as carriers.
20700        struct Rig {
20701            handler: ControlHandler,
20702            forwarding: Arc<ForwardingTable>,
20703            owner: RouteCtx,
20704            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20705            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20706            generation: u64,
20707            next_connection: u64,
20708            _supervisor: Supervisor,
20709        }
20710
20711        async fn rig() -> Rig {
20712            rig_with_flow_support(true).await
20713        }
20714
20715        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20716            rig_with_scope_capabilities(flow_support, false).await
20717        }
20718
20719        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20720            let mut provides = Vec::new();
20721            if flow_support {
20722                provides.push("flow-scopes/v1");
20723            }
20724            if run_support {
20725                provides.push("agent-run-scopes/v1");
20726            }
20727            rig_with_target_capabilities(&provides).await
20728        }
20729
20730        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20731            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20732            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20733            // Decoder versions alone cannot admit scoped calls: only a capability
20734            // declaration promises the required run or flow behaviour.
20735            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20736            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20737            Frame::build(
20738                FrameType::Hello,
20739                control_flags(),
20740                0,
20741                0,
20742                connection,
20743                serde_json::to_vec(&body).unwrap(),
20744            )
20745            .unwrap()
20746        }
20747
20748        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20749            let registry = Arc::new(Registry::default());
20750            let forwarding = Arc::new(ForwardingTable::default());
20751            let supervisor_handle = SupervisorHandle::new();
20752            let supervisor =
20753                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20754                    .with_handle(supervisor_handle.clone());
20755            supervisor
20756                .supervise_configured(
20757                    ModuleSpec {
20758                        script: None,
20759                        carry_containment: false,
20760                        module_id: OWNER.to_string(),
20761                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20762                        args: Vec::new(),
20763                        env: Vec::new(),
20764                        reserved: false,
20765                        reserved_prefixes: Vec::new(),
20766                        protocol: ModuleProtocol::Subc,
20767                        overlap: Default::default(),
20768                    },
20769                    false,
20770                )
20771                .unwrap();
20772            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20773                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20774            }
20775            let handler =
20776                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20777                    .with_supervisor(supervisor_handle);
20778            let (owner, mut owner_rx) = wide_ctx(1);
20779            hello_via_sink(
20780                &handler,
20781                &owner,
20782                &mut owner_rx,
20783                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20784            )
20785            .await;
20786            let mut modules = BTreeMap::new();
20787            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20788                let (ctx, mut rx) = wide_ctx(connection);
20789                let hello = hello_with_capabilities(module_id, connection, provides);
20790                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20791                modules.insert(module_id.to_string(), (ctx, rx));
20792            }
20793            Rig {
20794                handler,
20795                forwarding,
20796                owner,
20797                _owner_rx: owner_rx,
20798                modules,
20799                generation: 0,
20800                next_connection: 100,
20801                _supervisor: supervisor,
20802            }
20803        }
20804
20805        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20806            ScopeCarrier::new(Principal::Reserved {
20807                module_id: module_id.to_string(),
20808            })
20809            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20810        }
20811
20812        /// The scope most tests open under: aft carries to any module, broca
20813        /// only to plexus and other, and the owner delegates as agent-1.
20814        fn session(scope_epoch: u64) -> ScopeRecord {
20815            let mut record = head("s", scope_epoch);
20816            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20817            record.attributes.agent_id = Some("agent-1".to_string());
20818            record.attributes.delegates = true;
20819            record
20820        }
20821
20822        impl Rig {
20823            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20824                self.generation += 1;
20825                sync(&self.handler, &self.owner, self.generation, scopes)
20826                    .await
20827                    .expect("the owner's sync is accepted");
20828            }
20829
20830            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20831                ScopeSelector::new(
20832                    Principal::Reserved {
20833                        module_id: OWNER.to_string(),
20834                    },
20835                    scope_ref.to_string(),
20836                    scope_epoch,
20837                )
20838            }
20839
20840            fn open_frame(
20841                &mut self,
20842                opener: Option<&str>,
20843                target: &str,
20844                scope: Option<ScopeSelector>,
20845            ) -> (
20846                RouteCtx,
20847                mpsc::Receiver<crate::router::OutboundFrame>,
20848                Frame,
20849            ) {
20850                self.next_connection += 1;
20851                let (ctx, rx) = wide_ctx(self.next_connection);
20852                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20853                    busy_refusals: None,
20854                    target: RouteTarget::ToolProvider {
20855                        module_id: target.to_string(),
20856                    },
20857                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20858                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20859                        module_id: module_id.to_string(),
20860                        launch_nonce: nonce(module_id),
20861                    }),
20862                    consumer_capabilities: None,
20863                    role_versions: None,
20864                    admission_facts: None,
20865                    scope,
20866                })
20867                .unwrap();
20868                let frame = Frame::build(
20869                    FrameType::Request,
20870                    control_flags(),
20871                    0,
20872                    0,
20873                    self.next_connection,
20874                    body,
20875                )
20876                .unwrap();
20877                (ctx, rx, frame)
20878            }
20879
20880            /// Open and expect a refusal before anything is relayed.
20881            async fn refused(
20882                &mut self,
20883                opener: Option<&str>,
20884                target: &str,
20885                scope: Option<ScopeSelector>,
20886            ) -> String {
20887                self.refusal_body(opener, target, scope).await["code"]
20888                    .as_str()
20889                    .unwrap()
20890                    .to_string()
20891            }
20892
20893            async fn refusal_body(
20894                &mut self,
20895                opener: Option<&str>,
20896                target: &str,
20897                scope: Option<ScopeSelector>,
20898            ) -> Value {
20899                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20900                let replies = tokio::time::timeout(
20901                    Duration::from_secs(2),
20902                    self.handler.handle_control_frame(&ctx, frame),
20903                )
20904                .await
20905                .expect("the open must be refused before waiting for a bind ack")
20906                .unwrap();
20907                assert_eq!(replies.len(), 1, "{replies:?}");
20908                assert_eq!(replies[0].header.ty, FrameType::Error);
20909                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20910                assert!(
20911                    module_rx.try_recv().is_err(),
20912                    "a refused open relays nothing"
20913                );
20914                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20915                parse_error(&replies[0])
20916            }
20917
20918            /// Start an open and return its task and the bind the target got.
20919            async fn relayed(
20920                &mut self,
20921                opener: Option<&str>,
20922                target: &str,
20923                scope: Option<ScopeSelector>,
20924            ) -> Relayed {
20925                self.relayed_with_legacy_root(opener, target, scope, None)
20926                    .await
20927            }
20928
20929            async fn relayed_with_legacy_root(
20930                &mut self,
20931                opener: Option<&str>,
20932                target: &str,
20933                scope: Option<ScopeSelector>,
20934                legacy_root: Option<&std::path::Path>,
20935            ) -> Relayed {
20936                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20937                if let Some(root) = legacy_root {
20938                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20939                    body["identity"]["project_root"] = serde_json::json!(root);
20940                    frame.body = serde_json::to_vec(&body).unwrap();
20941                }
20942                let handler = self.handler.clone();
20943                let task_ctx = ctx.clone();
20944                let task = tokio::spawn(async move {
20945                    handler
20946                        .handle_control_frame(&task_ctx, frame)
20947                        .await
20948                        .unwrap()
20949                });
20950                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20951                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20952                    .await
20953                    .expect("the target receives the relayed route.bind")
20954                    .unwrap()
20955                    .frame;
20956                Relayed {
20957                    target: target.to_string(),
20958                    client: ctx,
20959                    client_rx: rx,
20960                    task,
20961                    bind,
20962                }
20963            }
20964
20965            async fn ack(&self, relayed: &Relayed) {
20966                let (module, _) = &self.modules[&relayed.target];
20967                self.handler
20968                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20969                    .await
20970                    .unwrap();
20971            }
20972
20973            /// Open, ack and return the bound route.
20974            async fn bound(
20975                &mut self,
20976                opener: Option<&str>,
20977                target: &str,
20978                scope: Option<ScopeSelector>,
20979            ) -> Bound {
20980                let relayed = self.relayed(opener, target, scope).await;
20981                self.commit_relayed(relayed).await
20982            }
20983
20984            async fn bound_with_legacy_root(
20985                &mut self,
20986                opener: Option<&str>,
20987                target: &str,
20988                scope: Option<ScopeSelector>,
20989                root: &std::path::Path,
20990            ) -> Bound {
20991                let relayed = self
20992                    .relayed_with_legacy_root(opener, target, scope, Some(root))
20993                    .await;
20994                self.commit_relayed(relayed).await
20995            }
20996
20997            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
20998                self.ack(&relayed).await;
20999                let Relayed {
21000                    target,
21001                    client,
21002                    mut client_rx,
21003                    task,
21004                    bind,
21005                } = relayed;
21006                assert!(
21007                    task.await.unwrap().is_empty(),
21008                    "the open is answered by commit"
21009                );
21010                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
21011                Bound {
21012                    target,
21013                    client,
21014                    client_rx,
21015                    channel,
21016                    epoch,
21017                    bind,
21018                }
21019            }
21020
21021            fn live(&self, route: &Bound) -> bool {
21022                matches!(
21023                    self.forwarding
21024                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21025                        .unwrap(),
21026                    DataRoute::Client(DataRouteState::Bound(_))
21027                )
21028            }
21029        }
21030
21031        struct Relayed {
21032            target: String,
21033            client: RouteCtx,
21034            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21035            task: tokio::task::JoinHandle<Vec<Frame>>,
21036            bind: Frame,
21037        }
21038
21039        struct Bound {
21040            target: String,
21041            client: RouteCtx,
21042            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21043            channel: u16,
21044            epoch: u32,
21045            bind: Frame,
21046        }
21047
21048        impl Bound {
21049            /// The reason of the `route.closed` this client was sent, after
21050            /// checking it also got a GOODBYE on exactly this route.
21051            fn closed_reason(&mut self) -> RouteCloseReason {
21052                let mut reason = None;
21053                let mut goodbye = false;
21054                while let Ok(outbound) = self.client_rx.try_recv() {
21055                    let frame = outbound.frame;
21056                    match frame.header.ty {
21057                        FrameType::Goodbye => {
21058                            assert_eq!(
21059                                (frame.header.channel, frame.header.epoch),
21060                                (self.channel, self.epoch)
21061                            );
21062                            goodbye = true;
21063                        }
21064                        FrameType::Push => {
21065                            let ClientControlPush::RouteClosed {
21066                                reason: r,
21067                                module_id,
21068                                ..
21069                            } = serde_json::from_slice(&frame.body).unwrap()
21070                            else {
21071                                panic!("unexpected push");
21072                            };
21073                            assert_eq!(module_id, self.target);
21074                            reason = Some(r);
21075                        }
21076                        other => panic!("unexpected frame {other:?}"),
21077                    }
21078                }
21079                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21080                reason.expect("the client is told why the route closed")
21081            }
21082
21083            fn untouched(&mut self) -> bool {
21084                self.client_rx.try_recv().is_err()
21085            }
21086
21087            fn stamp(&self) -> Option<ScopeStamp> {
21088                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21089                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21090                    other => panic!("expected a route.bind, got {other:?}"),
21091                }
21092            }
21093        }
21094
21095        #[tokio::test]
21096        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21097        ) {
21098            let mut rig = rig().await;
21099            let mut record = session(1);
21100            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21101            record.child_owners = vec![Principal::Reserved {
21102                module_id: MAGIC.to_string(),
21103            }];
21104            rig.sync(vec![record]).await;
21105            let scope = || Some(rig_selector("s", Some(1)));
21106
21107            // Admitted: the owner, a bare carrier to any module, a targeted
21108            // carrier to its listed module.
21109            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21110            rig.bound(Some(AFT), OTHER, scope()).await;
21111            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21112
21113            // Refused scope_not_carrier: a targeted carrier to an unlisted
21114            // module, a module that is not listed at all (a child owner is not
21115            // a carrier), and a direct key-holder.
21116            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21117                assert_eq!(
21118                    rig.refused(opener, target, scope()).await,
21119                    error_codes::SCOPE_NOT_CARRIER,
21120                    "{opener:?} -> {target}"
21121                );
21122            }
21123        }
21124
21125        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21126            ScopeSelector::new(
21127                Principal::Reserved {
21128                    module_id: OWNER.to_string(),
21129                },
21130                scope_ref.to_string(),
21131                scope_epoch,
21132            )
21133        }
21134
21135        #[tokio::test]
21136        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21137            let mut rig = rig().await;
21138            rig.sync(vec![session(1)]).await;
21139            for opener in [OWNER, AFT] {
21140                assert_eq!(
21141                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21142                        .await,
21143                    error_codes::SCOPE_EPOCH_REQUIRED,
21144                    "{opener}"
21145                );
21146            }
21147        }
21148
21149        #[tokio::test]
21150        async fn admission_separates_not_synced_not_live_and_ended() {
21151            let mut rig = rig().await;
21152            // Before the configured owner's first sync: retryable.
21153            let code = rig
21154                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21155                .await;
21156            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21157            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21158
21159            // An owner that is not configured will never sync: terminal.
21160            let ghost = ScopeSelector::new(
21161                Principal::Reserved {
21162                    module_id: "ghost".to_string(),
21163                },
21164                "s".to_string(),
21165                Some(1),
21166            );
21167            assert_eq!(
21168                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21169                error_codes::SCOPE_NOT_LIVE
21170            );
21171
21172            rig.sync(vec![session(2)]).await;
21173            assert_eq!(
21174                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21175                    .await,
21176                error_codes::SCOPE_NOT_LIVE
21177            );
21178            for epoch in [1, 3] {
21179                assert_eq!(
21180                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21181                        .await,
21182                    error_codes::SCOPE_ENDED,
21183                    "epoch {epoch}"
21184                );
21185            }
21186            // Control: the live epoch is admitted.
21187            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21188                .await;
21189        }
21190
21191        #[tokio::test]
21192        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21193            let mut rig = rig().await;
21194            rig.sync(vec![session(1)]).await;
21195            let route = rig
21196                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21197                .await;
21198            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21199            assert_eq!(stamp.scope_ref, "s");
21200            assert_eq!(stamp.scope_epoch, 1);
21201            assert_eq!(stamp.kind, ScopeKind::Head);
21202            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21203            assert!(stamp.attributes.delegates);
21204            assert!(stamp.owner_authorized);
21205            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21206            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21207
21208            // broca owns a scope of its own on its own module connection; it is
21209            // not in scope_authority_owners, so its stamp is not authorized.
21210            let (broca, mut broca_rx) = wide_ctx(50);
21211            hello_via_sink(
21212                &rig.handler,
21213                &broca,
21214                &mut broca_rx,
21215                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21216            )
21217            .await;
21218            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21219                .await
21220                .unwrap();
21221            let own = ScopeSelector::new(
21222                Principal::Reserved {
21223                    module_id: BROCA.to_string(),
21224                },
21225                "b".to_string(),
21226                Some(1),
21227            );
21228            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21229            assert!(!route.stamp().unwrap().owner_authorized);
21230        }
21231
21232        #[tokio::test]
21233        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21234            let mut rig = rig().await;
21235            let mut record = head("s", 1);
21236            record.carriers = vec![carrier(AFT, None)];
21237            let flow_id = "Flow:run-7/step_2!~";
21238            record.attributes.flow_id = Some(flow_id.to_string());
21239            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21240                .await
21241                .unwrap();
21242            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21243                panic!("not a sync reply");
21244            };
21245            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21246            let route = rig
21247                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21248                .await;
21249            assert!(rig.live(&route), "the stamped bind committed");
21250            let stamp = route.stamp().expect("a flow scope carries a stamp");
21251            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21252            assert_eq!(stamp.attributes.agent_id, None);
21253            assert!(!stamp.attributes.delegates);
21254            assert!(stamp.owner_authorized);
21255            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21256            assert_eq!(unscoped.stamp(), None);
21257        }
21258
21259        #[tokio::test]
21260        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21261            let mut rig = rig_with_flow_support(false).await;
21262            let mut record = session(1);
21263            record.attributes.flow_id = Some("flow:7".to_string());
21264            rig.sync(vec![record]).await;
21265            for opener in [OWNER, AFT] {
21266                let body = rig
21267                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21268                    .await;
21269                assert_eq!(body["code"], "target_flow_unsupported");
21270                let message = body["message"].as_str().unwrap();
21271                for required in [PLEXUS, "flow-scopes/v1"] {
21272                    assert!(message.contains(required), "{message}");
21273                }
21274            }
21275        }
21276
21277        #[tokio::test]
21278        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21279            let mut rig = rig_with_flow_support(true).await;
21280            let mut record = session(1);
21281            record.attributes.flow_id = Some("flow:7".to_string());
21282            rig.sync(vec![record]).await;
21283            for opener in [OWNER, AFT] {
21284                let route = rig
21285                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21286                    .await;
21287                assert!(rig.live(&route));
21288                assert_eq!(
21289                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21290                    Some("flow:7")
21291                );
21292            }
21293        }
21294
21295        #[tokio::test]
21296        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21297            use std::future::Future;
21298
21299            let mut rig = rig_with_flow_support(true).await;
21300            let mut record = session(1);
21301            record.attributes.flow_id = Some("flow:7".to_string());
21302            rig.sync(vec![record]).await;
21303            let (client, mut client_rx, frame) =
21304                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21305            // Hold the route-open response permit so admission sees the first
21306            // target but relay reservation cannot capture an endpoint yet.
21307            for _ in 0..64 {
21308                client.egress.try_send(route_bind_ack(1)).unwrap();
21309            }
21310            let handler = rig.handler.clone();
21311            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21312            std::future::poll_fn(|cx| {
21313                assert!(open.as_mut().poll(cx).is_pending());
21314                std::task::Poll::Ready(())
21315            })
21316            .await;
21317            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21318
21319            let old_connection = rig.modules[PLEXUS].0.connection_id;
21320            rig.handler.cleanup_connection(old_connection).unwrap();
21321            let (replacement, mut replacement_rx) = wide_ctx(200);
21322            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21323            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21324            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21325            let hello = Frame::build(
21326                FrameType::Hello,
21327                control_flags(),
21328                0,
21329                0,
21330                200,
21331                serde_json::to_vec(&body).unwrap(),
21332            )
21333            .unwrap();
21334            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21335
21336            client_rx.try_recv().unwrap();
21337            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21338                .await
21339                .expect("the replacement is refused without waiting for a bind ack")
21340                .unwrap();
21341            assert_eq!(replies.len(), 1);
21342            let body = parse_error(&replies[0]);
21343            assert_eq!(body["code"], "target_flow_unsupported");
21344            for required in [PLEXUS, "flow-scopes/v1"] {
21345                assert!(body["message"].as_str().unwrap().contains(required));
21346            }
21347            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21348            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21349            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21350            assert!(rig
21351                .handler
21352                .registry
21353                .get_module_by_connection(replacement.connection_id)
21354                .unwrap()
21355                .is_some());
21356        }
21357
21358        #[tokio::test]
21359        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21360            use std::future::Future;
21361            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21362            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21363            const NEXT_HASH: &str =
21364                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21365            let mut rig = rig().await;
21366            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21367            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21368            rig.sync(vec![record.clone()]).await;
21369            let (client, mut rx, frame) = rig.open_frame(
21370                None,
21371                PLEXUS,
21372                Some(
21373                    rig.selector("s", Some(1))
21374                        .with_bind_proof(Some(PROOF.into())),
21375                ),
21376            );
21377            // Hold egress reservation while the scope owner changes its bind-proof
21378            // hash, so a proof valid at admission must be checked again at relay.
21379            for _ in 0..64 {
21380                client.egress.try_send(route_bind_ack(1)).unwrap();
21381            }
21382            let handler = rig.handler.clone();
21383            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21384            std::future::poll_fn(|cx| {
21385                assert!(open.as_mut().poll(cx).is_pending());
21386                std::task::Poll::Ready(())
21387            })
21388            .await;
21389            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21390            rig.sync(vec![record]).await;
21391            rx.try_recv().unwrap();
21392            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21393                .await
21394                .unwrap()
21395                .unwrap();
21396            assert_eq!(
21397                parse_error(&replies[0])["code"],
21398                error_codes::SCOPE_BIND_PROOF_MISMATCH
21399            );
21400            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21401            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21402            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21403        }
21404
21405        #[tokio::test]
21406        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21407            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21408            let mut rig = rig().await;
21409            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21410                .await;
21411            for opener in [OWNER, AFT] {
21412                for proof in [None, Some("malformed+proof=")] {
21413                    let route = rig
21414                        .bound(
21415                            Some(opener),
21416                            PLEXUS,
21417                            Some(
21418                                rig.selector("s", Some(1))
21419                                    .with_bind_proof(proof.map(str::to_string)),
21420                            ),
21421                        )
21422                        .await;
21423                    assert!(rig.live(&route));
21424                }
21425            }
21426        }
21427
21428        #[tokio::test]
21429        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21430            use std::future::Future;
21431            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21432            const NEXT_HASH: &str =
21433                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21434            let mut rig = rig().await;
21435            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21436                .await;
21437            let (client, mut rx, frame) =
21438                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21439            for _ in 0..64 {
21440                client.egress.try_send(route_bind_ack(1)).unwrap();
21441            }
21442            let handler = rig.handler.clone();
21443            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21444            std::future::poll_fn(|cx| {
21445                assert!(open.as_mut().poll(cx).is_pending());
21446                std::task::Poll::Ready(())
21447            })
21448            .await;
21449            rig.sync(vec![
21450                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21451            ])
21452            .await;
21453            rx.try_recv().unwrap();
21454            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21455            let bind = std::future::poll_fn(|cx| {
21456                assert!(open.as_mut().poll(cx).is_pending());
21457                module_rx.poll_recv(cx)
21458            })
21459            .await
21460            .unwrap()
21461            .frame;
21462            handler
21463                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21464                .await
21465                .unwrap();
21466            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21467                .await
21468                .unwrap()
21469                .unwrap();
21470            assert_eq!(replies.len(), 1);
21471            // Proof rechecking allowed the relay. Independent tag settlement
21472            // still asks the opener to retry after any same-epoch content change.
21473            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21474            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21475            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21476            let route = rig
21477                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21478                .await;
21479            assert!(rig.live(&route));
21480        }
21481
21482        #[tokio::test]
21483        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21484        {
21485            let mut rig = rig_with_flow_support(false).await;
21486            rig.sync(vec![session(1)]).await;
21487            let route = rig
21488                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21489                .await;
21490            assert!(rig.live(&route));
21491            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21492            let mut record = session(1);
21493            record.attributes.flow_id = Some("flow:7".to_string());
21494            rig.sync(vec![record]).await;
21495            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21496            assert!(rig.live(&unscoped));
21497            assert_eq!(unscoped.stamp(), None);
21498        }
21499
21500        #[tokio::test]
21501        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21502            let mut rig = rig().await;
21503            let mut record = session(1);
21504            record.attributes.flow_id = Some("flow:7".to_string());
21505            rig.sync(vec![record.clone()]).await;
21506            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21507            let mut owner_route = rig
21508                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21509                .await;
21510            let mut carrier_route = rig
21511                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21512                .await;
21513            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21514            rig.sync(vec![record.clone()]).await;
21515            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21516            assert!(rig.live(&owner_route) && owner_route.untouched());
21517            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21518
21519            record.attributes.flow_id = Some("flow:8".to_string());
21520            rig.sync(vec![record]).await;
21521            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21522            let before = before.unwrap();
21523            assert_eq!(after.scope_epoch, before.scope_epoch);
21524            assert!(after.version > before.version);
21525            for route in [&mut owner_route, &mut carrier_route] {
21526                assert!(!rig.live(route));
21527                assert_eq!(
21528                    route.closed_reason(),
21529                    RouteCloseReason::ScopeDelegationChanged
21530                );
21531            }
21532            assert!(rig.live(&unscoped) && unscoped.untouched());
21533            // Each provider also receives a GOODBYE for its drained route;
21534            // consume it before expecting the next route.bind on that sink.
21535            for target in [PLEXUS, OTHER] {
21536                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21537                let goodbye = module_rx
21538                    .try_recv()
21539                    .expect("the provider sees the drain")
21540                    .frame;
21541                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21542                assert!(module_rx.try_recv().is_err());
21543            }
21544            let rebound = rig
21545                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21546                .await;
21547            assert_eq!(
21548                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21549                Some("flow:8")
21550            );
21551        }
21552
21553        /// The owner's sync lands between admission and the module's ack. The
21554        /// open is refused by name, the module's other routes stay up, and the
21555        /// reserved pair is released. Changed content is retryable; an ended
21556        /// scope is not.
21557        #[tokio::test]
21558        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21559            let mut rig = rig().await;
21560            rig.sync(vec![session(1)]).await;
21561            let mut cotenant = rig
21562                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21563                .await;
21564
21565            let mut changed = session(1);
21566            changed.child_owners.push(Principal::Reserved {
21567                module_id: MAGIC.to_string(),
21568            });
21569            let mut ended = None;
21570            for (code, next) in [
21571                (error_codes::SCOPE_CHANGED, vec![changed]),
21572                (error_codes::SCOPE_ENDED, Vec::new()),
21573            ] {
21574                let relayed = rig
21575                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21576                    .await;
21577                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21578                ended = Some(next.is_empty());
21579                rig.sync(next).await;
21580                rig.ack(&relayed).await;
21581                let replies = relayed.task.await.unwrap();
21582                assert_eq!(replies.len(), 1, "{replies:?}");
21583                assert_eq!(parse_error(&replies[0])["code"], code);
21584                assert_eq!(
21585                    subc_protocol::error_codes::is_retryable_route_open(code),
21586                    code == error_codes::SCOPE_CHANGED
21587                );
21588                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21589                // The module is told to drop just the binding it created.
21590                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21591                // Collected, because ending the scope also closes the co-tenant
21592                // route, whose GOODBYE comes first.
21593                let mut goodbyes = Vec::new();
21594                while let Ok(outbound) = plexus_rx.try_recv() {
21595                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21596                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21597                }
21598                assert!(
21599                    goodbyes.contains(&(bind_channel, bind_epoch)),
21600                    "{goodbyes:?}"
21601                );
21602                assert!(rig
21603                    .handler
21604                    .registry
21605                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21606                    .unwrap()
21607                    .is_some());
21608            }
21609            assert_eq!(ended, Some(true));
21610            // The co-tenant stayed up through the change, and closed only when
21611            // the scope ended, by the drain rule rather than by the commit.
21612            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21613        }
21614
21615        /// Each row of the drain table on one set of routes: the owner's, a
21616        /// bare carrier's, and a targeted carrier's to each of its targets.
21617        #[tokio::test]
21618        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21619            struct Case {
21620                name: &'static str,
21621                change: fn(&mut ScopeRecord),
21622                /// Closed routes by index: owner->plexus, aft->plexus,
21623                /// broca->plexus, broca->other.
21624                closed: [Option<RouteCloseReason>; 4],
21625            }
21626            use RouteCloseReason::*;
21627            let cases = [
21628                Case {
21629                    name: "a carrier entry removed",
21630                    change: |r| {
21631                        r.carriers.retain(|c| {
21632                            c.principal
21633                                != Principal::Reserved {
21634                                    module_id: AFT.to_string(),
21635                                }
21636                        })
21637                    },
21638                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21639                },
21640                Case {
21641                    name: "a target removed from a carrier",
21642                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21643                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21644                },
21645                Case {
21646                    name: "a bare carrier narrowed to targets",
21647                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21648                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21649                },
21650                Case {
21651                    name: "delegates turned off",
21652                    change: |r| r.attributes.delegates = false,
21653                    closed: [Some(ScopeDelegationChanged); 4],
21654                },
21655                Case {
21656                    name: "agent_id changed",
21657                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21658                    closed: [Some(ScopeDelegationChanged); 4],
21659                },
21660                Case {
21661                    name: "a carrier added, child owners changed, the record re-sent",
21662                    change: |r| {
21663                        r.carriers.push(carrier(MAGIC, None));
21664                        r.child_owners.push(Principal::Reserved {
21665                            module_id: MAGIC.to_string(),
21666                        });
21667                    },
21668                    closed: [None; 4],
21669                },
21670                Case {
21671                    name: "a target added",
21672                    change: |r| {
21673                        r.carriers[1]
21674                            .targets
21675                            .as_mut()
21676                            .unwrap()
21677                            .push("third".to_string())
21678                    },
21679                    closed: [None; 4],
21680                },
21681                Case {
21682                    name: "delegates turned on",
21683                    change: |r| r.attributes.delegates = true,
21684                    closed: [None; 4],
21685                },
21686            ];
21687            for case in cases {
21688                let mut rig = rig().await;
21689                rig.sync(vec![session(1)]).await;
21690                let scope = || Some(rig_selector("s", Some(1)));
21691                let mut routes = [
21692                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21693                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21694                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21695                    rig.bound(Some(BROCA), OTHER, scope()).await,
21696                ];
21697                let mut record = session(1);
21698                (case.change)(&mut record);
21699                rig.sync(vec![record]).await;
21700                for (index, expected) in case.closed.iter().enumerate() {
21701                    let route = &mut routes[index];
21702                    match expected {
21703                        Some(reason) => {
21704                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21705                            assert_eq!(
21706                                route.closed_reason(),
21707                                *reason,
21708                                "{}: route {index}",
21709                                case.name
21710                            );
21711                        }
21712                        None => {
21713                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21714                            assert!(
21715                                route.untouched(),
21716                                "{}: route {index} was told something",
21717                                case.name
21718                            );
21719                        }
21720                    }
21721                }
21722            }
21723        }
21724
21725        #[tokio::test]
21726        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21727            // Removed, and replaced by a higher epoch.
21728            for next in [Vec::new(), vec![session(2)]] {
21729                let mut rig = rig().await;
21730                rig.sync(vec![session(1)]).await;
21731                let mut route = rig
21732                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21733                    .await;
21734                rig.sync(next).await;
21735                assert!(!rig.live(&route));
21736                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21737            }
21738
21739            // A child whose parent ends: its routes close as parent-ended, the
21740            // child stays live, and routes under the parent close as ended.
21741            let mut rig = rig().await;
21742            let mut child = session(1);
21743            child.scope_ref = "child".to_string();
21744            child.kind = ScopeKind::Worker;
21745            child.parent = Some(ScopeParent::new(
21746                Principal::Reserved {
21747                    module_id: OWNER.to_string(),
21748                },
21749                "s".to_string(),
21750                1,
21751            ));
21752            rig.sync(vec![session(1), child.clone()]).await;
21753            let mut child_route = rig
21754                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21755                .await;
21756            assert_eq!(
21757                child_route.stamp().unwrap().parent_state,
21758                Some(ParentState::Linked)
21759            );
21760            rig.sync(vec![child]).await;
21761            assert!(!rig.live(&child_route));
21762            assert_eq!(
21763                child_route.closed_reason(),
21764                RouteCloseReason::ScopeParentEnded
21765            );
21766        }
21767
21768        #[tokio::test]
21769        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21770        ) {
21771            let mut rig = rig().await;
21772            rig.sync(vec![session(1)]).await;
21773            let mut route = rig
21774                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21775                .await;
21776            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21777            rig.sync(vec![session(1)]).await;
21778            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21779            assert!(rig.live(&route) && route.untouched());
21780
21781            // A call in flight on the route when another carrier is added. A
21782            // forwarded REQUEST holds one credit on the route's flow until the
21783            // module answers; the router takes it exactly like this.
21784            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21785                .forwarding
21786                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21787                .unwrap()
21788            else {
21789                panic!("the route is bound");
21790            };
21791            binding.flow.acquire_tagged(9, false).await.unwrap();
21792            let mut widened = session(1);
21793            widened.carriers.push(carrier(MAGIC, None));
21794            rig.sync(vec![widened]).await;
21795            assert!(rig.live(&route) && route.untouched());
21796            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21797            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21798            // The call's credit is still held on an open flow, so its answer
21799            // will be delivered: closing the route would have closed the flow.
21800            assert_eq!(binding.flow.in_flight(), 1);
21801            binding
21802                .flow
21803                .acquire_tagged(10, false)
21804                .await
21805                .expect("the flow is still open");
21806        }
21807
21808        /// A swap's superseded endpoint keeps its routes until drained; ending
21809        /// the scope closes them there too.
21810        #[tokio::test]
21811        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21812            let mut rig = rig().await;
21813            rig.sync(vec![session(1)]).await;
21814            let mut on_incumbent = rig
21815                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21816                .await;
21817
21818            // Swap plexus: register a candidate and cut over, leaving the
21819            // incumbent superseded with the route still on it.
21820            let (candidate, _candidate_rx) = wide_ctx(9);
21821            let registration = rig
21822                .handler
21823                .registry
21824                .register_candidate_with_control_ops(
21825                    manifest(PLEXUS, PROTOCOL_VERSION),
21826                    PROTOCOL_VERSION,
21827                    candidate.connection_id,
21828                    module_baseline_control_ops(),
21829                )
21830                .unwrap();
21831            rig.forwarding
21832                .register_candidate_module_connection(
21833                    candidate.connection_id,
21834                    PLEXUS.to_string(),
21835                    PROTOCOL_VERSION,
21836                    manifest_concurrency(&registration.manifest),
21837                    candidate.egress.clone(),
21838                )
21839                .unwrap();
21840            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21841            rig.handler
21842                .registry
21843                .promote_candidate(PLEXUS)
21844                .unwrap()
21845                .unwrap();
21846            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21847
21848            rig.sync(Vec::new()).await;
21849            assert!(!rig.live(&on_incumbent));
21850            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21851            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21852            let goodbye = incumbent_rx
21853                .try_recv()
21854                .expect("the superseded endpoint is told")
21855                .frame;
21856            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21857        }
21858    }
21859}
21860
21861#[cfg(test)]
21862mod concurrency_default_exposure_tests {
21863    use super::*;
21864
21865    fn hello_body(role_json: &str) -> Vec<u8> {
21866        format!(
21867            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":[]}}}}}}}}"#
21868        )
21869        .into_bytes()
21870    }
21871
21872    fn manifest_from(body: &[u8]) -> ModuleManifest {
21873        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21874        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21875            .expect("manifest parses")
21876    }
21877
21878    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21879
21880    #[test]
21881    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21882        let body = hello_body(&format!(
21883            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21884        ));
21885        let manifest = manifest_from(&body);
21886        // Precondition: serde really resolved it to the default, so the typed
21887        // manifest alone cannot answer the question this probe exists for.
21888        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21889        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21890    }
21891
21892    #[test]
21893    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21894        let body = hello_body(&format!(
21895            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21896        ));
21897        let manifest = manifest_from(&body);
21898        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21899        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21900    }
21901
21902    #[test]
21903    fn non_management_roles_are_never_reported() {
21904        let body = hello_body(
21905            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21906        );
21907        let manifest = manifest_from(&body);
21908        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21909    }
21910}