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::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1200                PEER_BUILD_CAPABILITY.to_string(),
1201                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1202                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1203                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1204                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1205                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1206                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1207                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1208                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1209                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1210                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1211                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1212                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1213            ]),
1214            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1215            route_bind_relay_timeouts: BTreeMap::new(),
1216            route_bind_breakers,
1217            route_bind_concurrency,
1218            route_outages,
1219            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1220            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1221            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1222            storage_config: None,
1223            machine_id: None,
1224            admission_facts_carrier_module_id: None,
1225            admission_facts_targets: None,
1226            scopes: Arc::new(RwLock::new(ScopeTable::new(
1227                crate::daemon_config::default_scope_authority_owners(),
1228            ))),
1229            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1230            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1231            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1232            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1233            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1234            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1235            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1236            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1237            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1238            local_connections: Arc::new(Mutex::new(HashSet::new())),
1239            operator_app_policy: Default::default(),
1240            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1241            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1242            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1243            #[cfg(test)]
1244            app_open_test_platform: None,
1245            #[cfg(test)]
1246            app_open_test_launch: None,
1247            #[cfg(test)]
1248            config_review_test_reply: None,
1249            #[cfg(test)]
1250            recovery_exit_test_after_step: None,
1251            #[cfg(test)]
1252            recovery_exit_test_completed: None,
1253            #[cfg(test)]
1254            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1255            #[cfg(test)]
1256            recovery_exit_test_quiet_retry: false,
1257            #[cfg(test)]
1258            recovery_exit_test_retry_pause: None,
1259            #[cfg(test)]
1260            config_delivery_test_wakes: None,
1261            #[cfg(all(test, unix))]
1262            config_delivery_test_idle: None,
1263            #[cfg(windows)]
1264            windows_verify: None,
1265            #[cfg(windows)]
1266            windows_flash: None,
1267            #[cfg(windows)]
1268            windows_track: None,
1269            #[cfg(all(test, windows))]
1270            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1271            #[cfg(test)]
1272            caller_lookup: None,
1273            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1274            rescan: None,
1275            connected_clients: ConnectedClients::new(),
1276            local_endpoint_unavailable: None,
1277            counters,
1278            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1279            daemon_shutdown: DaemonShutdownFlag::default(),
1280            daemon_provenance: DaemonProvenanceFacts::default(),
1281            #[cfg(test)]
1282            control_dispatch_delay: None,
1283            #[cfg(test)]
1284            provenance_probe_override: None,
1285            #[cfg(test)]
1286            route_bind_relay_sent_hold: None,
1287            #[cfg(test)]
1288            hello_registry_to_forwarding_hold: None,
1289            #[cfg(test)]
1290            hello_ack_to_publication_hold: None,
1291            #[cfg(test)]
1292            hello_before_publication_hold: None,
1293            #[cfg(test)]
1294            hello_after_launch_check_hold: None,
1295            #[cfg(test)]
1296            hello_inside_publication_hold: None,
1297        }
1298    }
1299
1300    /// Set the central storage policy: registering modules then receive their
1301    /// resolved storage descriptor in HELLO_ACK.
1302    pub fn with_storage_config(
1303        mut self,
1304        storage_config: Option<crate::daemon_config::StorageConfig>,
1305    ) -> Self {
1306        self.storage_config = storage_config;
1307        self
1308    }
1309
1310    /// Open the ledger on its own writer thread; an unavailable sink does not
1311    /// prevent the daemon from serving routing or supervisor requests.
1312    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1313        self.activity = Some(crate::activity::ActivityLedger::open(
1314            run_dir.join("activity.jsonl"),
1315            incarnation,
1316        ));
1317        self.supervisor.set_activity(self.activity.clone());
1318        self
1319    }
1320
1321    /// Set the machine id served to every registering module (HELLO_ACK) and on
1322    /// `server.describe`.
1323    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1324        self.machine_id = machine_id;
1325        self
1326    }
1327
1328    /// Configure the exact reserved module and target ids permitted to relay
1329    /// opaque admission facts. Config-file loading validates this authority;
1330    /// this builder keeps the same policy available to embedded test daemons.
1331    pub fn with_admission_facts_config(
1332        mut self,
1333        carrier_module_id: Option<String>,
1334        targets: Option<Vec<String>>,
1335    ) -> Self {
1336        self.admission_facts_carrier_module_id = carrier_module_id;
1337        self.admission_facts_targets = targets;
1338        self
1339    }
1340
1341    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1342    /// Replaces the scope table with an empty one under the new list, so call it
1343    /// while building the handler, before any module can sync.
1344    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1345        self.scopes = Arc::new(RwLock::new(
1346            ScopeTable::new(owners.iter().cloned())
1347                .with_federated_owner(self.federated_scope_owner.clone()),
1348        ));
1349        self.scope_authority_owners = owners;
1350        self
1351    }
1352
1353    /// Set the exclusive federated owner while building the handler, before syncs.
1354    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1355        self.scopes = Arc::new(RwLock::new(
1356            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1357                .with_federated_owner(owner.clone()),
1358        ));
1359        self.federated_scope_owner = owner;
1360        self
1361    }
1362
1363    /// Set the startup policy before installing the rescan context or serving requests.
1364    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1365        self.privileged_operator_prompt = mode;
1366        self
1367    }
1368
1369    /// Override the route.bind relay timeout. Used by tests that assert the
1370    /// timeout path so they don't block on the production-safe default.
1371    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1372        self.route_bind_relay_timeout = timeout;
1373        self
1374    }
1375
1376    /// Install per-module route.bind relay budget overrides. A module id
1377    /// listed here wins over the daemon-wide default set via
1378    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1379    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1380    /// the same `Duration` the bind path will use.
1381    pub fn with_route_bind_relay_timeouts(
1382        mut self,
1383        timeouts: impl IntoIterator<Item = (String, Duration)>,
1384    ) -> Self {
1385        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1386        self
1387    }
1388
1389    /// Resolve the route.bind relay budget for a specific target module id.
1390    /// Per-module overrides win; the daemon-wide value (set via
1391    /// `with_route_bind_relay_timeout` or the built-in default) is the
1392    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1393    /// the same resolution `handle_route_open` will use.
1394    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1395        self.route_bind_relay_timeouts
1396            .get(module_id)
1397            .copied()
1398            .unwrap_or(self.route_bind_relay_timeout)
1399    }
1400
1401    /// Override the per-module bind-relay breaker policy.
1402    ///
1403    /// Used by tests, which cannot spend three production budgets opening a
1404    /// breaker or twenty seconds waiting for its cooldown. The production
1405    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1406    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1407    /// reasoning for the numbers.
1408    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1409        self.route_bind_breaker_threshold = threshold.max(1);
1410        self.route_bind_breaker_cooldown = cooldown;
1411        self
1412    }
1413
1414    #[cfg(test)]
1415    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1416        self.health_probe_timeout = timeout;
1417        self
1418    }
1419
1420    #[cfg(test)]
1421    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1422        self.control_dispatch_delay = Some(delay);
1423        self
1424    }
1425
1426    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1427    /// announce it is parked, once to be released. Build the barrier for two
1428    /// parties, the test being the other one.
1429    #[cfg(test)]
1430    pub(crate) fn with_route_bind_relay_sent_hold(
1431        mut self,
1432        hold: Arc<tokio::sync::Barrier>,
1433    ) -> Self {
1434        self.route_bind_relay_sent_hold = Some(hold);
1435        self
1436    }
1437
1438    /// A HELLO waits on `hold` twice between reserving its registry entry and
1439    /// installing its forwarding endpoint: once to announce it is parked, once
1440    /// to be released. Build the barrier for two parties, the test being the
1441    /// other one, and run the HELLO on a thread of its own.
1442    #[cfg(test)]
1443    pub(crate) fn with_hello_registry_to_forwarding_hold(
1444        mut self,
1445        hold: Arc<std::sync::Barrier>,
1446    ) -> Self {
1447        self.hello_registry_to_forwarding_hold = Some(hold);
1448        self
1449    }
1450
1451    #[cfg(test)]
1452    fn hold_between_registry_and_forwarding(&self) {
1453        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1454            hold.wait();
1455            hold.wait();
1456        }
1457    }
1458
1459    /// Park after the ACK is queued and forwarding is installed, until a test
1460    /// has read the ACK and issued a registry lookup from another connection.
1461    #[cfg(test)]
1462    fn hold_between_ack_and_publication(&self) {
1463        if let Some(hold) = &self.hello_ack_to_publication_hold {
1464            hold.wait();
1465            hold.wait();
1466        }
1467    }
1468
1469    #[cfg(all(test, unix))]
1470    pub(crate) fn with_hello_before_publication_hold(
1471        mut self,
1472        hold: Arc<std::sync::Barrier>,
1473    ) -> Self {
1474        self.hello_before_publication_hold = Some(hold);
1475        self
1476    }
1477
1478    #[cfg(all(test, unix))]
1479    pub(crate) fn with_hello_after_launch_check_hold(
1480        mut self,
1481        hold: Arc<std::sync::Barrier>,
1482    ) -> Self {
1483        self.hello_after_launch_check_hold = Some(hold);
1484        self
1485    }
1486
1487    #[cfg(all(test, unix))]
1488    pub(crate) fn with_hello_inside_publication_hold(
1489        mut self,
1490        hold: Arc<std::sync::Barrier>,
1491    ) -> Self {
1492        self.hello_inside_publication_hold = Some(hold);
1493        self
1494    }
1495
1496    pub fn with_process_liveness(
1497        mut self,
1498        process_liveness: Arc<dyn ModuleProcessLiveness>,
1499    ) -> Self {
1500        self.process_liveness = Some(process_liveness);
1501        self
1502    }
1503
1504    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1505        self.supervisor = supervisor;
1506        if let Some(owner) = &self.config_runtime {
1507            self.supervisor.install_binding_retirement(owner);
1508        }
1509        self.supervisor.set_activity(self.activity.clone());
1510        self
1511    }
1512
1513    pub fn with_daemon_provenance(
1514        mut self,
1515        pid: u32,
1516        started_at_ms: u64,
1517        executable_path: Option<PathBuf>,
1518        build_git_sha: Option<String>,
1519        build_lock_digest: Option<String>,
1520    ) -> Self {
1521        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1522        let process_start_time = process_start_time(pid);
1523        self.daemon_provenance = DaemonProvenanceFacts {
1524            build: DaemonBuildProvenance {
1525                build_git_sha,
1526                build_lock_digest,
1527            },
1528            pid: Some(pid),
1529            started_at_ms: Some(started_at_ms),
1530            start_clock: None,
1531            executable_path,
1532            executable_identity,
1533            process_start_time,
1534            probe: ExecutableIdentityProbe::default(),
1535        };
1536        self
1537    }
1538
1539    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1540        self.daemon_provenance.start_clock = Some(clock);
1541        self
1542    }
1543
1544    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1545    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1546        self.scopes
1547            .write()
1548            .unwrap_or_else(|poisoned| poisoned.into_inner())
1549            .set_wall_clock(Arc::new(clock));
1550        self
1551    }
1552
1553    #[cfg(test)]
1554    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1555        self.provenance_probe_override = Some(result);
1556        self
1557    }
1558
1559    /// Install the configured module set and its reserved capability bindings.
1560    /// Bindings are configuration-scoped and may point at a provider that has not
1561    /// been installed yet, so this does not require the bound module to exist.
1562    pub fn with_capability_config(
1563        self,
1564        modules: impl IntoIterator<Item = (String, bool)>,
1565        reserved_capabilities: BTreeMap<String, String>,
1566    ) -> Self {
1567        self.capability_evaluator
1568            .configure(modules, reserved_capabilities);
1569        self
1570    }
1571
1572    /// Share the supervisor's daemon-shutdown flag with this handler, so
1573    /// requirement changes after the daemon has begun its announced shutdown
1574    /// are not reported as faults.
1575    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1576        self.daemon_shutdown = flag;
1577        self
1578    }
1579
1580    pub fn with_supervisor_rescan(
1581        mut self,
1582        supervisor: Supervisor,
1583        config_path: impl Into<PathBuf>,
1584        configured_port: Option<u16>,
1585    ) -> Self {
1586        self.rescan = Some(SupervisorRescanContext {
1587            supervisor,
1588            config_path: config_path.into(),
1589            configured_port,
1590            storage_config: self.storage_config.clone(),
1591            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1592            admission_facts_targets: self.admission_facts_targets.clone(),
1593            scope_authority_owners: self.scope_authority_owners.clone(),
1594            federated_scope_owner: self.federated_scope_owner.clone(),
1595            privileged_operator_prompt: self.privileged_operator_prompt,
1596            generation: Arc::default(),
1597            rescan_lock: Arc::default(),
1598            module_entries: Arc::default(),
1599        });
1600        self
1601    }
1602
1603    pub(crate) fn with_supervisor_rescan_entries(
1604        self,
1605        modules: &[crate::daemon_config::ConfiguredModule],
1606    ) -> Self {
1607        if let Some(context) = &self.rescan {
1608            let mut entries = context
1609                .module_entries
1610                .lock()
1611                .unwrap_or_else(|e| e.into_inner());
1612            entries.seed(modules);
1613        }
1614        self
1615    }
1616
1617    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1618        self.connected_clients = connected_clients;
1619        self
1620    }
1621
1622    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1623    /// an operator can see a bind failure without reading the daemon log.
1624    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1625        self.local_endpoint_unavailable = reason;
1626        self
1627    }
1628
1629    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1630        Arc::clone(&self.forwarding)
1631    }
1632
1633    pub(crate) fn counters(&self) -> DaemonCounters {
1634        self.counters.clone()
1635    }
1636
1637    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1638    /// requirement event without depending on an operator polling a status command.
1639    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1640        let handler = Arc::downgrade(&self);
1641        let evaluator = self.capability_evaluator.clone();
1642        tokio::spawn(async move {
1643            loop {
1644                evaluator.wait_for_change_or_deadline().await;
1645                let Some(handler) = handler.upgrade() else {
1646                    break;
1647                };
1648                handler.refresh_capability_requirements();
1649            }
1650        });
1651    }
1652
1653    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1654    /// deadline passed during sleep is enforced on the first tick after wake.
1655    /// While no live scope carries a deadline the loop waits for an accepted
1656    /// scope change instead of ticking, so a daemon without deadlines never
1657    /// wakes for expiry.
1658    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1659        let context = scope_expiry::ScopeExpiryContext::new(&self);
1660        let deadline_added = self.scope_deadline_added.clone();
1661        tokio::spawn(async move {
1662            loop {
1663                if !context.has_deadlines() {
1664                    deadline_added.notified().await;
1665                    continue;
1666                }
1667                tokio::time::sleep(Duration::from_secs(1)).await;
1668                if let Err(error) = context.sweep() {
1669                    warn!(%error, "scope expiry sweep failed");
1670                }
1671            }
1672        });
1673    }
1674
1675    #[cfg(test)]
1676    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1677        scope_expiry::ScopeExpiryContext::new(self).sweep()
1678    }
1679
1680    fn publish_scope_changes(
1681        &self,
1682        changes: &[crate::scopes::ScopeTagChange],
1683        expired: &[crate::scopes::ScopeExpired],
1684    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1685        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1686    }
1687
1688    fn runtime_capability_snapshot(
1689        &self,
1690    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1691        let runtime = self
1692            .supervisor
1693            .list()
1694            .into_iter()
1695            .map(|module| {
1696                let status = module.status().map_err(|err| {
1697                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1698                })?;
1699                Ok(RuntimeModule {
1700                    module_id: status.module_id,
1701                    state: status.state,
1702                    enabled: status.enabled,
1703                })
1704            })
1705            .collect::<Result<Vec<_>, RouterError>>()?;
1706        // Include every registration, published or not. The capability
1707        // evaluator counts a module as providing its capabilities as soon as it
1708        // has registered, even before `catalog.list` shows it, so a HELLO in
1709        // progress does not change other modules' required-capability
1710        // verdicts. See `Registry::list_registered_modules`.
1711        let registrations = self.registry.list_registered_modules().map_err(|err| {
1712            RouterError::backend(
1713                0,
1714                0,
1715                format!("failed to list capability registrations: {err}"),
1716            )
1717        })?;
1718        let registrations = registrations
1719            .into_iter()
1720            .map(|registration| RegisteredModule {
1721                module_id: registration.manifest.module_id,
1722                module_version: registration.manifest.module_version,
1723                capabilities: registration.manifest.capabilities,
1724            })
1725            .collect();
1726        Ok((runtime, registrations))
1727    }
1728
1729    /// The capability side effects of a module becoming the active registration
1730    /// for its id: cache its manifest (logging how it differs from the cached
1731    /// one), run the deny census when its declarations call for one, and recompute the
1732    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1733    /// candidate's does not, and the supervisor does it at promotion instead,
1734    /// through [`crate::supervise::SwapPromotionObserver`].
1735    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1736        let cached_registration = RegisteredModule {
1737            module_id: registration.manifest.module_id.clone(),
1738            module_version: registration.manifest.module_version.clone(),
1739            capabilities: registration.manifest.capabilities.clone(),
1740        };
1741        let change = self.capability_evaluator.record_hello(&cached_registration);
1742        log_manifest_change(&cached_registration.module_id, &change);
1743        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1744            self.enforce_capability_denies();
1745        }
1746        self.refresh_capability_requirements();
1747    }
1748
1749    /// Point the shared supervisor handle at this handler for swap promotions.
1750    /// Called wherever a handler is put behind the `Arc` the router serves, so
1751    /// it can be held weakly.
1752    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1753        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1754            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1755        self.supervisor.set_swap_promotion_observer(observer);
1756    }
1757
1758    pub fn refresh_capability_requirements(&self) {
1759        match self.runtime_capability_snapshot() {
1760            Ok((runtime, registrations)) => {
1761                let events = self
1762                    .capability_evaluator
1763                    .evaluate_now(&runtime, &registrations);
1764                if !events.is_empty() {
1765                    self.catalog_readiness_revision
1766                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1767                }
1768                log_requirement_events(events, &self.daemon_shutdown);
1769            }
1770            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1771        }
1772    }
1773
1774    /// Reconcile only live, attested route bindings after a capability deny edge
1775    /// or target claim was added. This is deliberately a control-plane census:
1776    /// the opaque forwarding hot path must not grow a per-frame capability check.
1777    fn enforce_capability_denies(&self) {
1778        let registrations = match self.registry.list_registered_modules() {
1779            Ok(snapshot) => snapshot,
1780            Err(err) => {
1781                warn!(error = %err, "failed to read registrations for capability deny census");
1782                return;
1783            }
1784        };
1785        let manifests = registrations
1786            .into_iter()
1787            .map(|registration| {
1788                (
1789                    registration.manifest.module_id.clone(),
1790                    registration.manifest,
1791                )
1792            })
1793            .collect::<BTreeMap<_, _>>();
1794        let census = match self.forwarding.route_census(None) {
1795            Ok(census) => census,
1796            Err(err) => {
1797                warn!(error = %err, "failed to read route census for capability deny enforcement");
1798                return;
1799            }
1800        };
1801
1802        for (target_module_id, routes) in census {
1803            let Some(target_manifest) = manifests.get(&target_module_id) else {
1804                continue;
1805            };
1806            let mut closed_routes = Vec::new();
1807            let mut goodbyes = Vec::new();
1808            for route in routes {
1809                let Principal::Reserved {
1810                    module_id: opening_module_id,
1811                } = &route.principal
1812                else {
1813                    continue;
1814                };
1815                let Some(opening_manifest) = manifests.get(opening_module_id) else {
1816                    continue;
1817                };
1818                let Some(capability) = denied_capability(
1819                    opening_manifest.capabilities.as_ref(),
1820                    target_manifest.capabilities.as_ref(),
1821                ) else {
1822                    continue;
1823                };
1824
1825                match self.forwarding.release_client_route(
1826                    route.goodbye_target.connection_id,
1827                    route.goodbye_target.channel,
1828                    route.goodbye_target.epoch,
1829                ) {
1830                    Ok(RouteRelease::Removed(module_goodbye)) => {
1831                        warn!(
1832                            opening_module_id,
1833                            target_module_id,
1834                            capability,
1835                            "force-closing route because an attested capability deny edge now matches"
1836                        );
1837                        goodbyes.push(module_goodbye);
1838                        goodbyes.push(route.goodbye_target.clone());
1839                        closed_routes.push(route);
1840                    }
1841                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
1842                    Err(err) => warn!(
1843                        opening_module_id,
1844                        target_module_id,
1845                        capability,
1846                        error = %err,
1847                        "failed to force-close capability-denied route"
1848                    ),
1849                }
1850            }
1851
1852            if closed_routes.is_empty() {
1853                continue;
1854            }
1855            send_route_control_pushes(
1856                &self.forwarding,
1857                closed_routes,
1858                ClientControlPush::RouteClosed {
1859                    module_id: target_module_id,
1860                    channels: Vec::new(),
1861                    reason: RouteCloseReason::CapabilityDenied,
1862                    drained: false,
1863                    abandoned: 0,
1864                    excluded_subscriptions: 0,
1865                    terminal: Some(false),
1866                },
1867            );
1868            // route.closed records the reason; the route GOODBYE ends the
1869            // client's handle and settles any calls still pending on it.
1870            self.emit_route_goodbyes(goodbyes);
1871        }
1872    }
1873
1874    /// Why a registered module is not accepting new route binds, or `None` when
1875    /// it is. This is the module's effective readiness: its declared readiness
1876    /// first, then every `need: required` capability it declares evaluating to
1877    /// `provided`. `route.open` and `catalog.list` both read it here so the
1878    /// catalog never reports a module routable that `route.open` would refuse.
1879    fn not_ready_reason(
1880        &self,
1881        registration: &crate::registry::ModuleRegistration,
1882    ) -> Option<NotReadyReason> {
1883        if !registration.ready {
1884            return Some(NotReadyReason {
1885                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1886                capability: None,
1887            });
1888        }
1889        self.first_unprovided_required_capability(registration)
1890            .map(|capability| NotReadyReason {
1891                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1892                capability: Some(capability),
1893            })
1894    }
1895
1896    /// The lexicographically first capability this registration declares
1897    /// `need: required` whose evaluator verdict is not `provided`.
1898    ///
1899    /// The verdicts are the capability evaluator's own; nothing here decides
1900    /// what "provided" means. The evaluator counts a capability provided as
1901    /// soon as a module claiming it has REGISTERED, not once that module is
1902    /// ready. That distinction is what keeps two modules that require each
1903    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1904    /// is ready", each would wait for the other to become ready first and
1905    /// neither ever would. Do not tighten it to readiness.
1906    ///
1907    /// A required capability with no verdict at all means this registration's
1908    /// HELLO or catalog.update landed after the last recompute; recompute once
1909    /// rather than let a missing verdict read as either answer. If it is still
1910    /// missing (the recompute itself failed) the capability counts as
1911    /// unprovided: the refusal is retryable, and routing a module whose
1912    /// required provider is unknown is the outcome this check exists to stop.
1913    fn first_unprovided_required_capability(
1914        &self,
1915        registration: &crate::registry::ModuleRegistration,
1916    ) -> Option<String> {
1917        self.first_unprovided_required_capability_for(
1918            &registration.manifest.module_id,
1919            registration.manifest.capabilities.as_ref(),
1920        )
1921    }
1922
1923    fn first_unprovided_required_capability_for(
1924        &self,
1925        module_id: &str,
1926        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1927    ) -> Option<String> {
1928        let required = capabilities
1929            .into_iter()
1930            .flat_map(|declarations| declarations.requires.iter())
1931            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1932            .map(|requirement| requirement.capability.as_str())
1933            .collect::<BTreeSet<_>>();
1934        if required.is_empty() {
1935            return None;
1936        }
1937        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1938        if required
1939            .iter()
1940            .any(|capability| verdict(capability).is_none())
1941        {
1942            self.refresh_capability_requirements();
1943        }
1944        required
1945            .into_iter()
1946            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1947            .map(str::to_string)
1948    }
1949
1950    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1951        self.capability_evaluator
1952            .statuses()
1953            .into_iter()
1954            .map(capability_requirement_status)
1955            .collect()
1956    }
1957
1958    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1959    /// registration-release watch. The signal is what the supervisor waits on
1960    /// before spawning a replacement, so it must only fire once forwarding
1961    /// teardown is also done (see [`Self::cleanup_connection`] /
1962    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1963    /// registry-only path below because publication already owns the spawn lock.
1964    fn deregister_connection(
1965        &self,
1966        connection_id: ConnectionId,
1967        reason: RegistrationEndReason,
1968    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1969        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1970            spawn.end_primary_registration();
1971        }
1972        self.registry
1973            .deregister_connection_with_reason(connection_id, reason)
1974    }
1975
1976    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1977    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1978    // or claim-bound consumers to revoke. Remove only its unpublished registry
1979    // entry without re-entering primary-registration teardown.
1980    fn rollback_unpublished_hello(
1981        &self,
1982        connection: ConnectionId,
1983    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1984        self.registry.deregister_connection_with_reason(
1985            connection,
1986            RegistrationEndReason::RegistrationFailed,
1987        )
1988    }
1989
1990    fn request_refusal_close(
1991        &self,
1992        connection: ConnectionId,
1993        sink: Option<&crate::FrameSink>,
1994        reason: CloseReason,
1995    ) {
1996        if let Some(sink) = sink {
1997            sink.terminate_ingress();
1998        }
1999        if self.claims.close_notifications_enabled() {
2000            self.forwarding.request_connection_close(connection, reason);
2001        }
2002    }
2003
2004    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
2005        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
2006            return None;
2007        }
2008        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
2009            parse_client_control_request(&frame.body)
2010        else {
2011            return None;
2012        };
2013        Some(target_module_id(&target).to_string())
2014    }
2015
2016    pub(crate) fn route_open_capacity_refusal(
2017        &self,
2018        ctx: &RouteCtx,
2019        frame: &Frame,
2020        target_module_id: &str,
2021        in_flight: usize,
2022        limit: usize,
2023    ) -> Result<Frame, RouterError> {
2024        // Sent before the request reaches `handle_route_open`, so the caller
2025        // fields come from the raw frame here.
2026        let caller = self.route_open_caller_from_frame(ctx, frame);
2027        self.route_open_admission_refusal_frame(
2028            ctx,
2029            &caller,
2030            frame,
2031            target_module_id,
2032            "open_admission_full",
2033            (in_flight, limit),
2034            format!(
2035                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
2036            ),
2037        )
2038    }
2039
2040    fn route_open_target_capacity_refusal(
2041        &self,
2042        ctx: &RouteCtx,
2043        caller: &RouteOpenCaller,
2044        frame: &Frame,
2045        target_module_id: &str,
2046        in_flight: usize,
2047    ) -> Result<Frame, RouterError> {
2048        self.route_open_admission_refusal_frame(
2049            ctx,
2050            caller,
2051            frame,
2052            target_module_id,
2053            "target_binds_full",
2054            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
2055            format!(
2056                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
2057            ),
2058        )
2059    }
2060
2061    /// Admission pressure clears as existing binds settle, so its refusal must
2062    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
2063    /// `module_reloading`, `module_warming`, `target_unavailable`, or
2064    /// `module_timeout`. `target_unavailable` is honest for an attempt that
2065    /// cannot currently reach its target; `module_timeout` would falsely claim
2066    /// that a wait expired. A new, cleaner code would be terminal to deployed
2067    /// clients, so it requires a client-tolerance rollout before daemon emission.
2068    #[allow(clippy::too_many_arguments)]
2069    fn route_open_admission_refusal_frame(
2070        &self,
2071        ctx: &RouteCtx,
2072        caller: &RouteOpenCaller,
2073        frame: &Frame,
2074        target_module_id: &str,
2075        reason: &'static str,
2076        (in_flight, limit): (usize, usize),
2077        message: impl Into<String>,
2078    ) -> Result<Frame, RouterError> {
2079        let code = error_codes::TARGET_UNAVAILABLE;
2080        self.counters.increment_route_open_refused(code);
2081        info!(
2082            target: "control",
2083            code,
2084            reason,
2085            module_id = ?target_module_id,
2086            connection_id = ctx.connection_id.get(),
2087            principal = %caller.principal,
2088            scope = %caller.scope,
2089            harness = %caller.harness,
2090            in_flight,
2091            limit,
2092            "route.open refused"
2093        );
2094        control_error_frame(frame, code, message.into())
2095    }
2096
2097    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
2098    ///
2099    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
2100    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
2101    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
2102    #[cfg(test)]
2103    pub fn handle_control(
2104        &self,
2105        connection_id: ConnectionId,
2106        frame: Frame,
2107    ) -> Result<Vec<Frame>, RouterError> {
2108        match frame.header.ty {
2109            FrameType::Ping => Ok(vec![pong(&frame)?]),
2110            FrameType::Hello => self.handle_hello(connection_id, None, frame),
2111            FrameType::Goodbye => self.handle_goodbye(connection_id),
2112            ty => Ok(vec![control_error_frame(
2113                &frame,
2114                "unsupported_control_frame",
2115                format!("unsupported channel-0 frame {ty:?}"),
2116            )?]),
2117        }
2118    }
2119
2120    pub async fn handle_control_frame(
2121        &self,
2122        ctx: &RouteCtx,
2123        frame: Frame,
2124    ) -> Result<Vec<Frame>, RouterError> {
2125        self.handle_control_frame_timed(ctx, frame, None).await
2126    }
2127
2128    #[cfg(any(test, feature = "test-support"))]
2129    pub fn with_test_operator_app_policy(
2130        mut self,
2131        policy: crate::operator_apps::TestOperatorAppPolicy,
2132    ) -> Self {
2133        self.operator_app_policy = policy.into();
2134        self
2135    }
2136
2137    /// Inject the Windows signature check for tests. The injected check
2138    /// answers the verified version string or the rejection reason; the
2139    /// daemon enforces the floor itself on the returned version.
2140    #[cfg(all(windows, any(test, feature = "test-support")))]
2141    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
2142        self.windows_verify = Some(verify);
2143        self
2144    }
2145
2146    /// Record which pids the daemon would flash for `already_running`.
2147    #[cfg(all(windows, any(test, feature = "test-support")))]
2148    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
2149        self.windows_flash = Some(flash);
2150        self
2151    }
2152
2153    /// Inject a tracking failure for tests: makes `track_launched_process`
2154    /// fail so a test can prove a launch that cannot be tracked is stopped,
2155    /// never left running.
2156    #[cfg(all(windows, any(test, feature = "test-support")))]
2157    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2158        self.windows_track = Some(track);
2159        self
2160    }
2161
2162    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2163        self.local_connections
2164            .lock()
2165            .unwrap_or_else(|p| p.into_inner())
2166            .insert(connection);
2167    }
2168
2169    // Keep the connection-level delivery decision shared with route.bind. The
2170    // target's capability opt-in is separate from recognition of the caller.
2171    fn connection_operator_app(
2172        &self,
2173        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2174    ) -> Option<subc_protocol::peer::OperatorApp> {
2175        stamp
2176            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2177            .map(|stamp| stamp.app.clone())
2178    }
2179
2180    pub(crate) fn record_observed_peer(
2181        &self,
2182        connection: ConnectionId,
2183        peer: subc_os::local_peer::ObservedPeer,
2184    ) {
2185        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2186        let peer = match peer {
2187            OsPeer::Unobserved => ObservedPeer::unobserved(),
2188            OsPeer::Observed(peer) => {
2189                let observed = match peer.user {
2190                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2191                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2192                };
2193                observed
2194                    .with_exe(
2195                        peer.exe
2196                            .and_then(|path| path.into_os_string().into_string().ok()),
2197                    )
2198                    .with_signing_id(peer.signing_id)
2199            }
2200        };
2201        self.observed_peers
2202            .lock()
2203            .unwrap_or_else(|p| p.into_inner())
2204            .insert(connection, peer);
2205    }
2206
2207    pub(crate) fn record_caller_endpoints(
2208        &self,
2209        connection: ConnectionId,
2210        endpoints: Option<(SocketAddr, SocketAddr)>,
2211    ) {
2212        let mut callers = self
2213            .caller_endpoints
2214            .lock()
2215            .unwrap_or_else(|p| p.into_inner());
2216        callers.remove(&connection);
2217        if let Some(endpoints) = endpoints {
2218            callers.insert(connection, endpoints);
2219        }
2220    }
2221
2222    #[cfg(test)]
2223    pub(crate) fn with_caller_lookup_for_test(
2224        mut self,
2225        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2226    ) -> Self {
2227        self.caller_lookup = Some(Arc::new(lookup));
2228        self
2229    }
2230
2231    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2232        let endpoints = self
2233            .caller_endpoints
2234            .lock()
2235            .unwrap_or_else(|p| p.into_inner())
2236            .get(&connection)
2237            .copied();
2238        #[cfg(test)]
2239        let lookup = self.caller_lookup.clone();
2240        tokio::task::spawn_blocking(move || {
2241            #[cfg(test)]
2242            if let Some(lookup) = lookup {
2243                return lookup(endpoints);
2244            }
2245            endpoints
2246                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2247                .unwrap_or_default()
2248        })
2249        .await
2250        .unwrap_or_default()
2251    }
2252
2253    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2254        frame.header.channel == 0
2255            && frame.header.ty == FrameType::Request
2256            && self
2257                .forwarding
2258                .module_endpoint_for_connection(ctx.connection_id)
2259                .is_ok_and(|endpoint| endpoint.is_none())
2260            && parse_client_control_request(&frame.body)
2261                .ok()
2262                .is_some_and(|request| privileged_operation(&request).is_some())
2263    }
2264
2265    pub(crate) async fn handle_control_frame_timed(
2266        &self,
2267        ctx: &RouteCtx,
2268        frame: Frame,
2269        dispatch_started_at: Option<StdInstant>,
2270    ) -> Result<Vec<Frame>, RouterError> {
2271        let first = ctx.egress.first_ingress_frame();
2272        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2273            .await
2274    }
2275
2276    pub(crate) async fn handle_control_frame_ingress(
2277        &self,
2278        ctx: &RouteCtx,
2279        frame: Frame,
2280        dispatch_started_at: Option<StdInstant>,
2281        first: bool,
2282    ) -> Result<Vec<Frame>, RouterError> {
2283        if ctx.egress.ingress_terminal() {
2284            return Ok(Vec::new());
2285        }
2286        #[cfg(test)]
2287        self.claims.record_dispatch(frame.header.corr);
2288        let claim_binding = self.claims.binding(ctx.connection_id);
2289        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2290            && claim_binding
2291                .as_ref()
2292                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2293        .then(|| self.prefix_hello_attempt(ctx));
2294        if claim_binding
2295            .as_ref()
2296            .is_some_and(|binding| binding.prefix_module_id().is_some())
2297        {
2298            let registered = self
2299                .forwarding
2300                .module_endpoint_for_connection(ctx.connection_id)
2301                .map_err(RouterError::Forwarding)?
2302                .is_some();
2303            if !registered && frame.header.ty != FrameType::Hello {
2304                return self
2305                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2306                    .await;
2307            }
2308            if registered && frame.header.ty == FrameType::Goodbye {
2309                ctx.egress.terminate_ingress();
2310                let result = self.handle_goodbye(ctx.connection_id);
2311                self.claims.connection_closed(ctx.connection_id);
2312                self.request_refusal_close(
2313                    ctx.connection_id,
2314                    Some(&ctx.egress),
2315                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2316                );
2317                return result;
2318            }
2319            if registered && frame.header.ty == FrameType::Request {
2320                let allowed =
2321                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2322                        matches!(
2323                            probe.op.as_str(),
2324                            "catalog.update"
2325                                | "catalog.update_role_declarations"
2326                                | "scope.describe"
2327                                | "scope.watch"
2328                                | "supervisor.live_roots"
2329                                | "activity.record"
2330                        )
2331                    });
2332                if !allowed {
2333                    return Ok(vec![control_error_frame(
2334                        &frame,
2335                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2336                        "prefix registrations have only brokered module operations",
2337                    )?]);
2338                }
2339            }
2340            if registered
2341                && frame.header.ty == FrameType::Push
2342                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2343                    .is_ok_and(|probe| probe.op == "route.status")
2344            {
2345                return Ok(vec![control_error_frame(
2346                    &frame,
2347                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2348                    "prefix registrations may push only route.status for routes they serve",
2349                )?]);
2350            }
2351        }
2352        match frame.header.ty {
2353            FrameType::Ping => Ok(vec![pong(&frame)?]),
2354            FrameType::Hello => {
2355                if claim_binding
2356                    .as_ref()
2357                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2358                {
2359                    return self
2360                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2361                        .await;
2362                }
2363                // Resolved once, here: the blocking HELLO below may outlive this
2364                // reader and run after cleanup has forgotten the channel, and it
2365                // must still be judged as this channel's HELLO.
2366                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2367                if let Some(spawn) = &channel_spawn {
2368                    spawn.wait_launch().await;
2369                    // Refused launches close the channel. Leave their pending
2370                    // HELLO unanswered instead of racing a reply against shutdown.
2371                    if !spawn.launch_ready() {
2372                        ctx.egress.terminate_ingress();
2373                        return Ok(Vec::new());
2374                    }
2375                    #[cfg(test)]
2376                    self.pause_hello_ingress_for_test().await;
2377                } else if claim_binding.is_none() {
2378                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2379                        if let (Some(module), Some(nonce)) = (
2380                            hello
2381                                .get("manifest")
2382                                .and_then(|value| value.get("module_id"))
2383                                .and_then(|value| value.as_str()),
2384                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2385                        ) {
2386                            if !self
2387                                .config_runtime
2388                                .as_ref()
2389                                .is_some_and(|owner| owner.module_is_gated(module))
2390                                && !self.supervisor.wait_program_binding(module, nonce).await
2391                            {
2392                                self.request_refusal_close(
2393                                    ctx.connection_id,
2394                                    Some(&ctx.egress),
2395                                    CloseReason::new(
2396                                        "program_refused",
2397                                        "the spawned program binding failed",
2398                                    ),
2399                                );
2400                                return Ok(vec![control_error_frame(
2401                                    &frame,
2402                                    if self
2403                                        .config_runtime
2404                                        .as_ref()
2405                                        .is_some_and(|owner| owner.is_recovering())
2406                                    {
2407                                        "config_gated"
2408                                    } else {
2409                                        "program_refused"
2410                                    },
2411                                    "the spawned program binding failed",
2412                                )?]);
2413                            }
2414                        }
2415                    }
2416                }
2417                let handler = self.clone();
2418                let connection = ctx.connection_id;
2419                let egress = ctx.egress.clone();
2420                let correlation = frame.header.corr;
2421                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2422                let span = tracing::Span::current();
2423                let hello_binding = claim_binding.clone();
2424                let replies = tokio::task::spawn_blocking(move || {
2425                    tracing::dispatcher::with_default(&dispatcher, || {
2426                        span.in_scope(|| {
2427                            handler.handle_hello_checked(
2428                                connection,
2429                                Some(egress),
2430                                frame,
2431                                true,
2432                                hello_binding,
2433                                channel_spawn,
2434                            )
2435                        })
2436                    })
2437                })
2438                .await
2439                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2440                #[cfg(test)]
2441                if prefix_attempt.is_some() {
2442                    self.claims.pause_prefix_commit_for_test(false).await;
2443                }
2444                if let Some(attempt) = &mut prefix_attempt {
2445                    let accepted = !replies
2446                        .iter()
2447                        .any(|reply| reply.header.ty == FrameType::Error)
2448                        && self
2449                            .registry
2450                            .get_module_by_connection(ctx.connection_id)
2451                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2452                            .is_some();
2453                    if accepted {
2454                        attempt.accepted = true;
2455                    } else {
2456                        ctx.egress.terminate_ingress();
2457                        for reply in replies {
2458                            ctx.egress.send_flushed(reply).await?;
2459                        }
2460                        return Ok(Vec::new());
2461                    }
2462                }
2463                Ok(replies)
2464            }
2465            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2466            FrameType::Cancel => {
2467                // Channel-0 cancellation withdraws approvals and subscriptions
2468                // and fences pending agent declarations;
2469                // successful cancellation has no ordinary reply.
2470                // A config Apply may also own an OS prompt. Cancel that prompt
2471                // before config cancellation can report the request handled.
2472                if self
2473                    .agent_declarations
2474                    .cancel(ctx.connection_id, frame.header.corr)
2475                    || self
2476                        .forwarding
2477                        .operator_confirms()
2478                        .cancel(ctx.connection_id, frame.header.corr)
2479                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2480                    || self
2481                        .supervisor
2482                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2483                    || self.cancel_activity_subscription(ctx, &frame)?
2484                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2485                    || self
2486                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2487                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2488                {
2489                    Ok(Vec::new())
2490                } else {
2491                    Ok(vec![control_error_frame(
2492                        &frame,
2493                        "unknown_subscription",
2494                        "no subscription has this correlation id",
2495                    )?])
2496                }
2497            }
2498            FrameType::Request => {
2499                // This additive operation is not part of the existing exhaustive
2500                // module-control enum. Probe the op before decoding that enum.
2501                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2502                if let Some(probe) = &op {
2503                    self.record_control_usage(ctx.connection_id, &probe.op);
2504                }
2505                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2506                if let Some(refusal) = self
2507                    .recovery_request_refusal(
2508                        ctx,
2509                        &frame,
2510                        op.as_ref().map(|probe| probe.op.as_str()),
2511                    )
2512                    .await?
2513                {
2514                    if claim_present {
2515                        self.reclaim_presented_expiry(&frame);
2516                        return self
2517                            .refuse_claim_connection(ctx, &frame, "config_gated")
2518                            .await;
2519                    }
2520                    return Ok(vec![refusal]);
2521                }
2522                if claim_present {
2523                    return self.handle_claim_present(ctx, &frame, first).await;
2524                }
2525                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2526                    return self.handle_claim_mint(ctx, &frame).await;
2527                }
2528                if let Some(refusal) = self.registration_operation_refusal(
2529                    ctx,
2530                    &frame,
2531                    op.as_ref().map(|probe| probe.op.as_str()),
2532                )? {
2533                    return Ok(vec![refusal]);
2534                }
2535                if op
2536                    .as_ref()
2537                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2538                {
2539                    return self.handle_catalog_watch(ctx, frame);
2540                }
2541                if op
2542                    .as_ref()
2543                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2544                {
2545                    return self.handle_scope_watch(ctx, frame);
2546                }
2547                if op
2548                    .as_ref()
2549                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2550                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2551                        .unwrap_or(false)
2552                {
2553                    return Ok(vec![control_error_frame(
2554                        &frame,
2555                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2556                        "provider_declarations are fixed at HELLO; restart the module to change them",
2557                    )?]);
2558                }
2559                if let Some(probe) = op
2560                    .as_ref()
2561                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2562                {
2563                    return self
2564                        .handle_module_config_request(ctx, frame, &probe.op)
2565                        .await;
2566                }
2567                if op
2568                    .as_ref()
2569                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2570                {
2571                    return self.handle_config_gate_request(ctx, frame).await;
2572                }
2573                if op
2574                    .as_ref()
2575                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2576                {
2577                    return self.handle_activity_record(ctx, frame).await;
2578                }
2579                if op.as_ref().is_some_and(|probe| {
2580                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2581                }) {
2582                    return self.handle_activity_read(ctx, frame).await;
2583                }
2584                if op
2585                    .as_ref()
2586                    .is_some_and(|probe| probe.op == "operator.confirm")
2587                {
2588                    return self.handle_operator_confirm(ctx, frame).await;
2589                }
2590                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2591                    return self
2592                        .observe_control_wait(
2593                            ctx,
2594                            None,
2595                            ops::APP_OPEN,
2596                            self.handle_app_open(ctx, frame),
2597                        )
2598                        .await;
2599                }
2600                if op
2601                    .as_ref()
2602                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2603                {
2604                    return self.handle_connection_describe(ctx, frame).await;
2605                }
2606                if op
2607                    .as_ref()
2608                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2609                {
2610                    return self.handle_scope_served_by(ctx.connection_id, frame);
2611                }
2612                if self
2613                    .forwarding
2614                    .module_endpoint_for_connection(ctx.connection_id)
2615                    .map_err(RouterError::Forwarding)?
2616                    .is_some()
2617                {
2618                    if !is_known_module_request_op(&frame.body) {
2619                        return Ok(vec![control_error_frame(
2620                            &frame,
2621                            "unsupported_control_frame",
2622                            "module-originated channel-0 REQUEST is not supported",
2623                        )?]);
2624                    }
2625                    let request = match parse_module_control_request_from_module(&frame.body) {
2626                        Ok(request) => request,
2627                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2628                            return Ok(vec![control_error_frame(
2629                                &frame,
2630                                "unsupported_control_frame",
2631                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2632                            )?])
2633                        }
2634                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2635                            return Ok(vec![control_error_frame(
2636                                &frame,
2637                                "invalid_control_body",
2638                                format!("malformed module control body: {err}"),
2639                            )?])
2640                        }
2641                    };
2642                    let op = module_control_request_op(&request);
2643                    let corr = frame.header.corr;
2644                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2645                    if let ModuleControlRequestFromModule::AgentCommands {
2646                        started,
2647                        finished,
2648                        known,
2649                    } = request
2650                    {
2651                        return self
2652                            .agent_declarations
2653                            .enqueue(
2654                                self,
2655                                ctx,
2656                                frame,
2657                                crate::resource_totals::Declaration {
2658                                    started,
2659                                    finished,
2660                                    known,
2661                                },
2662                            )
2663                            .await;
2664                    }
2665                    let result =
2666                        self.handle_module_control_request(ctx.connection_id, frame, request);
2667                    log_slow_control_dispatch(
2668                        dispatch_started_at,
2669                        op,
2670                        ctx.connection_id,
2671                        corr,
2672                        None,
2673                    );
2674                    return result;
2675                }
2676
2677                if is_known_module_request_op(&frame.body) {
2678                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2679                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2680                    let code = if is_agents {
2681                        "not_supervised"
2682                    } else if op
2683                        .as_ref()
2684                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2685                    {
2686                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2687                    } else {
2688                        "not_registered"
2689                    };
2690                    return Ok(vec![control_error_frame(
2691                        &frame,
2692                        code,
2693                        "module-originated control requests require the module's own registered connection",
2694                    )?]);
2695                }
2696
2697                let request = match parse_client_control_request(&frame.body) {
2698                    Ok(request) => request,
2699                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2700                        return Ok(vec![control_error_frame(
2701                            &frame,
2702                            "unknown_control_op",
2703                            format!("unknown client control op: {err}"),
2704                        )?])
2705                    }
2706                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2707                        return Ok(vec![control_error_frame(
2708                            &frame,
2709                            "invalid_control_body",
2710                            format!("malformed client control body: {err}"),
2711                        )?])
2712                    }
2713                };
2714                let op = client_control_request_op(&request);
2715                let corr = frame.header.corr;
2716                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2717                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2718                #[cfg(test)]
2719                if let Some(delay) = self.control_dispatch_delay {
2720                    tokio::time::sleep(delay).await;
2721                }
2722                let result = self
2723                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2724                    .await;
2725                if let Some(timings) = route_open_timings.as_mut() {
2726                    timings.finish();
2727                }
2728                log_slow_control_dispatch(
2729                    dispatch_started_at,
2730                    op,
2731                    ctx.connection_id,
2732                    corr,
2733                    route_open_timings.as_ref(),
2734                );
2735                result
2736            }
2737            FrameType::Push => {
2738                let Some(endpoint) = self
2739                    .forwarding
2740                    .module_endpoint_for_connection(ctx.connection_id)
2741                    .map_err(RouterError::Forwarding)?
2742                else {
2743                    return Ok(vec![control_error_frame(
2744                        &frame,
2745                        "unsupported_control_frame",
2746                        "client-originated channel-0 PUSH is not supported",
2747                    )?]);
2748                };
2749                self.handle_status_update(endpoint, frame)
2750            }
2751            FrameType::Response | FrameType::Error
2752                if self
2753                    .forwarding
2754                    .module_endpoint_for_connection(ctx.connection_id)
2755                    .map_err(RouterError::Forwarding)?
2756                    .is_some() =>
2757            {
2758                self.handle_module_relay_response(ctx.connection_id, frame)
2759            }
2760            ty => Ok(vec![control_error_frame(
2761                &frame,
2762                "unsupported_control_frame",
2763                format!("unsupported channel-0 frame {ty:?}"),
2764            )?]),
2765        }
2766    }
2767
2768    #[cfg(test)]
2769    fn pause_cleanup_for_test(&self, stage: u8) {
2770        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2771        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2772            let (_, (reached, release)) = slot.take().unwrap();
2773            drop(slot);
2774            let _ = reached.send(());
2775            let _ = release.recv_timeout(Duration::from_secs(5));
2776        }
2777    }
2778
2779    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2780    /// right after the nonce is resolved.
2781    #[cfg(all(test, unix, feature = "test-support"))]
2782    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2783        *self
2784            .after_nonce_attestation
2785            .lock()
2786            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2787    }
2788
2789    #[cfg(test)]
2790    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2791        let hook = self
2792            .after_nonce_attestation
2793            .lock()
2794            .unwrap_or_else(|p| p.into_inner())
2795            .take();
2796        if let Some(hook) = hook {
2797            hook();
2798        }
2799    }
2800
2801    #[cfg(test)]
2802    async fn pause_hello_ingress_for_test(&self) {
2803        let pause = self
2804            .hello_ingress_pause
2805            .lock()
2806            .unwrap_or_else(|p| p.into_inner())
2807            .take();
2808        if let Some((reached, release)) = pause {
2809            let _ = reached.send(());
2810            let _ = release.await;
2811        }
2812    }
2813
2814    pub fn cleanup_connection(
2815        &self,
2816        connection_id: ConnectionId,
2817    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2818        // The server loop joins its offloaded request tasks (route opens,
2819        // privileged requests and activity reads) before this cleanup runs, and
2820        // inline dispatch has ended. Two kinds of work are not joined. Agent
2821        // command declarations run on their queue's detached worker, so the
2822        // queue is closed first: every declaration still queued or validating
2823        // has its commit fence cancelled before anything below can change how
2824        // the connection resolves. A HELLO whose reader was dropped keeps
2825        // running on its blocking thread. It carries the channel spawn its
2826        // reader resolved at ingress instead of re-reading the index forgotten
2827        // below, so it is still judged as that channel's HELLO: the retired
2828        // spawn refuses it before it records anything, and a channel HELLO
2829        // never records a launch nonce, so it cannot leave this connection any
2830        // nonce authority.
2831        self.agent_declarations.close(connection_id);
2832        self.close_catalog_subscriptions(connection_id);
2833        self.close_config_settings_subscriptions(connection_id);
2834        self.close_scope_subscriptions(connection_id);
2835        #[cfg(test)]
2836        self.pause_cleanup_for_test(0);
2837        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2838            spawn.retire_registration_channel();
2839        }
2840        self.supervisor
2841            .forget_registration_connection(connection_id);
2842        #[cfg(test)]
2843        self.pause_cleanup_for_test(1);
2844        self.local_connections
2845            .lock()
2846            .unwrap_or_else(|p| p.into_inner())
2847            .remove(&connection_id);
2848        self.caller_endpoints
2849            .lock()
2850            .unwrap_or_else(|p| p.into_inner())
2851            .remove(&connection_id);
2852        self.build_class_warned
2853            .lock()
2854            .unwrap_or_else(|p| p.into_inner())
2855            .remove(&connection_id);
2856        // Retire the capture before its published facts so an in-flight
2857        // verification cannot recreate them after cleanup.
2858        self.captured_peers
2859            .lock()
2860            .unwrap_or_else(|p| p.into_inner())
2861            .remove(&connection_id);
2862        self.observed_peers
2863            .lock()
2864            .unwrap_or_else(|p| p.into_inner())
2865            .remove(&connection_id);
2866        self.config_desktop_stamps
2867            .lock()
2868            .unwrap_or_else(|p| p.into_inner())
2869            .remove(&connection_id);
2870        self.operator_apps
2871            .lock()
2872            .unwrap_or_else(|p| p.into_inner())
2873            .remove(&connection_id);
2874        self.forwarding
2875            .operator_confirms()
2876            .connection_closed(connection_id);
2877        let cleanup = self.cleanup_connection_with_end_reason(
2878            connection_id,
2879            RegistrationEndReason::ConnectionClosed,
2880        );
2881        // A draining writer can still be reached by a route until forwarding
2882        // cleanup finishes. Keep its claim sink visible to launch retirement.
2883        self.claims.connection_closed(connection_id);
2884        cleanup
2885    }
2886
2887    fn cleanup_connection_with_end_reason(
2888        &self,
2889        connection_id: ConnectionId,
2890        requested_reason: RegistrationEndReason,
2891    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2892        #[cfg(test)]
2893        if let Some(pause) = self
2894            .activity_request_pause
2895            .lock()
2896            .unwrap()
2897            .as_ref()
2898            .filter(|pause| pause.connection == connection_id)
2899        {
2900            pause
2901                .cleanup_started
2902                .store(true, std::sync::atomic::Ordering::Release);
2903        }
2904        if let Some(runtime) = &self.config_runtime {
2905            runtime.disconnected(connection_id);
2906        }
2907        self.agent_declarations.close(connection_id);
2908        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2909            self.registry
2910                .get_module_by_connection(connection_id)?
2911                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2912                .and_then(|module| module.registration_end_reason().ok().flatten())
2913                .unwrap_or(requested_reason)
2914        } else {
2915            requested_reason
2916        };
2917        let crash_closed = self
2918            .registry
2919            .get_module_by_connection(connection_id)?
2920            .and_then(|registration| {
2921                self.forwarding
2922                    .module_endpoint_for_connection(connection_id)
2923                    .ok()
2924                    .flatten()
2925                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2926                    .map(|routes| (registration.manifest.module_id, routes))
2927            });
2928        let crash_closed = crash_closed.map(|(module_id, routes)| {
2929            let terminal = match self.supervisor.get(&module_id) {
2930                None => false,
2931                Some(module) => match module.will_recover_after_connection_loss() {
2932                    Ok(will_recover) => !will_recover,
2933                    Err(err) => {
2934                        warn!(
2935                            %module_id,
2936                            error = %err,
2937                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2938                        );
2939                        false
2940                    }
2941                },
2942            };
2943            // The forwarding table gates all providers at the start of daemon
2944            // shutdown, before their connections are closed. An ordinary
2945            // module disconnect still reports crash if that gate is not set.
2946            let (reason, drained) = match self
2947                .forwarding
2948                .daemon_drain_result_for_connection(connection_id)
2949            {
2950                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
2951                Ok(None) => (RouteCloseReason::Crash, false),
2952                Err(err) => {
2953                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
2954                    (RouteCloseReason::Crash, false)
2955                }
2956            };
2957            (module_id, routes, reason, drained, terminal)
2958        });
2959        let registrations = self.deregister_connection(connection_id, end_reason);
2960        // Read before teardown: the spawn whose registration this connection
2961        // was. Its registration ending is an authority change for it.
2962        let ended_authority = self
2963            .forwarding
2964            .target_authority_for_connection(connection_id)
2965            .ok()
2966            .flatten();
2967        let cleanup = if crash_closed.is_some() {
2968            self.forwarding.cleanup_connection_counted(connection_id)
2969        } else {
2970            // A module connection's teardown needs the count of abandoned
2971            // route.bind relays for its route.closed notice below. Any other
2972            // connection, such as a client's, sends no such notice and needs
2973            // only its routes released, so it uses the route-only wrapper and
2974            // reports zero.
2975            self.forwarding
2976                .cleanup_connection(connection_id)
2977                .map(|released| crate::forwarding::ConnectionCleanup {
2978                    released,
2979                    abandoned_relays: 0,
2980                })
2981        };
2982        // The route.closed push waits for forwarding teardown because only
2983        // teardown knows how many pending route.bind relays it aborted. It still
2984        // goes out before the GOODBYEs for the released routes, and its targets
2985        // were captured above, before teardown removed those routes.
2986        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
2987            let abandoned = cleanup
2988                .as_ref()
2989                .map_or(0, |cleanup| cleanup.abandoned_relays);
2990            send_route_control_pushes(
2991                &self.forwarding,
2992                routes,
2993                ClientControlPush::RouteClosed {
2994                    module_id,
2995                    channels: Vec::new(),
2996                    reason,
2997                    drained,
2998                    abandoned,
2999                    excluded_subscriptions: 0,
3000                    terminal: Some(terminal),
3001                },
3002            );
3003        }
3004        if let Ok(cleanup) = cleanup {
3005            self.emit_route_goodbyes(cleanup.released);
3006        }
3007        if let Some(record) = ended_authority {
3008            self.change_spawn_authority(&record);
3009        }
3010        // Signal the registration-release watch only now that BOTH registry and
3011        // forwarding teardown are done, so a supervisor waiting to spawn a
3012        // replacement never observes release while old routes still exist.
3013        if matches!(&registrations, Ok(r) if !r.is_empty()) {
3014            crate::supervise::notify_registration_release();
3015            self.capability_evaluator.wake_deadline_loop();
3016            self.refresh_capability_requirements();
3017        }
3018        self.supervisor.remove_spawn_subscribers(connection_id);
3019        self.activity_streams
3020            .lock()
3021            .unwrap_or_else(|p| p.into_inner())
3022            .retain(|(id, _), task| {
3023                if *id == connection_id {
3024                    task.abort();
3025                    false
3026                } else {
3027                    true
3028                }
3029            });
3030        // Sync authority dies with its connection, so the owner's next
3031        // connection can take it; the owner's scopes stay as they are.
3032        self.hello_launch_nonces
3033            .lock()
3034            .unwrap_or_else(|poisoned| poisoned.into_inner())
3035            .forget(connection_id);
3036        self.scopes
3037            .write()
3038            .unwrap_or_else(|poisoned| poisoned.into_inner())
3039            .release_connection(connection_id);
3040        registrations
3041    }
3042
3043    pub(crate) fn handle_route_goodbye(
3044        &self,
3045        connection_id: ConnectionId,
3046        route_channel: u16,
3047        route_epoch: u32,
3048    ) -> Result<bool, RouterError> {
3049        debug!(
3050            connection_id = connection_id.get(),
3051            route_channel, route_epoch, "handling route GOODBYE"
3052        );
3053        let RouteRelease::Removed(released_route) = self
3054            .forwarding
3055            .release_client_route(connection_id, route_channel, route_epoch)
3056            .map_err(RouterError::Forwarding)?
3057        else {
3058            return Ok(false);
3059        };
3060        self.emit_route_goodbyes(vec![released_route]);
3061        Ok(true)
3062    }
3063
3064    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
3065        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
3066    }
3067
3068    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
3069    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
3070    /// own commit failed after the module had already accepted). Without this, a
3071    /// module that accepts late keeps a binding subc has torn down, so a later
3072    /// frame on that module channel could misdeliver if the channel is reused.
3073    ///
3074    /// Never closes the shared module connection on failure: a dropped notification
3075    /// only wastes a bounded amount of warm module-side state, which the module's
3076    /// own idle reaper reclaims. Only call this once the route.bind relay was
3077    /// actually enqueued to the module — if the relay send itself failed, the
3078    /// module never created a binding and there is nothing to tear down.
3079    fn send_abandoned_route_bind_goodbye(
3080        &self,
3081        module_sink: &crate::FrameSink,
3082        negotiated_ver: u8,
3083        module_channel: u16,
3084        module_epoch: u32,
3085    ) {
3086        let frame = match Frame::build_with_version(
3087            negotiated_ver,
3088            FrameType::Goodbye,
3089            control_flags(),
3090            module_channel,
3091            module_epoch,
3092            0,
3093            Vec::new(),
3094        ) {
3095            Ok(frame) => frame,
3096            Err(err) => {
3097                warn!(
3098                    route_channel = module_channel,
3099                    error = %err,
3100                    "failed to build GOODBYE for abandoned route.bind"
3101                );
3102                return;
3103            }
3104        };
3105        crate::forwarding::send_module_route_goodbye(
3106            &self.counters,
3107            module_sink,
3108            frame,
3109            None,
3110            "abandoned route.bind",
3111        );
3112    }
3113
3114    #[cfg(test)]
3115    fn handle_hello(
3116        &self,
3117        connection_id: ConnectionId,
3118        egress: Option<crate::router::FrameSink>,
3119        frame: Frame,
3120    ) -> Result<Vec<Frame>, RouterError> {
3121        let binding = self.claims.binding(connection_id);
3122        let channel_spawn = self.supervisor.registration_spawn(connection_id);
3123        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
3124    }
3125
3126    fn handle_hello_checked(
3127        &self,
3128        connection_id: ConnectionId,
3129        sink: Option<crate::FrameSink>,
3130        frame: Frame,
3131        wait_for_gate: bool,
3132        prefix_binding: Option<claims::ClaimBinding>,
3133        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3134    ) -> Result<Vec<Frame>, RouterError> {
3135        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
3136        #[cfg(test)]
3137        if prefix_binding.is_some() {
3138            self.claims.pause_prefix_hello_for_test(5);
3139            match self.claims.take_prefix_hello_failure_for_test() {
3140                Some("error") => {
3141                    return Err(RouterError::backend(
3142                        0,
3143                        frame.header.corr,
3144                        "injected HELLO failure",
3145                    ))
3146                }
3147                Some("panic") => panic!("injected HELLO task panic"),
3148                _ => {}
3149            }
3150        }
3151        if let Some(binding) = &prefix_binding {
3152            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3153            let module = value
3154                .as_ref()
3155                .and_then(|value| value["manifest"]["module_id"].as_str());
3156            if !binding.admit_prefix_hello(module)
3157                || !self.prefix_binding_live(binding, connection_id)
3158                || !module.is_some_and(|module| {
3159                    self.supervisor
3160                        .prefix_claim_authorized(&binding.registration.module_id, module)
3161                })
3162                || binding.registration.check().is_err()
3163            {
3164                return Ok(vec![control_error_frame(
3165                    &frame,
3166                    "claim_prefix_refused",
3167                    "HELLO must name the prefix claim's exact module id once",
3168                )?]);
3169            }
3170        }
3171        struct RefuseUnregisteredChannel {
3172            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3173            sink: Option<crate::FrameSink>,
3174        }
3175        impl Drop for RefuseUnregisteredChannel {
3176            fn drop(&mut self) {
3177                if let Some(spawn) = &self.spawn {
3178                    if !spawn.registered() {
3179                        if let Some(sink) = &self.sink {
3180                            sink.terminate_ingress();
3181                        }
3182                        spawn.retire_registration_channel();
3183                    }
3184                }
3185            }
3186        }
3187        let _channel_attempt = RefuseUnregisteredChannel {
3188            spawn: channel_spawn.clone(),
3189            sink: sink.clone(),
3190        };
3191        if let Some(spawn) = &channel_spawn {
3192            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3193            if let Err(code) = spawn.admit_hello(
3194                value
3195                    .as_ref()
3196                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3197            ) {
3198                return Ok(vec![control_error_frame(
3199                    &frame,
3200                    code,
3201                    "registration channel HELLO refused",
3202                )?]);
3203            }
3204        }
3205        debug!(
3206            connection_id = connection_id.get(),
3207            corr = frame.header.corr,
3208            "handling HELLO"
3209        );
3210        // A module connection has one identity for its entire lifetime. A second
3211        // registration would leave the old registry owner behind while replacing
3212        // its forwarding endpoint and launch nonce.
3213        if self
3214            .registry
3215            .get_module_by_connection(connection_id)
3216            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3217            .is_some()
3218        {
3219            return Ok(vec![control_error_frame(
3220                &frame,
3221                "invalid_hello",
3222                "connection is already registered as a module",
3223            )?]);
3224        }
3225        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3226            Ok(value) => value,
3227            Err(err) => {
3228                return Ok(vec![control_error_frame(
3229                    &frame,
3230                    "invalid_hello",
3231                    format!("malformed HELLO body: {err}"),
3232                )?])
3233            }
3234        };
3235        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3236            return Ok(vec![control_error_frame(
3237                &frame,
3238                error_codes::INVALID_PROVIDER_DECLARATIONS,
3239                detail,
3240            )?]);
3241        }
3242        if let Some(module) = hello_value
3243            .get("manifest")
3244            .and_then(|value| value.get("module_id"))
3245            .and_then(|value| value.as_str())
3246        {
3247            let recovering = self
3248                .config_runtime
3249                .as_ref()
3250                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3251            // Defence in depth: RuntimeOwner::module_is_gated in
3252            // config_gate/admission.rs already gates every id during recovery.
3253            // A registration channel still never uses the nonce fallback.
3254            if recovering
3255                && channel_spawn.as_ref().is_none_or(|spawn| {
3256                    !self.supervisor.has_live_verified_channel_binding(spawn)
3257                        || spawn.check().is_err()
3258                })
3259                && !(channel_spawn.is_none()
3260                    && hello_value
3261                        .get("launch_nonce")
3262                        .and_then(|value| value.as_str())
3263                        .is_some_and(|nonce| {
3264                            self.supervisor.spawned_consumer_authorized(module, nonce)
3265                                && self
3266                                    .supervisor
3267                                    .has_live_verified_program_binding(module, nonce)
3268                        }))
3269            {
3270                return Ok(vec![control_error_frame(
3271                    &frame,
3272                    "config_gated",
3273                    "recovery admits only previously bound supervised launches",
3274                )?]);
3275            }
3276            if self
3277                .config_runtime
3278                .as_ref()
3279                .is_some_and(|owner| owner.module_is_gated(module))
3280                && (channel_spawn
3281                    .as_ref()
3282                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3283                    || self.config_runtime.as_ref().is_some_and(|owner| {
3284                        !recovering && owner.check_module_hold(module).is_err()
3285                    }))
3286            {
3287                return Ok(vec![control_error_frame(
3288                    &frame,
3289                    "reserved_module",
3290                    "a gated identity belongs only to its supervised child",
3291                )?]);
3292            }
3293        }
3294        if channel_spawn.is_none() {
3295            if let (Some(module), Some(nonce)) = (
3296                hello_value
3297                    .get("manifest")
3298                    .and_then(|value| value.get("module_id"))
3299                    .and_then(|value| value.as_str()),
3300                hello_value
3301                    .get("launch_nonce")
3302                    .and_then(|value| value.as_str()),
3303            ) {
3304                let binding = self.supervisor.has_program_binding_record(module, nonce);
3305                let required = self
3306                    .config_runtime
3307                    .as_ref()
3308                    .is_some_and(|owner| owner.module_is_gated(module));
3309                if let Some(error) = (binding || required)
3310                    .then(|| {
3311                        self.supervisor
3312                            .check_current_program_binding(module, nonce)
3313                            .err()
3314                    })
3315                    .flatten()
3316                {
3317                    let code = if error.code == "program_refused" {
3318                        "program_refused"
3319                    } else {
3320                        "config_delivery_deferred"
3321                    };
3322                    self.request_refusal_close(
3323                        connection_id,
3324                        sink.as_ref(),
3325                        CloseReason::new(code, error.detail.clone()),
3326                    );
3327                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3328                }
3329            }
3330        }
3331        if let Err(err) = validate_hello_display_name(&hello_value) {
3332            return Ok(vec![control_error_frame(
3333                &frame,
3334                "invalid_manifest",
3335                err.to_string(),
3336            )?]);
3337        }
3338        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3339            return Ok(vec![control_error_frame(
3340                &frame,
3341                "invalid_capability_grammar",
3342                err.to_string(),
3343            )?]);
3344        }
3345        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3346            return Ok(vec![control_error_frame(
3347                &frame,
3348                "invalid_manifest",
3349                err.to_string(),
3350            )?]);
3351        }
3352        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3353            return Ok(vec![control_error_frame(
3354                &frame,
3355                "invalid_event_declaration",
3356                err.to_string(),
3357            )?]);
3358        }
3359        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3360            return Ok(vec![control_error_frame(
3361                &frame,
3362                "invalid_manifest",
3363                err.to_string(),
3364            )?]);
3365        }
3366        if let Some(provenance) = hello_value
3367            .get("manifest")
3368            .and_then(|manifest| manifest.get("provenance"))
3369        {
3370            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3371                return Ok(vec![control_error_frame(
3372                    &frame,
3373                    "invalid_manifest",
3374                    format!("malformed manifest provenance: {err}"),
3375                )?]);
3376            }
3377        }
3378        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3379            let module_id = hello_value["manifest"]["module_id"]
3380                .as_str()
3381                .unwrap_or("<unknown>");
3382            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3383        }
3384        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3385            let module_id = hello_value
3386                .get("manifest")
3387                .and_then(|m| m.get("module_id"))
3388                .and_then(serde_json::Value::as_str)
3389                .unwrap_or("unknown");
3390            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3391        }
3392        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3393            let module_id = hello_value["manifest"]["module_id"]
3394                .as_str()
3395                .unwrap_or("<unknown>");
3396            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3397        }
3398        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3399            let module_id = hello_value["manifest"]["module_id"]
3400                .as_str()
3401                .unwrap_or("<unknown>");
3402            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3403        }
3404        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3405            Ok(hello) => hello,
3406            Err(err) => {
3407                return Ok(vec![control_error_frame(
3408                    &frame,
3409                    "invalid_hello",
3410                    format!("malformed HELLO body: {err}"),
3411                )?])
3412            }
3413        };
3414
3415        if hello.protocol_ver != hello.manifest.protocol_ver {
3416            return Ok(vec![control_error_frame(
3417                &frame,
3418                "invalid_manifest",
3419                format!(
3420                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3421                    hello.protocol_ver, hello.manifest.protocol_ver
3422                ),
3423            )?]);
3424        }
3425
3426        if hello.manifest.module_id.trim().is_empty() {
3427            return Ok(vec![control_error_frame(
3428                &frame,
3429                "invalid_manifest",
3430                "manifest module_id must not be empty",
3431            )?]);
3432        }
3433
3434        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3435            Ok(negotiated_ver) => negotiated_ver,
3436            Err(message) => {
3437                return Ok(vec![control_error_frame(
3438                    &frame,
3439                    "version_unsupported",
3440                    message,
3441                )?])
3442            }
3443        };
3444
3445        // Registration and forwarding publication use the same module gate as
3446        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3447        // precede those transitions. A program-refusal hold blocks future
3448        // spawns, but does not take this gate or revoke a HELLO whose supervised
3449        // child's image has already passed the check.
3450        let _publication_gate = if let Some(owner) = &self.config_runtime {
3451            let gate = owner
3452                .module_gate(&hello.manifest.module_id)
3453                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3454            Some(if wait_for_gate {
3455                gate.blocking_lock_owned()
3456            } else {
3457                match gate.try_lock_owned() {
3458                    Ok(guard) => guard,
3459                    Err(_) => {
3460                        return Ok(vec![control_error_frame(
3461                            &frame,
3462                            "config_delivery_deferred",
3463                            "module admission is busy",
3464                        )?])
3465                    }
3466                }
3467            })
3468        } else {
3469            None
3470        };
3471        #[cfg(test)]
3472        if let Some(hold) = &self.hello_before_publication_hold {
3473            hold.wait();
3474            hold.wait();
3475        }
3476        let module = &hello.manifest.module_id;
3477        let required = self
3478            .config_runtime
3479            .as_ref()
3480            .is_some_and(|owner| owner.module_is_gated(module));
3481        let recovering = self
3482            .config_runtime
3483            .as_ref()
3484            .is_some_and(|owner| owner.is_recovering());
3485        // Both entry paths (handle_control -> handle_hello and
3486        // handle_control_frame_timed -> spawn_blocking) enter this same
3487        // handle_hello_checked function. Its fresh, fail-closed store check
3488        // precedes parsing and this publication-gate check; this cached read
3489        // also observes any recovery transition published during that work.
3490        // The nonce-connection-only fallback is defence in depth alongside
3491        // RuntimeOwner::module_is_gated's all-id recovery gate.
3492        if recovering
3493            && channel_spawn.as_ref().is_none_or(|spawn| {
3494                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3495            })
3496            && !(channel_spawn.is_none()
3497                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3498                    self.supervisor.spawned_consumer_authorized(module, nonce)
3499                        && self
3500                            .supervisor
3501                            .has_live_verified_program_binding(module, nonce)
3502                }))
3503        {
3504            return Ok(vec![control_error_frame(
3505                &frame,
3506                "config_gated",
3507                "recovery admits only previously bound supervised launches",
3508            )?]);
3509        }
3510        if required
3511            && (channel_spawn
3512                .as_ref()
3513                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3514                || self
3515                    .config_runtime
3516                    .as_ref()
3517                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3518        {
3519            return Ok(vec![control_error_frame(
3520                &frame,
3521                "reserved_module",
3522                "gated admission requires the current supervised child's registration channel and verified image binding",
3523            )?]);
3524        }
3525        if let Some(spawn) = &channel_spawn {
3526            if let Err(code) = spawn.check() {
3527                return Ok(vec![control_error_frame(
3528                    &frame,
3529                    code,
3530                    "registration launch is no longer live",
3531                )?]);
3532            }
3533        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3534            if required || self.supervisor.has_program_binding_record(module, nonce) {
3535                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3536                    let code = if error.code == "program_refused" {
3537                        "program_refused"
3538                    } else {
3539                        "config_delivery_deferred"
3540                    };
3541                    self.request_refusal_close(
3542                        connection_id,
3543                        sink.as_ref(),
3544                        CloseReason::new(code, error.detail.clone()),
3545                    );
3546                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3547                }
3548            }
3549        }
3550
3551        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3552        // swap is open for this id, the only HELLO admitted as a second process
3553        // is the one carrying the candidate's launch nonce (the swap token), and
3554        // it registers into the candidate slot rather than being refused as a
3555        // duplicate. Run after the reserved gate, a reserved module's candidate
3556        // would be refused `reserved_module` for presenting a nonce that gate
3557        // does not know. See `SupervisorHandle::swap_hello_admission`.
3558        let swap_admission = match &channel_spawn {
3559            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3560            Some(_) => SwapHelloAdmission::NotSwapping,
3561            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3562            None => self
3563                .supervisor
3564                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3565        };
3566        if swap_admission == SwapHelloAdmission::ProtocolNone {
3567            warn!(
3568                module_id = %hello.manifest.module_id,
3569                connection_id = connection_id.get(),
3570                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3571            );
3572            // The code stays `swap_token_invalid` for existing callers; only the
3573            // explanation names the actual reason.
3574            return Ok(vec![control_error_frame(
3575                &frame,
3576                "swap_token_invalid",
3577                format!(
3578                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3579                    hello.manifest.module_id
3580                ),
3581            )?]);
3582        }
3583        if swap_admission == SwapHelloAdmission::ChannelRequired {
3584            warn!(
3585                module_id = %hello.manifest.module_id,
3586                connection_id = connection_id.get(),
3587                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3588            );
3589            // The code stays `swap_token_invalid` for existing callers; only the
3590            // explanation names the actual reason.
3591            return Ok(vec![control_error_frame(
3592                &frame,
3593                "swap_token_invalid",
3594                format!(
3595                    "module_id '{}' is gated; it must register over its supervised registration channel",
3596                    hello.manifest.module_id
3597                ),
3598            )?]);
3599        }
3600        if swap_admission == SwapHelloAdmission::Refused {
3601            warn!(
3602                module_id = %hello.manifest.module_id,
3603                connection_id = connection_id.get(),
3604                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3605            );
3606            return Ok(vec![control_error_frame(
3607                &frame,
3608                "swap_token_invalid",
3609                format!(
3610                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3611                    hello.manifest.module_id
3612                ),
3613            )?]);
3614        }
3615        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3616
3617        // A swap candidate proves its identity with the candidate nonce above.
3618        // Other registrations receive this catalog fact only when reserved-module
3619        // policy required and accepted a nonce; unreserved registrations require
3620        // no nonce check.
3621        let verification = if swap_candidate && channel_spawn.is_none() {
3622            ReservedHelloVerification {
3623                nonce_verified: true,
3624                prefix_owner: None,
3625            }
3626        } else {
3627            let verification = if let Some(binding) = &prefix_binding {
3628                if !self.supervisor.prefix_claim_authorized(
3629                    &binding.registration.module_id,
3630                    &hello.manifest.module_id,
3631                ) {
3632                    return Ok(vec![control_error_frame(
3633                        &frame,
3634                        "claim_prefix_refused",
3635                        "prefix ownership changed",
3636                    )?]);
3637                }
3638                Ok(ReservedHelloVerification {
3639                    nonce_verified: true,
3640                    prefix_owner: Some(binding.registration.module_id.clone()),
3641                })
3642            } else if channel_spawn.is_some() {
3643                self.supervisor
3644                    .channel_hello_verification(&hello.manifest.module_id)
3645            } else {
3646                self.supervisor.reserved_hello_verification(
3647                    &hello.manifest.module_id,
3648                    hello.launch_nonce.as_deref(),
3649                )
3650            };
3651            match verification {
3652                Ok(verified) => verified,
3653                Err(rejection) => {
3654                    let message = match rejection {
3655                        ReservedHelloRejection::Exact { module_id } => format!(
3656                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3657                        ),
3658                        ReservedHelloRejection::Prefix {
3659                            prefix,
3660                            owner_module_id,
3661                        } => format!(
3662                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3663                            hello.manifest.module_id
3664                        ),
3665                    };
3666                    return Ok(vec![control_error_frame(
3667                        &frame,
3668                        "reserved_module",
3669                        message,
3670                    )?]);
3671                }
3672            }
3673        };
3674
3675        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3676            &hello.manifest.module_id,
3677            hello.manifest.capabilities.as_ref(),
3678        );
3679        if let Some(refusal) = reserved_capability_refusals.first() {
3680            let capability = refusal.capability.clone();
3681            let bound_module = refusal.claimants[0].clone();
3682            log_duplicate_claim_events(reserved_capability_refusals);
3683            return Ok(vec![control_error_frame(
3684                &frame,
3685                "reserved_capability",
3686                format!(
3687                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3688                    capability, bound_module, hello.manifest.module_id
3689                ),
3690            )?]);
3691        }
3692
3693        // A connection that already opened client routes must not also register as
3694        // a module: cleanup would then release only one side and leak the other.
3695        if self
3696            .forwarding
3697            .connection_has_client_routes(connection_id)
3698            .map_err(RouterError::Forwarding)?
3699        {
3700            return Ok(vec![control_error_frame(
3701                &frame,
3702                "invalid_hello",
3703                "connection has open client routes and cannot also register as a module",
3704            )?]);
3705        }
3706
3707        // Kept for scope sync authority, which goes only to the connection that
3708        // presented the module's current launch nonce. Recorded before the
3709        // registration is attempted: a connection whose registration then fails
3710        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3711        // A registration channel's authority is the channel itself, never a
3712        // nonce it also presented, and a prefix registration's is its claim:
3713        // neither records one, so neither can fall back to nonce authority.
3714        self.hello_launch_nonces
3715            .lock()
3716            .unwrap_or_else(|poisoned| poisoned.into_inner())
3717            .record(
3718                connection_id,
3719                if prefix_binding.is_some() || channel_spawn.is_some() {
3720                    None
3721                } else {
3722                    hello.launch_nonce.as_deref()
3723                },
3724            );
3725        let control_ops = effective_module_control_ops(hello.control_ops);
3726        let prefix_submodule = verification.prefix_owner.is_some();
3727        // Built before anything is registered so an encoding failure leaves no
3728        // registry or forwarding state behind.
3729        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3730        #[cfg(test)]
3731        struct PublicationFinished(Arc<std::sync::Barrier>);
3732        #[cfg(test)]
3733        impl Drop for PublicationFinished {
3734            fn drop(&mut self) {
3735                self.0.wait();
3736            }
3737        }
3738        #[cfg(test)]
3739        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3740            hold.wait();
3741            hold.wait();
3742            PublicationFinished(hold.clone())
3743        });
3744        let publication_spawn = channel_spawn
3745            .as_ref()
3746            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3747        #[cfg(test)]
3748        if prefix_binding.is_some() {
3749            self.claims.pause_prefix_hello_for_test(7);
3750        }
3751        let _registration_publication = match publication_spawn {
3752            Some(spawn) => Some(match spawn.begin_publication() {
3753                Ok(guard) => guard,
3754                Err(code) => {
3755                    return Ok(vec![control_error_frame(
3756                        &frame,
3757                        code,
3758                        "registration ended before HELLO publication",
3759                    )?])
3760                }
3761            }),
3762            None => None,
3763        };
3764        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3765            let live = self.claims.lock_prefix_binding(binding, connection_id);
3766            let ownership = self.supervisor.prefix_claim_publication(
3767                &binding.registration.module_id,
3768                &hello.manifest.module_id,
3769            );
3770            if live.is_none()
3771                || ownership.is_none()
3772                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3773                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3774            {
3775                return Ok(vec![control_error_frame(
3776                    &frame,
3777                    "claim_prefix_refused",
3778                    "prefix authority ended before publication",
3779                )?]);
3780            }
3781            (live, ownership)
3782        } else {
3783            (None, None)
3784        };
3785        if let Some(spawn) = publication_spawn {
3786            self.forwarding
3787                .bind_spawn(connection_id, spawn)
3788                .map_err(RouterError::Forwarding)?;
3789        }
3790        // The spawn whose own registration this HELLO is, for `target` on
3791        // the route.open reply: its channel, or the launch its nonce was
3792        // minted for. A prefix child's HELLO names no spawn of its own. It is
3793        // only looked up here. The connection is bound to it and its
3794        // requested declarations are frozen once the registry has accepted
3795        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3796        // duplicate, or for any other reason, leaves the spawn untouched: its
3797        // closing connection is then no registration of the spawn and ends
3798        // none of the spawn's routes.
3799        let hello_authority = match (&channel_spawn, &prefix_binding) {
3800            (Some(spawn), _) => Some(spawn.authority.clone()),
3801            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3802                self.supervisor
3803                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3804            }),
3805            (None, Some(_)) => None,
3806        }
3807        .map(|record| HelloAuthority {
3808            record,
3809            requested: hello
3810                .manifest
3811                .provider_declarations
3812                .clone()
3813                .unwrap_or_default(),
3814            froze: Default::default(),
3815        });
3816        #[cfg(test)]
3817        if prefix_binding.is_some() {
3818            self.claims.pause_prefix_hello_for_test(8);
3819        }
3820        if swap_candidate {
3821            let module_id = hello.manifest.module_id.clone();
3822            let mut differing_declarations = Default::default();
3823            let reply = self.register_swap_candidate(
3824                connection_id,
3825                sink,
3826                &frame,
3827                hello.manifest,
3828                negotiated_ver,
3829                control_ops,
3830                hello_ack,
3831                hello_authority.as_ref(),
3832                &mut differing_declarations,
3833                #[cfg(windows)]
3834                hello.launch_nonce.as_deref(),
3835            )?;
3836            if let Some(spawn) = &channel_spawn {
3837                if self
3838                    .registry
3839                    .get_module_by_connection(connection_id)
3840                    .ok()
3841                    .flatten()
3842                    .is_some()
3843                {
3844                    if let Some(sink) = primary_sink {
3845                        spawn.bind_primary_sink(sink);
3846                    }
3847                    spawn.hello_accepted();
3848                }
3849            } else if self
3850                .registry
3851                .get_module_by_connection(connection_id)
3852                .ok()
3853                .flatten()
3854                .is_some()
3855            {
3856                self.supervisor
3857                    .retire_unused_registration_channel(&module_id, true);
3858            }
3859            if self
3860                .registry
3861                .get_module_by_connection(connection_id)
3862                .ok()
3863                .flatten()
3864                .is_some()
3865            {
3866                self.file_development_widening(
3867                    hello_authority.map(|authority| authority.record),
3868                    differing_declarations,
3869                );
3870            }
3871            return Ok(reply);
3872        }
3873        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3874        // is refused, but `catalog.list` does not show the module and the
3875        // catalog generation does not move until it is published below, once
3876        // its forwarding endpoint exists. Listing it now would advertise a
3877        // module that `route.open` still refuses for having no forwarding
3878        // connection.
3879        let registration = match self
3880            .registry
3881            .register_unpublished_verified_with_control_ops(
3882                hello.manifest,
3883                negotiated_ver,
3884                connection_id,
3885                control_ops,
3886                verification.nonce_verified,
3887            ) {
3888            Ok(registration) => registration,
3889            Err(RegistryError::DuplicateModuleId { module_id }) => {
3890                return Ok(vec![control_error_frame(
3891                    &frame,
3892                    "duplicate_module_id",
3893                    format!(
3894                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3895                    ),
3896                )?])
3897            }
3898            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3899                return Ok(vec![control_error_frame(
3900                    &frame,
3901                    "invalid_module_id",
3902                    err.to_string(),
3903                )?])
3904            }
3905            Err(err) => {
3906                return Ok(vec![control_error_frame(
3907                    &frame,
3908                    "registry_error",
3909                    err.to_string(),
3910                )?])
3911            }
3912        };
3913        let differing_declarations =
3914            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3915                Ok(differing) => differing,
3916                Err(err) => {
3917                    if matches!(
3918                        self.rollback_unpublished_hello(connection_id),
3919                        Ok(r) if !r.is_empty()
3920                    ) {
3921                        crate::supervise::notify_registration_release();
3922                    }
3923                    return Err(RouterError::Forwarding(err));
3924                }
3925            };
3926        #[cfg(test)]
3927        self.hold_between_registry_and_forwarding();
3928
3929        let mut reply = Vec::new();
3930        // Registry readers must wait from before the ACK can be read until
3931        // publication. Nest forwarding inside the registry lock, never reverse.
3932        let publication = self
3933            .registry
3934            .publish_registration_after(connection_id, || {
3935                if let Some(sink) = sink {
3936                    // The forwarding table's module store is also the daemon-to-module
3937                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3938                    // manifest has no routable provider role. Non-routable modules still
3939                    // cannot receive route.bind in production: `handle_route_open` checks
3940                    // the registry manifest with `target_has_required_role` before the
3941                    // only production call to `begin_route_bind_relay_for` below that
3942                    // route.open path. The remaining direct relay callers are unit tests
3943                    // and benchmark harnesses that construct forwarding state explicitly.
3944                    //
3945                    // The HELLO_ACK is queued by the forwarding table itself, before the
3946                    // endpoint becomes visible, and is NOT returned as a reply. A module
3947                    // reads HELLO_ACK first and exits on anything else; a reply is only
3948                    // written after this handler returns, by which time a route.open on
3949                    // another connection could already have queued a route.bind request
3950                    // for this module ahead of it.
3951                    let concurrency = manifest_concurrency(&registration.manifest);
3952                    self.forwarding.register_module_connection_acked(
3953                        connection_id,
3954                        registration.manifest.module_id.clone(),
3955                        negotiated_ver,
3956                        concurrency,
3957                        sink,
3958                        crate::forwarding::ModuleHelloAck {
3959                            frame: hello_ack,
3960                            verified_prefix_owner: verification.prefix_owner,
3961                        },
3962                    )?;
3963                } else {
3964                    // No sink means no forwarding endpoint, so nothing can be routed
3965                    // ahead of the ack; it goes out as the reply.
3966                    reply.push(hello_ack);
3967                }
3968                #[cfg(test)]
3969                self.hold_between_ack_and_publication();
3970                Ok(())
3971            })
3972            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3973        let published = match publication {
3974            Ok(published) => published,
3975            Err(err) => {
3976                // The registry lock has been released, so rollback can take it
3977                // again. No forwarding endpoint or route was published. Keep
3978                // forwarding's weak connection-to-spawn association until the
3979                // connection's read loop ends and removes its remaining routes.
3980                // Removing this unpublished entry does not advance the catalog
3981                // generation.
3982                if matches!(
3983                    self.rollback_unpublished_hello(connection_id),
3984                    Ok(r) if !r.is_empty()
3985                ) {
3986                    crate::supervise::notify_registration_release();
3987                }
3988                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3989                return Ok(vec![control_error_frame(
3990                    &frame,
3991                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
3992                        "invalid_hello"
3993                    } else {
3994                        forwarding_error_code(&err)
3995                    },
3996                    err.to_string(),
3997                )?]);
3998            }
3999        };
4000        if !published {
4001            debug!(
4002                module_id = %registration.manifest.module_id,
4003                connection_id = connection_id.get(),
4004                "registration was removed before it could be published"
4005            );
4006            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
4007            return Ok(reply);
4008        }
4009
4010        drop(_prefix_ownership);
4011        drop(_prefix_live);
4012
4013        // Exposure over assumption: Concurrency's serde default is pinned to the
4014        // pre-field behavior (ModuleManaged), so a management surface that is
4015        // genuinely Serial and just never declared it inherits concurrent
4016        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
4017        // turns "no module has been bitten yet" into the checkable claim "no
4018        // module is exposed" -- one read of the boot log instead of a fleet
4019        // audit. Detected from the raw HELLO bytes because the serde default
4020        // deliberately erases the absent/declared distinction from the type.
4021        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
4022            info!(
4023                module_id = %registration.manifest.module_id,
4024                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
4025            );
4026        }
4027        if registration.manifest.registration_channel == Some(false)
4028            && self
4029                .supervisor
4030                .module_is_gated(&registration.manifest.module_id)
4031            && self
4032                .config_runtime
4033                .as_ref()
4034                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
4035                .as_deref()
4036                == Some("declared")
4037        {
4038            warn!(module_id = %registration.manifest.module_id,
4039                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
4040        }
4041
4042        self.apply_registration_capabilities(&registration);
4043
4044        self.supervisor
4045            .record_activity_registration(&registration.manifest.module_id);
4046
4047        info!(
4048            module_id = %registration.manifest.module_id,
4049            module_version = %registration.manifest.module_version,
4050            negotiated_ver,
4051            routable_provider = manifest_provides_routable_role(&registration.manifest),
4052            connection_id = connection_id.get(),
4053            "module registered"
4054        );
4055
4056        if let Some(spawn) = &channel_spawn {
4057            if let Some(sink) = primary_sink {
4058                spawn.bind_primary_sink(sink);
4059            }
4060            spawn.hello_accepted();
4061        } else if !prefix_submodule {
4062            self.supervisor
4063                .retire_unused_registration_channel(&registration.manifest.module_id, false);
4064        }
4065        self.file_development_widening(
4066            hello_authority.map(|authority| authority.record),
4067            differing_declarations,
4068        );
4069        #[cfg(windows)]
4070        if let Some(nonce) = hello.launch_nonce.as_deref() {
4071            self.supervisor
4072                .program_hello_accepted(&registration.manifest.module_id, nonce);
4073        }
4074
4075        #[cfg(test)]
4076        if let Some(hold) = &self.hello_inside_publication_hold {
4077            hold.wait();
4078            hold.wait();
4079        }
4080
4081        Ok(reply)
4082    }
4083
4084    /// Register a HELLO the swap gate admitted into the candidate slot of the
4085    /// registry and of forwarding, where it is reachable over its own
4086    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
4087    /// nothing routes to it until the supervisor cuts over.
4088    ///
4089    /// Registry first (unpublished), then forwarding, then publication, the
4090    /// same order as an ordinary HELLO; a forwarding failure removes the
4091    /// registry entry again. The swap supervisor treats a published, ready
4092    /// candidate as registered and promotes it, and promotion needs the
4093    /// candidate's forwarding endpoint, so the candidate is published only
4094    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
4095    /// recompute capability verdicts or run the capability deny census
4096    /// (`enforce_capability_denies`): both are about the module in the active
4097    /// slot, which `route.open` can target. A candidate sits in the candidate
4098    /// slot, so it neither provides capabilities to other modules nor can be
4099    /// routed to until promotion moves it into the active slot.
4100    #[allow(clippy::too_many_arguments)]
4101    fn register_swap_candidate(
4102        &self,
4103        connection_id: ConnectionId,
4104        sink: Option<crate::FrameSink>,
4105        frame: &Frame,
4106        manifest: ModuleManifest,
4107        negotiated_ver: u8,
4108        control_ops: Vec<String>,
4109        hello_ack: Frame,
4110        hello_authority: Option<&HelloAuthority>,
4111        differing_declarations: &mut ProviderDeclarations,
4112        #[cfg(windows)] launch_nonce: Option<&str>,
4113    ) -> Result<Vec<Frame>, RouterError> {
4114        let module_id = manifest.module_id.clone();
4115        // Closing a swap and publishing its candidate must be ordered. The
4116        // spawn role proves which slot is intended, not that the slot is open.
4117        self.supervisor
4118            .with_swap_candidate_admission(&module_id, || {
4119                let reply = self.publish_swap_candidate(
4120                    connection_id,
4121                    sink,
4122                    frame,
4123                    manifest,
4124                    negotiated_ver,
4125                    control_ops,
4126                    hello_ack,
4127                    hello_authority,
4128                    differing_declarations,
4129                    #[cfg(windows)]
4130                    launch_nonce,
4131                );
4132                let admitted = self
4133                    .registry
4134                    .get_candidate(&module_id)
4135                    .ok()
4136                    .flatten()
4137                    .is_some_and(|candidate| candidate.connection_id == connection_id);
4138                (reply, admitted)
4139            })
4140            .unwrap_or_else(|| {
4141                Ok(vec![control_error_frame(
4142                    frame,
4143                    "swap_token_invalid",
4144                    "swap ended before candidate HELLO publication",
4145                )?])
4146            })
4147    }
4148
4149    #[allow(clippy::too_many_arguments)]
4150    fn publish_swap_candidate(
4151        &self,
4152        connection_id: ConnectionId,
4153        sink: Option<crate::FrameSink>,
4154        frame: &Frame,
4155        manifest: ModuleManifest,
4156        negotiated_ver: u8,
4157        control_ops: Vec<String>,
4158        hello_ack: Frame,
4159        hello_authority: Option<&HelloAuthority>,
4160        differing_declarations: &mut ProviderDeclarations,
4161        #[cfg(windows)] launch_nonce: Option<&str>,
4162    ) -> Result<Vec<Frame>, RouterError> {
4163        let module_id = manifest.module_id.clone();
4164        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4165            manifest,
4166            negotiated_ver,
4167            connection_id,
4168            control_ops,
4169        ) {
4170            Ok(registration) => registration,
4171            Err(RegistryError::DuplicateModuleId { module_id }) => {
4172                return Ok(vec![control_error_frame(
4173                    frame,
4174                    "duplicate_module_id",
4175                    format!(
4176                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4177                    ),
4178                )?])
4179            }
4180            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4181                return Ok(vec![control_error_frame(
4182                    frame,
4183                    "invalid_module_id",
4184                    err.to_string(),
4185                )?])
4186            }
4187            Err(err) => {
4188                return Ok(vec![control_error_frame(
4189                    frame,
4190                    "registry_error",
4191                    err.to_string(),
4192                )?])
4193            }
4194        };
4195        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4196            Ok(differing) => differing,
4197            Err(err) => {
4198                if matches!(
4199                    self.rollback_unpublished_hello(connection_id),
4200                    Ok(r) if !r.is_empty()
4201                ) {
4202                    crate::supervise::notify_registration_release();
4203                }
4204                return Err(RouterError::Forwarding(err));
4205            }
4206        };
4207        #[cfg(test)]
4208        self.hold_between_registry_and_forwarding();
4209        let mut reply = Vec::new();
4210        let publication = self
4211            .registry
4212            .publish_registration_after(connection_id, || {
4213                if let Some(sink) = sink {
4214                    // Same ordering as an ordinary HELLO: queue the ACK before
4215                    // inserting the endpoint, and keep registry readers excluded
4216                    // until the candidate is published.
4217                    let concurrency = manifest_concurrency(&registration.manifest);
4218                    self.forwarding.register_candidate_module_connection_acked(
4219                        connection_id,
4220                        module_id.clone(),
4221                        negotiated_ver,
4222                        concurrency,
4223                        sink,
4224                        hello_ack,
4225                    )?;
4226                } else {
4227                    reply.push(hello_ack);
4228                }
4229                #[cfg(test)]
4230                self.hold_between_ack_and_publication();
4231                Ok(())
4232            })
4233            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4234        let published = match publication {
4235            Ok(published) => published,
4236            Err(err) => {
4237                if matches!(
4238                    self.rollback_unpublished_hello(connection_id),
4239                    Ok(r) if !r.is_empty()
4240                ) {
4241                    crate::supervise::notify_registration_release();
4242                }
4243                self.refuse_hello_authority(connection_id, hello_authority);
4244                return Ok(vec![control_error_frame(
4245                    frame,
4246                    forwarding_error_code(&err),
4247                    err.to_string(),
4248                )?]);
4249            }
4250        };
4251        if !published {
4252            debug!(
4253                module_id = %module_id,
4254                connection_id = connection_id.get(),
4255                "swap candidate registration was removed before it could be published"
4256            );
4257            self.refuse_hello_authority(connection_id, hello_authority);
4258            return Ok(reply);
4259        }
4260        info!(
4261            module_id = %module_id,
4262            module_version = %registration.manifest.module_version,
4263            negotiated_ver,
4264            ready = registration.ready,
4265            connection_id = connection_id.get(),
4266            "swap candidate registered; not routable until cutover"
4267        );
4268        #[cfg(windows)]
4269        if let Some(nonce) = launch_nonce {
4270            self.supervisor.program_hello_accepted(&module_id, nonce);
4271        }
4272        Ok(reply)
4273    }
4274
4275    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4276    /// spawn's requested provider declarations. Runs only once the registry
4277    /// has accepted the HELLO, before its endpoint is published, so a route
4278    /// reserved on the endpoint always finds the spawn. Returns the requested
4279    /// entries that differ from the saved approvals, for a widening request.
4280    fn admit_hello_authority(
4281        &self,
4282        connection: ConnectionId,
4283        authority: Option<&HelloAuthority>,
4284    ) -> Result<ProviderDeclarations, ForwardingError> {
4285        let Some(authority) = authority else {
4286            return Ok(ProviderDeclarations::new());
4287        };
4288        let froze = authority
4289            .record
4290            .freeze_declarations(authority.requested.clone());
4291        authority
4292            .froze
4293            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4294        self.forwarding
4295            .bind_target_authority(connection, authority.record.clone())
4296            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4297        Ok(froze.unwrap_or_default())
4298    }
4299
4300    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4301    /// registry accepted it, so the refused connection is no registration of
4302    /// the spawn and the spawn's declarations are left for the HELLO that
4303    /// does register it to freeze.
4304    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4305        let Some(authority) = authority else {
4306            return;
4307        };
4308        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4309            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4310        }
4311        if authority
4312            .froze
4313            .swap(false, std::sync::atomic::Ordering::Relaxed)
4314        {
4315            authority.record.unfreeze_refused_declarations();
4316        }
4317    }
4318
4319    fn build_hello_ack(
4320        &self,
4321        frame: &Frame,
4322        negotiated_ver: u8,
4323        module_id: &str,
4324    ) -> Result<Frame, RouterError> {
4325        let ack = ModuleHelloAckBody {
4326            negotiated_ver,
4327            subc_ops: module_subc_ops(),
4328            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4329            storage: self
4330                .storage_config
4331                .as_ref()
4332                .map(|cfg| cfg.descriptor_for(module_id)),
4333            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4334        };
4335        let body = serde_json::to_vec(&ack).map_err(|err| {
4336            RouterError::backend(
4337                0,
4338                frame.header.corr,
4339                format!("failed to encode HELLO_ACK: {err}"),
4340            )
4341        })?;
4342
4343        Frame::build_with_version(
4344            negotiated_ver,
4345            FrameType::HelloAck,
4346            control_flags(),
4347            0,
4348            0,
4349            frame.header.corr,
4350            body,
4351        )
4352        .map_err(RouterError::FrameBuild)
4353    }
4354
4355    async fn handle_client_control_request(
4356        &self,
4357        ctx: &RouteCtx,
4358        frame: Frame,
4359        request: ClientControlRequest,
4360        route_open_timings: &mut Option<RouteOpenTimings>,
4361    ) -> Result<Vec<Frame>, RouterError> {
4362        if let Some(owner) = &self.config_runtime {
4363            let module = match &request {
4364                ClientControlRequest::SupervisorRestart { module_id, .. }
4365                | ClientControlRequest::SupervisorReload { module_id }
4366                | ClientControlRequest::SupervisorSwap { module_id, .. }
4367                | ClientControlRequest::SupervisorSetEnabled {
4368                    module_id,
4369                    enabled: true,
4370                } => Some(module_id.as_str()),
4371                _ => None,
4372            };
4373            let rescan = matches!(
4374                &request,
4375                ClientControlRequest::SupervisorRescan { preview: false }
4376                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4377            );
4378            let held = if module.is_some() || rescan {
4379                let module = module.map(str::to_owned);
4380                owner
4381                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4382                    .await
4383            } else {
4384                Ok(())
4385            };
4386            if let Err(error) = held {
4387                if error.code != "config_delivery_deferred" {
4388                    let code = if error.code == "store_tampered" {
4389                        "store_tampered"
4390                    } else {
4391                        "config_gated"
4392                    };
4393                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4394                }
4395            }
4396        }
4397        if let Some(operation) = privileged_operation(&request) {
4398            let caller = self.resolve_caller(ctx.connection_id).await;
4399            let op = client_control_request_op(&request);
4400            let text = prompt_text(operation, &caller);
4401            match self.privileged_operator_prompt {
4402                PrivilegedOperatorPrompt::Log => {
4403                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4404                        target = ?operation, caller = %caller.description(), summary = %text,
4405                        "privileged request would prompt the operator");
4406                }
4407                PrivilegedOperatorPrompt::Enforce => {
4408                    let key =
4409                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4410                    let shortcut =
4411                        self.operator_shortcut_stamp(ctx.connection_id)
4412                            .await
4413                            .map(|stamp| {
4414                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
4415                            });
4416                    let outcome = self
4417                        .forwarding
4418                        .operator_confirms()
4419                        .approve_privileged_with_shortcut(
4420                            ctx,
4421                            &frame,
4422                            op,
4423                            text,
4424                            caller.description(),
4425                            key,
4426                            shortcut,
4427                        )
4428                        .await;
4429                    if outcome.code != "confirmed" {
4430                        return Ok(vec![outcome.frame(&frame)]);
4431                    }
4432                }
4433            }
4434        }
4435        match request {
4436            ClientControlRequest::DaemonShutdownIntent { intent } => {
4437                if intent.as_str() != Some("restart") {
4438                    return Ok(vec![control_error_frame(
4439                        &frame,
4440                        "invalid_params",
4441                        "intent must be 'restart'",
4442                    )?]);
4443                }
4444                // A stamped daemon boots a newer approved generation only from a
4445                // durable restart intent, written here before the daemon exits.
4446                // Failing to write it never blocks the restart: the next start
4447                // then boots the last active generation and the newer one waits.
4448                if let Some(owner) = &self.config_runtime {
4449                    match owner
4450                        .on_blocking(|owner| owner.assign_daemon_restart())
4451                        .await
4452                    {
4453                        Ok(Some(generation)) => {
4454                            info!(
4455                                generation,
4456                                "daemon restart will warm up approved generation"
4457                            )
4458                        }
4459                        Ok(None) => {}
4460                        Err(error) => warn!(
4461                            %error,
4462                            "daemon restart intent not recorded; the next start boots the last active generation"
4463                        ),
4464                    }
4465                }
4466                let response = ClientControlResponse::DaemonShutdownIntent {
4467                    intent: "restart".to_owned(),
4468                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4469                };
4470                Ok(vec![control_response_body_frame(
4471                    &frame,
4472                    &response,
4473                    "ClientControlResponse::DaemonShutdownIntent",
4474                )?])
4475            }
4476            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4477            ClientControlRequest::CatalogList { module_id } => {
4478                self.handle_catalog_list(frame, module_id)
4479            }
4480            ClientControlRequest::RouteOpen {
4481                target,
4482                identity,
4483                consumer_identity,
4484                consumer_capabilities,
4485                role_versions,
4486                busy_refusals,
4487                admission_facts,
4488                scope,
4489                ..
4490            } => {
4491                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4492                    &frame.body,
4493                ) {
4494                    Ok(extensions) => extensions,
4495                    Err(err) => {
4496                        return Ok(vec![control_error_frame(
4497                            &frame,
4498                            "invalid_control_body",
4499                            format!("malformed route.open extensions: {err}"),
4500                        )?]);
4501                    }
4502                };
4503                self.handle_route_open(
4504                    ctx,
4505                    frame,
4506                    RouteOpenRequest {
4507                        target,
4508                        identity,
4509                        consumer_identity,
4510                        consumer_capabilities,
4511                        role_versions,
4512                        busy_refusals,
4513                        admission_facts,
4514                        scope,
4515                        accepts_close_reasons: extensions.accepts_close_reasons,
4516                    },
4517                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4518                )
4519                .await
4520            }
4521            ClientControlRequest::RoutePoll {
4522                route_channel,
4523                route_epoch,
4524                kind,
4525            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4526            ClientControlRequest::SupervisorList {} => {
4527                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4528                    self.agent_declarations.refuse(
4529                        self,
4530                        ctx,
4531                        control_error_frame(
4532                            &frame,
4533                            "busy",
4534                            "supervisor list work is at capacity; retry",
4535                        )?,
4536                    );
4537                    return Ok(Vec::new());
4538                };
4539                // Filesystem-backed diagnostics must not hold up this connection's reader.
4540                let handler = self.clone();
4541                let sink = ctx.egress.clone();
4542                tokio::spawn(
4543                    async move {
4544                        let _permit = permit;
4545                        let result = handler.handle_supervisor_list(frame.clone()).await;
4546                        let replies = match result {
4547                            Ok(replies) => replies,
4548                            Err(error) => {
4549                                control_error_frame(&frame, "backend_error", error.to_string())
4550                                    .into_iter()
4551                                    .collect()
4552                            }
4553                        };
4554                        for reply in replies {
4555                            if !matches!(
4556                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4557                                    .await,
4558                                Ok(Ok(()))
4559                            ) {
4560                                break;
4561                            }
4562                        }
4563                    }
4564                    .with_current_subscriber(),
4565                );
4566                Ok(Vec::new())
4567            }
4568            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4569                self.handle_supervisor_spawn_snapshot(frame)
4570            }
4571            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4572                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4573            }
4574            ClientControlRequest::SupervisorRestart {
4575                module_id,
4576                drain_timeout_ms,
4577            } => {
4578                self.log_supervisor_request_received(
4579                    ctx,
4580                    frame.header.corr,
4581                    ops::SUPERVISOR_RESTART,
4582                    Some(&module_id),
4583                    None,
4584                )?;
4585                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4586                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4587                    .await
4588            }
4589            ClientControlRequest::SupervisorSwap {
4590                module_id,
4591                ready_timeout_ms,
4592            } => {
4593                self.log_supervisor_request_received(
4594                    ctx,
4595                    frame.header.corr,
4596                    ops::SUPERVISOR_SWAP,
4597                    Some(&module_id),
4598                    None,
4599                )?;
4600                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4601                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4602                    .await
4603            }
4604            ClientControlRequest::SupervisorReload { module_id } => {
4605                self.log_supervisor_request_received(
4606                    ctx,
4607                    frame.header.corr,
4608                    ops::SUPERVISOR_RELOAD,
4609                    Some(&module_id),
4610                    None,
4611                )?;
4612                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4613                self.handle_supervisor_reload(frame, module_id, requester)
4614                    .await
4615            }
4616            ClientControlRequest::SupervisorRescan { preview } => {
4617                if !preview {
4618                    self.log_supervisor_request_received(
4619                        ctx,
4620                        frame.header.corr,
4621                        ops::SUPERVISOR_RESCAN,
4622                        None,
4623                        None,
4624                    )?;
4625                }
4626                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4627                let operation = self.handle_supervisor_rescan(
4628                    frame,
4629                    if preview {
4630                        RescanMode::Preview
4631                    } else {
4632                        RescanMode::Execute
4633                    },
4634                    requester,
4635                );
4636                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4637                    .await
4638            }
4639            ClientControlRequest::SupervisorRescanChecked {
4640                preview,
4641                candidate,
4642                expect,
4643            } => {
4644                self.observe_control_wait(
4645                    ctx,
4646                    None,
4647                    ops::SUPERVISOR_RESCAN,
4648                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4649                )
4650                .await
4651            }
4652            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4653                self.log_supervisor_request_received(
4654                    ctx,
4655                    frame.header.corr,
4656                    ops::SUPERVISOR_RELEASE_RESERVED,
4657                    Some(&module_id),
4658                    None,
4659                )?;
4660                self.handle_supervisor_release_reserved(frame, module_id)
4661                    .await
4662            }
4663            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4664                self.log_supervisor_request_received(
4665                    ctx,
4666                    frame.header.corr,
4667                    ops::SUPERVISOR_SET_ENABLED,
4668                    Some(&module_id),
4669                    Some(enabled),
4670                )?;
4671                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4672                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4673                    .await
4674            }
4675            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4676                self.handle_supervisor_health_probe(ctx, frame, module_id)
4677                    .await
4678            }
4679            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4680            ClientControlRequest::SupervisorRoutes { module_id } => {
4681                self.handle_supervisor_routes(frame, module_id)
4682            }
4683            ClientControlRequest::SupervisorProvenance { module_id } => {
4684                self.handle_supervisor_provenance(ctx, frame, module_id)
4685                    .await
4686            }
4687            ClientControlRequest::SupervisorStderrTail {
4688                module_id,
4689                max_lines,
4690                max_bytes,
4691            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4692            ClientControlRequest::SupervisorTerminals { module_id } => {
4693                self.handle_supervisor_terminals(ctx, frame, module_id)
4694                    .await
4695            }
4696        }
4697    }
4698
4699    fn log_supervisor_request_received(
4700        &self,
4701        ctx: &RouteCtx,
4702        corr: u64,
4703        op: &'static str,
4704        module_id: Option<&str>,
4705        enabled: Option<bool>,
4706    ) -> Result<(), RouterError> {
4707        let caller = self.supervisor_requester(ctx, corr)?;
4708        let caller = principal_label(&caller);
4709        // `Option` fields are recorded only when present, so a request with no
4710        // module id (rescan) or no enabled flag simply omits that field.
4711        info!(
4712            target: "control",
4713            op,
4714            module_id,
4715            enabled,
4716            connection_id = ctx.connection_id.get(),
4717            caller = %caller,
4718            "supervisor request received"
4719        );
4720        Ok(())
4721    }
4722
4723    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4724        Ok(self
4725            .registry
4726            .get_module_by_connection(ctx.connection_id)
4727            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4728            .map(|registration| Principal::Reserved {
4729                module_id: registration.manifest.module_id,
4730            })
4731            .unwrap_or(Principal::Direct))
4732    }
4733
4734    fn handle_module_control_request(
4735        &self,
4736        connection_id: ConnectionId,
4737        frame: Frame,
4738        request: ModuleControlRequestFromModule,
4739    ) -> Result<Vec<Frame>, RouterError> {
4740        match request {
4741            ModuleControlRequestFromModule::RouteAuthorize {
4742                principal,
4743                scope,
4744                target,
4745                expected,
4746            } => self.handle_route_authorize(
4747                connection_id,
4748                frame,
4749                principal,
4750                scope,
4751                target,
4752                expected,
4753            ),
4754            ModuleControlRequestFromModule::CatalogUpdate {
4755                provides,
4756                capabilities,
4757                ready,
4758            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4759            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4760                self.handle_catalog_update_role_declarations(
4761                    connection_id,
4762                    frame,
4763                    role_declarations,
4764                )
4765            }
4766            ModuleControlRequestFromModule::LiveRoots {} => {
4767                let registered = self
4768                    .registry
4769                    .get_module_by_connection(connection_id)
4770                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4771                let Some(registration) = registered else {
4772                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4773                };
4774                let response = self
4775                    .forwarding
4776                    .live_roots(&registration.manifest.module_id)
4777                    .map_err(RouterError::Forwarding)?;
4778                Ok(vec![control_response_body_frame(
4779                    &frame,
4780                    &response,
4781                    "ModuleControlResponseToModule::LiveRoots",
4782                )?])
4783            }
4784            ModuleControlRequestFromModule::AgentCommands {
4785                started,
4786                finished,
4787                known,
4788            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4789            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4790                self.handle_scope_sync(connection_id, frame, generation, scopes)
4791            }
4792            ModuleControlRequestFromModule::ScopeApply {
4793                generation,
4794                upsert,
4795                end,
4796            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4797            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4798                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4799            }
4800            _ => Ok(vec![control_error_frame(
4801                &frame,
4802                "unsupported_control_frame",
4803                "unsupported module control operation",
4804            )?]),
4805        }
4806    }
4807
4808    fn handle_scope_served_by(
4809        &self,
4810        connection_id: ConnectionId,
4811        frame: Frame,
4812    ) -> Result<Vec<Frame>, RouterError> {
4813        let registered = self
4814            .registry
4815            .get_module_by_connection(connection_id)
4816            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4817        let Some(registered) = registered else {
4818            return Ok(vec![control_error_frame(
4819                &frame,
4820                "not_registered",
4821                "scope.served_by requires an active module registration owned by this connection",
4822            )?]);
4823        };
4824        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4825        {
4826            Ok(request) => request,
4827            Err(err) => {
4828                return Ok(vec![control_error_frame(
4829                    &frame,
4830                    "invalid_control_body",
4831                    format!("malformed scope.served_by body: {err}"),
4832                )?])
4833            }
4834        };
4835        let answer = self
4836            .scopes
4837            .read()
4838            .unwrap_or_else(|poisoned| poisoned.into_inner())
4839            .served_by(
4840                &registered.manifest.module_id,
4841                &request.scope_ref,
4842                request.scope_epoch,
4843                &request.module_id,
4844            );
4845        let reply = subc_control::ScopeServedByReply::new(
4846            answer,
4847            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4848        );
4849        Ok(vec![control_response_body_frame(
4850            &frame,
4851            &reply,
4852            "ScopeServedByReply",
4853        )?])
4854    }
4855
4856    /// Explicit test-only phone policy; daemon configuration cannot select it.
4857    #[cfg(any(test, feature = "test-support"))]
4858    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
4859        self.operator_app_policy.phone_enabled = enabled;
4860        self
4861    }
4862
4863    /// Resolve folders before taking the scope-table lock: a slow filesystem
4864    /// must not hold up admissions for unrelated scoped routes.
4865    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
4866        let mut scopes = ScopeRecords::from(scopes);
4867        for (index, record) in scopes.records.iter_mut().enumerate() {
4868            if let Some(refusal) = Self::canonicalize_workdir(record) {
4869                scopes.refusals.insert(index, refusal);
4870            }
4871        }
4872        scopes
4873    }
4874
4875    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
4876        let workdir = record.workdir.as_mut()?;
4877        let path = std::path::Path::new(workdir);
4878        if !path.is_absolute() {
4879            return Some((
4880                error_codes::INVALID_WORKDIR,
4881                "workdir must be absolute".to_string(),
4882            ));
4883        }
4884        match ProjectRootId::from_path_allowing_missing(path) {
4885            Ok(root) => match root.as_path().to_str() {
4886                Some(canonical) => {
4887                    *workdir = canonical.to_string();
4888                    None
4889                }
4890                None => Some((
4891                    error_codes::INVALID_WORKDIR,
4892                    "canonical workdir is not UTF-8".to_string(),
4893                )),
4894            },
4895            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
4896        }
4897    }
4898
4899    /// `scope.sync`: the owner is the module registered on this connection.
4900    /// A connection with no registration (every client connection, `direct`
4901    /// included) is refused `not_registered` before the table is consulted.
4902    fn handle_scope_sync(
4903        &self,
4904        connection_id: ConnectionId,
4905        frame: Frame,
4906        generation: u64,
4907        scopes: Vec<ScopeRecord>,
4908    ) -> Result<Vec<Frame>, RouterError> {
4909        self.handle_scope_change(connection_id, frame, generation, scopes, None)
4910    }
4911
4912    fn handle_scope_change(
4913        &self,
4914        connection_id: ConnectionId,
4915        frame: Frame,
4916        generation: u64,
4917        scopes: Vec<ScopeRecord>,
4918        end: Option<Vec<ScopeEnd>>,
4919    ) -> Result<Vec<Frame>, RouterError> {
4920        let is_apply = end.is_some();
4921        let Some(registration) = self
4922            .registry
4923            .get_module_by_connection(connection_id)
4924            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4925        else {
4926            return Ok(vec![control_error_frame(
4927                &frame,
4928                "not_registered",
4929                "scope.sync and scope.apply require an active module registration owned by this connection",
4930            )?]);
4931        };
4932        let owner = registration.manifest.module_id;
4933        let scopes = Self::prepare_scope_records(scopes);
4934        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
4935        let is_current_launch = |connection: ConnectionId| {
4936            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
4937        };
4938        // Lock order is the scope table, then the forwarding table: the new
4939        // tags are published, and the routes the change closes are selected,
4940        // while the scope table is still write-locked, so no admission can read
4941        // a record whose tag is not yet published.
4942        let mut table = self
4943            .scopes
4944            .write()
4945            .unwrap_or_else(|poisoned| poisoned.into_inner());
4946        let outcome = match end {
4947            Some(end) => table.apply(
4948                &owner,
4949                connection_id,
4950                is_current_launch,
4951                generation,
4952                scopes,
4953                end,
4954            ),
4955            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
4956        };
4957        let drained = match &outcome {
4958            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
4959            Err(_) => Vec::new(),
4960        };
4961        let has_deadlines = outcome.is_ok() && table.has_deadlines();
4962        drop(table);
4963        if has_deadlines {
4964            self.scope_deadline_added.notify_one();
4965        }
4966        match outcome {
4967            Ok(applied) => {
4968                let counts = ScopeOutcomeCounts::of(&applied.results);
4969                info!(
4970                    owner = %owner,
4971                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4972                    generation,
4973                    records = applied.results.len(),
4974                    created = counts.created,
4975                    replaced = counts.replaced,
4976                    updated = counts.updated,
4977                    unchanged = counts.unchanged,
4978                    refused = counts.refused,
4979                    ended = applied.ended.len(),
4980                    tag_changes = applied.tag_changes.len(),
4981                    routes_closed = drained.len(),
4982                    "scope change accepted"
4983                );
4984                // An accepted scope change can still refuse individual records, and the
4985                // owner is the only party that sees the reply. Name them here so
4986                // an operator can tell a refused session from a missing one
4987                // without the owner's logs. Capped so a call that refuses
4988                // thousands cannot flood the log; the count above is complete.
4989                for refused in applied
4990                    .results
4991                    .iter()
4992                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
4993                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
4994                {
4995                    warn!(
4996                        owner = %owner,
4997                        generation,
4998                        scope_ref = %refused.scope_ref,
4999                        scope_epoch = refused.scope_epoch,
5000                        code = refused.code.as_deref().unwrap_or(""),
5001                        "scope record refused"
5002                    );
5003                }
5004                self.close_scope_drained_routes(drained);
5005                let response = if is_apply {
5006                    ModuleControlResponseToModule::ScopeApply {
5007                        generation,
5008                        results: applied.results,
5009                        end_results: applied.end_results,
5010                        ended: applied.ended,
5011                    }
5012                } else {
5013                    ModuleControlResponseToModule::ScopeSync {
5014                        generation,
5015                        results: applied.results,
5016                        ended: applied.ended,
5017                    }
5018                };
5019                Ok(vec![control_response_body_frame(
5020                    &frame,
5021                    &response,
5022                    "scope change response",
5023                )?])
5024            }
5025            Err(refusal) => {
5026                info!(
5027                    owner = %owner,
5028                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
5029                    generation,
5030                    code = refusal.code,
5031                    "scope change refused"
5032                );
5033                Ok(vec![control_error_frame(
5034                    &frame,
5035                    refusal.code,
5036                    refusal.message,
5037                )?])
5038            }
5039        }
5040    }
5041
5042    /// Notify both endpoints of routes drained by a scope change.
5043    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
5044        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
5045    }
5046
5047    /// Re-authorize a stored source on a principal the module supplies.
5048    ///
5049    /// That principal carries no spawn or authority epoch, so this reply never
5050    /// conveys a caller attestation or a first-party mark, and a provider must
5051    /// not apply automatic grants on anything it authorizes.
5052    fn handle_route_authorize(
5053        &self,
5054        connection_id: ConnectionId,
5055        frame: Frame,
5056        principal: Principal,
5057        scope: subc_protocol::scope::RouteAuthorizeScope,
5058        target: String,
5059        expected: subc_protocol::scope::RouteAuthorizeExpected,
5060    ) -> Result<Vec<Frame>, RouterError> {
5061        use crate::scopes::admission::{admit_route, AdmissionMode};
5062        use subc_protocol::scope::{
5063            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
5064        };
5065        let registry = self
5066            .registry
5067            .route_admission_snapshot()
5068            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5069        let owner_configured = match &scope.owner {
5070            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5071            _ => false,
5072        };
5073        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
5074        let answer = {
5075            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
5076            let permitted = registry
5077                .iter()
5078                .find(|r| r.connection_id == connection_id)
5079                .is_some_and(|r| {
5080                    scopes.is_federated_owner(&Principal::Reserved {
5081                        module_id: r.module_id.clone(),
5082                    }) && r.capabilities.as_ref().is_some_and(|caps| {
5083                        caps.provides
5084                            .iter()
5085                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
5086                    })
5087                });
5088            if !permitted {
5089                drop(scopes);
5090                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
5091                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
5092            }
5093            admit_route(
5094                &scopes,
5095                &registry,
5096                &principal,
5097                &target,
5098                Some(&selector),
5099                owner_configured,
5100                AdmissionMode::Authorize(&expected),
5101            )
5102        };
5103        let response = match answer {
5104            Ok(admission) => {
5105                let mut response = RouteAuthorizeResponse::new(
5106                    RouteAuthorizeOutcome::Authorized,
5107                    "route admission authorized",
5108                );
5109                response.content_version = admission.content_version;
5110                response
5111            }
5112            Err(refusal) => refusal.response(),
5113        };
5114        Ok(vec![control_response_body_frame(
5115            &frame,
5116            &response,
5117            "RouteAuthorizeResponse",
5118        )?])
5119    }
5120
5121    /// `scope.describe`: any registered module may read any scope, because a
5122    /// provider must read the scope a route it serves is stamped with.
5123    fn handle_scope_describe(
5124        &self,
5125        connection_id: ConnectionId,
5126        frame: Frame,
5127        owner: Principal,
5128        scope_ref: String,
5129    ) -> Result<Vec<Frame>, RouterError> {
5130        let registered = self
5131            .registry
5132            .get_module_by_connection(connection_id)
5133            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5134        let Some(registered) = registered else {
5135            return Ok(vec![control_error_frame(
5136                &frame,
5137                "not_registered",
5138                "scope.describe requires an active module registration owned by this connection",
5139            )?]);
5140        };
5141        let scopes = self
5142            .scopes
5143            .read()
5144            .unwrap_or_else(|poisoned| poisoned.into_inner());
5145        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5146            return Ok(vec![control_error_frame(
5147                &frame,
5148                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5149                "scope.describe of the federated owner requires scope-federated/v1",
5150            )?]);
5151        }
5152        let mut description = scopes.describe(&owner, &scope_ref);
5153        drop(scopes);
5154        if owner
5155            != (Principal::Reserved {
5156                module_id: registered.manifest.module_id.clone(),
5157            })
5158        {
5159            if let Some(facts) = description
5160                .stamp
5161                .as_mut()
5162                .and_then(|stamp| stamp.attributes.federated.as_mut())
5163            {
5164                facts.stamp_required = false;
5165            }
5166        }
5167        // Describe readers also decode strict ScopeAttributes. Attribution is
5168        // safe to omit unless the requesting module declares it understands it.
5169        if !registered
5170            .manifest
5171            .capabilities
5172            .as_ref()
5173            .is_some_and(|caps| {
5174                caps.provides
5175                    .iter()
5176                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5177            })
5178        {
5179            if let Some(stamp) = description.stamp.as_mut() {
5180                stamp.attributes.on_behalf_of_agent = None;
5181            }
5182        }
5183        if !registered
5184            .manifest
5185            .capabilities
5186            .as_ref()
5187            .is_some_and(|caps| {
5188                caps.provides
5189                    .iter()
5190                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5191            })
5192        {
5193            if let Some(stamp) = description.stamp.as_mut() {
5194                stamp.attributes.flow_version = None;
5195                stamp.attributes.flow_code_hash = None;
5196                stamp.attributes.flow_install_id = None;
5197            }
5198        }
5199        let owner_configured = match &owner {
5200            // Ask whether the owner is configured (`is_configured`), not
5201            // whether it is on the roster (`get(..).is_some()`): a supervised
5202            // module's process can register and describe a scope before the
5203            // supervisor has put it on the roster.
5204            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5205            _ => false,
5206        };
5207        let response = ModuleControlResponseToModule::ScopeDescribe {
5208            status: description.status,
5209            scope_epoch: description.scope_epoch,
5210            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5211            owner_synced: description.owner_synced,
5212            owner_configured,
5213            scope: description.stamp,
5214        };
5215        Ok(vec![control_response_body_frame(
5216            &frame,
5217            &response,
5218            "ModuleControlResponseToModule::ScopeDescribe",
5219        )?])
5220    }
5221
5222    fn handle_catalog_update_role_declarations(
5223        &self,
5224        connection_id: ConnectionId,
5225        frame: Frame,
5226        role_declarations: serde_json::Value,
5227    ) -> Result<Vec<Frame>, RouterError> {
5228        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5229            return Ok(vec![control_error_frame(
5230                &frame,
5231                "invalid_role_declarations",
5232                err.to_string(),
5233            )?]);
5234        }
5235        let declarations = serde_json::from_value(role_declarations)
5236            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5237        if self
5238            .registry
5239            .replace_role_declarations_for_connection(connection_id, declarations)
5240            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5241            .is_none()
5242        {
5243            return Ok(vec![control_error_frame(
5244                &frame,
5245                "not_registered",
5246                "catalog.update_role_declarations requires an active module registration owned by this connection",
5247            )?]);
5248        }
5249        control_response_body_frame(
5250            &frame,
5251            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5252            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5253        )
5254        .map(|frame| vec![frame])
5255    }
5256
5257    fn handle_catalog_update(
5258        &self,
5259        connection_id: ConnectionId,
5260        frame: Frame,
5261        provides: Vec<ProviderRole>,
5262        capabilities: Option<CapabilityDeclarations>,
5263        ready: Option<bool>,
5264    ) -> Result<Vec<Frame>, RouterError> {
5265        self.refresh_capability_requirements();
5266        let Some(registration) = self
5267            .registry
5268            .get_module_by_connection(connection_id)
5269            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5270        else {
5271            return Ok(vec![control_error_frame(
5272                &frame,
5273                "not_registered",
5274                "catalog.update requires an active module registration owned by this connection",
5275            )?]);
5276        };
5277
5278        if let Some(message) =
5279            catalog_update_frozen_field_message(&registration.manifest, &provides)
5280        {
5281            return Ok(vec![control_error_frame(
5282                &frame,
5283                "catalog_update_frozen_field",
5284                message,
5285            )?]);
5286        }
5287
5288        let mut candidate = registration.manifest.clone();
5289        candidate.provides = provides.clone();
5290        candidate.capabilities = capabilities
5291            .clone()
5292            .or_else(|| registration.manifest.capabilities.clone());
5293        if let Some(rich_ui) = &candidate.rich_ui {
5294            if let Err(err) = rich_ui.validate() {
5295                return Ok(vec![control_error_frame(
5296                    &frame,
5297                    "invalid_manifest",
5298                    err.to_string(),
5299                )?]);
5300            }
5301        }
5302        if let Err(err) = candidate.validate_capability_grammar() {
5303            return Ok(vec![control_error_frame(
5304                &frame,
5305                "invalid_capability_grammar",
5306                err.to_string(),
5307            )?]);
5308        }
5309
5310        // Updates must honor the same reserved owner as initial registration;
5311        // otherwise an empty HELLO could acquire the claim after admission.
5312        let mut conflicts = self
5313            .capability_evaluator
5314            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5315        if let Some(conflict) = conflicts.first() {
5316            let message = format!(
5317                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5318                conflict.capability, conflict.claimants[0], candidate.module_id
5319            );
5320            for conflict in &mut conflicts {
5321                conflict.source = DuplicateClaimSource::CatalogUpdate;
5322            }
5323            log_duplicate_claim_events(conflicts);
5324            return Ok(vec![control_error_frame(
5325                &frame,
5326                "reserved_capability",
5327                message,
5328            )?]);
5329        }
5330
5331        let updated = match self.registry.replace_catalog_for_connection(
5332            connection_id,
5333            provides,
5334            capabilities,
5335            ready,
5336        ) {
5337            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5338                return Ok(vec![control_error_frame(
5339                    &frame,
5340                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5341                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5342                )?])
5343            }
5344            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5345                return Ok(vec![control_error_frame(
5346                    &frame,
5347                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5348                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5349                )?])
5350            }
5351            result => {
5352                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5353            }
5354        };
5355        if updated.is_none() {
5356            return Ok(vec![control_error_frame(
5357                &frame,
5358                "not_registered",
5359                "catalog.update requires an active module registration owned by this connection",
5360            )?]);
5361        }
5362        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5363            log_duplicate_claim_events(
5364                self.capability_evaluator
5365                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5366            );
5367        }
5368        if capability_census_trigger(
5369            registration.manifest.capabilities.as_ref(),
5370            updated
5371                .as_ref()
5372                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5373        ) {
5374            self.enforce_capability_denies();
5375        }
5376        self.refresh_capability_requirements();
5377
5378        let response = ModuleControlResponseToModule::CatalogUpdate {};
5379        control_response_body_frame(
5380            &frame,
5381            &response,
5382            "ModuleControlResponseToModule::CatalogUpdate",
5383        )
5384        .map(|frame| vec![frame])
5385    }
5386
5387    pub(crate) fn with_activity_ledger_config(
5388        mut self,
5389        run_dir: &Path,
5390        incarnation: String,
5391        config: crate::activity::ActivityConfig,
5392    ) -> Self {
5393        self.activity = Some(crate::activity::ActivityLedger::open_config(
5394            run_dir.join("activity.jsonl"),
5395            incarnation,
5396            config,
5397        ));
5398        self.supervisor.set_activity(self.activity.clone());
5399        self
5400    }
5401
5402    pub(crate) async fn configure_activity(
5403        &self,
5404        config: crate::activity::ActivityConfig,
5405    ) -> Result<(), &'static str> {
5406        match &self.activity {
5407            Some(ledger) => ledger.configure(config).await,
5408            None => Ok(()),
5409        }
5410    }
5411
5412    fn cancel_activity_subscription(
5413        &self,
5414        ctx: &RouteCtx,
5415        frame: &Frame,
5416    ) -> Result<bool, RouterError> {
5417        let task = self
5418            .activity_streams
5419            .lock()
5420            .unwrap_or_else(|p| p.into_inner())
5421            .remove(&(ctx.connection_id, frame.header.corr));
5422        let Some(task) = task else {
5423            return Ok(false);
5424        };
5425        task.abort();
5426        let end = Frame::build_with_version(
5427            response_version(frame),
5428            FrameType::StreamEnd,
5429            control_flags(),
5430            0,
5431            0,
5432            frame.header.corr,
5433            Vec::new(),
5434        )
5435        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5436        let sink = ctx.egress.clone();
5437        tokio::spawn(async move {
5438            let _ = sink.send(end).await;
5439        });
5440        Ok(true)
5441    }
5442
5443    async fn handle_activity_read(
5444        &self,
5445        ctx: &RouteCtx,
5446        frame: Frame,
5447    ) -> Result<Vec<Frame>, RouterError> {
5448        #[cfg(test)]
5449        {
5450            let pause = self
5451                .activity_request_pause
5452                .lock()
5453                .unwrap()
5454                .clone()
5455                .filter(|pause| pause.connection == ctx.connection_id);
5456            if let Some(pause) = pause {
5457                let _cancelled = ActivityRequestCancellation(pause.clone());
5458                pause.started.notify_one();
5459                std::future::pending::<()>().await;
5460            }
5461        }
5462        use subc_control::{
5463            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5464            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5465        };
5466        #[derive(Deserialize)]
5467        struct Identity {
5468            #[serde(default)]
5469            consumer_identity: Option<ConsumerIdentity>,
5470        }
5471        // A registration channel or claim-bound connection carries its module in
5472        // its binding, so no request field can name another principal, and its
5473        // subscription ends when the bound spawn's authority does.
5474        let mut bound_spawn = None;
5475        let legacy = match self.activity_reader(ctx.connection_id) {
5476            channel_operations::ActivityReader::Module { module_id, spawn } => {
5477                bound_spawn = Some(spawn);
5478                Some(Ok(Principal::Reserved { module_id }))
5479            }
5480            // Refused outright: falling back to `direct` would admit it.
5481            channel_operations::ActivityReader::Refused => {
5482                return Ok(vec![control_error_frame(
5483                    &frame,
5484                    ACTIVITY_READ_FORBIDDEN,
5485                    "helper, relay and retired connections cannot read activity",
5486                )?]);
5487            }
5488            channel_operations::ActivityReader::Legacy => None,
5489        };
5490        // A registered module connection already identifies its caller. Ignore
5491        // consumer_identity there so a module cannot borrow a mirror's identity.
5492        // Only separate consumer connections use the Direct/nonce trust boundary.
5493        let principal = match legacy {
5494            Some(principal) => principal,
5495            None => match self
5496                .forwarding
5497                .module_id_for_connection(ctx.connection_id)
5498                .map_err(RouterError::Forwarding)?
5499            {
5500                Some(module_id) => Ok(Principal::Reserved { module_id }),
5501                None => {
5502                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5503                        Ok(identity) => identity,
5504                        Err(_) => {
5505                            return Ok(vec![control_error_frame(
5506                                &frame,
5507                                ACTIVITY_MALFORMED,
5508                                "malformed activity read",
5509                            )?])
5510                        }
5511                    };
5512                    self.route_open_principal(
5513                        ctx.connection_id,
5514                        &frame,
5515                        identity.consumer_identity,
5516                    )?
5517                }
5518            },
5519        };
5520        let admitted = matches!(principal, Ok(Principal::Direct))
5521            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5522        if !admitted {
5523            return Ok(vec![control_error_frame(
5524                &frame,
5525                ACTIVITY_READ_FORBIDDEN,
5526                "activity reads require an operator or trusted mirror principal",
5527            )?]);
5528        }
5529        let Some(ledger) = &self.activity else {
5530            return Ok(vec![control_error_frame(
5531                &frame,
5532                ACTIVITY_UNAVAILABLE,
5533                "activity ledger unavailable",
5534            )?]);
5535        };
5536        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5537            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5538        {
5539            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5540                Ok(request) => ledger.query(request).await,
5541                Err(_) => Err(ACTIVITY_MALFORMED),
5542            };
5543            return match result {
5544                Ok(reply) => Ok(vec![control_response_body_frame(
5545                    &frame,
5546                    &reply,
5547                    ops::ACTIVITY_QUERY,
5548                )?]),
5549                Err(code) => Ok(vec![control_error_frame(
5550                    &frame,
5551                    code,
5552                    "activity query refused",
5553                )?]),
5554            };
5555        }
5556        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5557            Ok(request) => request,
5558            Err(_) => {
5559                return Ok(vec![control_error_frame(
5560                    &frame,
5561                    ACTIVITY_MALFORMED,
5562                    "malformed activity subscription",
5563                )?])
5564            }
5565        };
5566        let mut subscription = match ledger.subscribe(request.since).await {
5567            Ok(subscription) => subscription,
5568            Err(code) => {
5569                return Ok(vec![control_error_frame(
5570                    &frame,
5571                    code,
5572                    "activity subscription refused",
5573                )?])
5574            }
5575        };
5576        let key = (ctx.connection_id, frame.header.corr);
5577        let sink = ctx.egress.clone();
5578        let mut streams = self
5579            .activity_streams
5580            .lock()
5581            .unwrap_or_else(|p| p.into_inner());
5582        streams.retain(|_, task| !task.is_finished());
5583        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5584            return Ok(vec![control_error_frame(
5585                &frame,
5586                "duplicate_subscription",
5587                "activity subscription correlation id already in use",
5588            )?]);
5589        }
5590        let stream = async move {
5591            loop {
5592                let entry = if let Some(entry) = subscription.replay.pop_front() {
5593                    Some(entry)
5594                } else {
5595                    subscription.receiver.recv().await
5596                };
5597                let Some(entry) = entry else {
5598                    break;
5599                };
5600                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5601                    return;
5602                };
5603                let Ok(next) = Frame::build_with_version(
5604                    response_version(&frame),
5605                    FrameType::StreamData,
5606                    control_flags(),
5607                    0,
5608                    0,
5609                    frame.header.corr,
5610                    body,
5611                ) else {
5612                    return;
5613                };
5614                if sink.send(next).await.is_err() {
5615                    return;
5616                }
5617            }
5618            // Dropping a full subscriber's sender drains its accepted entries
5619            // before the terminal error, preserving their order on the wire.
5620            if let Some(code) = subscription.terminal_code() {
5621                if let Ok(end) =
5622                    control_error_frame(&frame, code, "activity subscriber fell behind")
5623                {
5624                    let _ = sink.send(end).await;
5625                }
5626            }
5627        };
5628        // The spawn's retirement revokes this connection's authority. End the
5629        // subscription then, rather than when the connection's close is
5630        // eventually processed or the next entry fails to send.
5631        let task = tokio::spawn(async move {
5632            match bound_spawn {
5633                Some(spawn) => {
5634                    tokio::select! {
5635                        () = stream => {}
5636                        () = spawn.wait_closed() => {}
5637                    }
5638                }
5639                None => stream.await,
5640            }
5641        });
5642        streams.insert(key, task.abort_handle());
5643        Ok(Vec::new())
5644    }
5645
5646    async fn handle_activity_record(
5647        &self,
5648        ctx: &RouteCtx,
5649        frame: Frame,
5650    ) -> Result<Vec<Frame>, RouterError> {
5651        use subc_control::{
5652            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5653            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5654        };
5655        let result = async {
5656            let module = self
5657                .forwarding
5658                .module_id_for_connection(ctx.connection_id)
5659                .ok()
5660                .flatten()
5661                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5662            let request: ActivityRecordRequest =
5663                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5664            crate::activity::validate(&module, &request)?;
5665            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5666            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5667            let at_ms = std::time::SystemTime::now()
5668                .duration_since(std::time::UNIX_EPOCH)
5669                .unwrap_or_default()
5670                .as_millis() as u64;
5671            ledger.record(module, request, actor, at_ms).await
5672        }
5673        .await;
5674        match result {
5675            Ok(entry) => Ok(vec![control_response_body_frame(
5676                &frame,
5677                &ActivityRecordResponse { seq: entry.seq },
5678                "activity.record",
5679            )?]),
5680            Err(code) => Ok(vec![control_error_frame(
5681                &frame,
5682                code,
5683                "activity recording refused",
5684            )?]),
5685        }
5686    }
5687
5688    fn activity_actor(
5689        &self,
5690        connection: ConnectionId,
5691        module: &str,
5692        on: Option<&subc_control::ActivityOn>,
5693    ) -> Result<subc_control::ActivityActor, &'static str> {
5694        use crate::forwarding::{DataRoute, DataRouteState};
5695        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5696        let principal = |id: &str| Principal::Reserved {
5697            module_id: id.to_owned(),
5698        };
5699        let mut actor = ActivityActor {
5700            principal: principal(module),
5701            scope_owner: None,
5702            agent_id: None,
5703            run_id: None,
5704            flow_id: None,
5705            project_root: None,
5706            workdir: None,
5707            project_id: None,
5708        };
5709        let scope = match on {
5710            None => return Ok(actor),
5711            Some(ActivityOn::Scope(scope)) => {
5712                let selector = subc_protocol::scope::ScopeSelector::new(
5713                    principal(module),
5714                    scope.scope_ref.clone(),
5715                    Some(scope.epoch),
5716                );
5717                self.scopes
5718                    .read()
5719                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5720                    .attribute(&principal(module), module, &selector, true)
5721                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5722            }
5723            Some(ActivityOn::Route(route)) => {
5724                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5725                    .forwarding
5726                    .lookup_data_route(connection, route.channel, route.epoch)
5727                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5728                else {
5729                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5730                };
5731                if binding.module_id != module {
5732                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5733                }
5734                actor.principal = binding.principal.clone();
5735                actor.project_root = binding
5736                    .project_root
5737                    .as_ref()
5738                    .map(|root| root.as_path().to_path_buf());
5739                let Some(bound) = &binding.scope else {
5740                    return Ok(actor);
5741                };
5742                let owner = principal(&bound.owner);
5743                let selector = subc_protocol::scope::ScopeSelector::new(
5744                    owner.clone(),
5745                    bound.scope_ref.clone(),
5746                    Some(bound.tag.scope_epoch),
5747                );
5748                let admitted = self
5749                    .scopes
5750                    .read()
5751                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5752                    .attribute(&owner, module, &selector, true)
5753                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5754                if admitted.tag != bound.tag {
5755                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5756                }
5757                admitted
5758            }
5759        };
5760        actor.scope_owner = Some(scope.stamp.owner);
5761        actor.agent_id = scope.stamp.attributes.agent_id;
5762        actor.run_id = scope.stamp.attributes.run_id;
5763        actor.flow_id = scope.stamp.attributes.flow_id;
5764        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5765        actor.project_id = scope.stamp.project_id;
5766        Ok(actor)
5767    }
5768
5769    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5770        let module_id = self
5771            .claims
5772            .binding(connection)
5773            .filter(|binding| {
5774                binding.consumer_live(connection) && binding.registration.authority.alive()
5775            })
5776            .map(|binding| binding.registration.module_id.clone())
5777            .or_else(|| {
5778                self.registry
5779                    .module_id_for_connection(connection)
5780                    .ok()
5781                    .flatten()
5782            });
5783        let principal = module_id
5784            .map(|module_id| format!("reserved:{module_id}"))
5785            .unwrap_or_else(|| "direct".to_owned());
5786        self.control_usage
5787            .lock()
5788            .unwrap_or_else(|poisoned| poisoned.into_inner())
5789            .record(op, &principal);
5790    }
5791
5792    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5793        self.refresh_capability_requirements();
5794        // A bare connection count is ambiguous between many clients holding a
5795        // route each and one client accumulating hundreds, so publish the
5796        // concentration alongside it. Route state is best-effort here: a
5797        // diagnostic endpoint must still answer if the forwarding lock is
5798        // contended.
5799        let mut counters = self.counters.snapshot();
5800        if let Some(obj) = counters.as_object_mut() {
5801            obj.insert(
5802                "control_usage".into(),
5803                self.control_usage
5804                    .lock()
5805                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5806                    .snapshot(),
5807            );
5808        }
5809        let losses = self.resource_tracker.loss_diagnostics();
5810        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5811            if let Some(obj) = counters.as_object_mut() {
5812                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5813            }
5814        }
5815        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5816            obj.insert(
5817                "activity_unparseable_lines".into(),
5818                ledger.read_errors().into(),
5819            );
5820            obj.insert(
5821                "activity_lifecycle_append_failures".into(),
5822                ledger.lifecycle_failures().into(),
5823            );
5824            obj.insert(
5825                "activity_started_digest_skips".into(),
5826                ledger.lifecycle_digest_skips().into(),
5827            );
5828        }
5829        if let (Ok((connections_with_routes, max)), Some(obj)) = (
5830            self.forwarding.client_route_concentration(),
5831            counters.as_object_mut(),
5832        ) {
5833            obj.insert(
5834                "client_connections_with_routes".into(),
5835                connections_with_routes.into(),
5836            );
5837            obj.insert("max_routes_on_one_connection".into(), max.into());
5838        }
5839        // A module that is being fast-refused and a module that is fine look
5840        // identical from a client that retries and succeeds, so name the open
5841        // breakers here. This rides the existing free-form counters object
5842        // rather than a new wire field, so no sibling that deserializes
5843        // `ServerDescribe` has to be rebuilt to keep reading it.
5844        if let (Some(open_breakers), Some(obj)) = (
5845            self.route_bind_breakers.open_snapshot(),
5846            counters.as_object_mut(),
5847        ) {
5848            obj.insert("route_bind_breakers_open".into(), open_breakers);
5849        }
5850        // A daemon whose local endpoint could not be bound keeps serving TCP,
5851        // and the connection file names no endpoint. Name the reason here, in
5852        // the free-form counters object, so an operator reading daemon facts
5853        // sees it without searching the log, and no wire field changes.
5854        if let (Some(reason), Some(obj)) = (
5855            self.local_endpoint_unavailable.clone(),
5856            counters.as_object_mut(),
5857        ) {
5858            obj.insert("local_endpoint_unavailable".into(), reason.into());
5859        }
5860        let response = ClientControlResponse::ServerDescribe {
5861            protocol_ver: PROTOCOL_VERSION,
5862            subc_ops: subc_ops(),
5863            capabilities: self.describe_capabilities(),
5864            connected_clients: self.connected_clients.count(),
5865            counters: Some(counters),
5866            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
5867            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
5868            capability_requirements: self.capability_requirement_statuses(),
5869            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
5870            config_path: self
5871                .rescan
5872                .as_ref()
5873                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
5874        };
5875        Ok(vec![control_response_body_frame(
5876            &frame,
5877            &response,
5878            "ClientControlResponse::ServerDescribe",
5879        )?])
5880    }
5881
5882    fn handle_catalog_list(
5883        &self,
5884        frame: Frame,
5885        module_id: Option<String>,
5886    ) -> Result<Vec<Frame>, RouterError> {
5887        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
5888        Ok(vec![Frame::build_with_version(
5889            response_version(&frame),
5890            FrameType::Response,
5891            control_flags(),
5892            0,
5893            0,
5894            frame.header.corr,
5895            body,
5896        )
5897        .map_err(RouterError::FrameBuild)?])
5898    }
5899
5900    #[cfg(test)]
5901    fn uncached_catalog_list(
5902        &self,
5903        corr: u64,
5904        module_id: Option<&str>,
5905    ) -> Result<ClientControlResponse, RouterError> {
5906        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
5907    }
5908
5909    fn catalog_list_snapshot(
5910        &self,
5911        corr: u64,
5912        module_id: Option<&str>,
5913        include_declarations: bool,
5914    ) -> Result<ClientControlResponse, RouterError> {
5915        let (generation, modules) = self
5916            .registry
5917            .list_modules_with_nonce_verification()
5918            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
5919        let entries = modules
5920            .into_iter()
5921            .filter(|(registration, _)| {
5922                module_id
5923                    .map(|wanted| registration.manifest.module_id == wanted)
5924                    .unwrap_or(true)
5925            })
5926            .map(|(registration, nonce_verified)| {
5927                let entry = self
5928                    .catalog_discovery_entry(&registration, include_declarations)
5929                    .map_err(|err| RouterError::backend(0, corr, err))?;
5930                let not_ready = self.not_ready_reason(&registration);
5931                let mut entry = entry;
5932                entry.roles = registration.manifest.provides;
5933                entry.control_ops = registration.control_ops;
5934                Ok(entry
5935                    .with_ready(not_ready.is_none())
5936                    .with_display_name(registration.manifest.display_name)
5937                    .with_not_ready(not_ready)
5938                    .with_module_version(Some(registration.manifest.module_version))
5939                    .with_provenance(registration.manifest.provenance)
5940                    .with_capabilities(registration.manifest.capabilities)
5941                    .with_self_signals(registration.manifest.self_signals)
5942                    .with_events(registration.manifest.events)
5943                    .with_operation_delivery(registration.manifest.operation_delivery)
5944                    .with_operation_payload(registration.manifest.operation_payload)
5945                    .with_flow_operations(registration.manifest.flow_operations)
5946                    .with_operation_deferral(registration.manifest.operation_deferral)
5947                    .with_confirm_operations(registration.manifest.confirm_operations)
5948                    .with_rich_ui(registration.manifest.rich_ui)
5949                    .with_role_declarations(registration.manifest.role_declarations)
5950                    .with_nonce_verified(nonce_verified))
5951            })
5952            .collect::<Result<Vec<_>, RouterError>>()?;
5953        Ok(ClientControlResponse::CatalogList {
5954            generation,
5955            modules: entries,
5956            subc_ops: subc_ops(),
5957        })
5958    }
5959
5960    /// The caller fields for a refusal that only has the raw request frame,
5961    /// such as the connection-level admission refusal sent before the request
5962    /// reaches [`Self::handle_route_open`].
5963    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
5964        let Ok(ClientControlRequest::RouteOpen {
5965            identity,
5966            consumer_identity,
5967            scope,
5968            ..
5969        }) = parse_client_control_request(&frame.body)
5970        else {
5971            return RouteOpenCaller::unknown();
5972        };
5973        let principal = self
5974            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
5975            .map(|attested| attested.principal);
5976        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
5977    }
5978
5979    fn route_open_principal(
5980        &self,
5981        connection_id: ConnectionId,
5982        frame: &Frame,
5983        consumer_identity: Option<ConsumerIdentity>,
5984    ) -> Result<Result<Principal, Frame>, RouterError> {
5985        let attested = self
5986            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
5987            .map(|attested| attested.principal);
5988        self.route_open_principal_attested(frame, consumer_identity, attested)
5989    }
5990
5991    /// [`Self::route_open_principal`] with `attested` already taken by
5992    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
5993    /// claim or launch nonce once.
5994    fn route_open_principal_attested(
5995        &self,
5996        frame: &Frame,
5997        consumer_identity: Option<ConsumerIdentity>,
5998        attested: Option<Principal>,
5999    ) -> Result<Result<Principal, Frame>, RouterError> {
6000        if let Some(principal) = attested {
6001            return Ok(Ok(principal));
6002        }
6003        Ok(Err(control_error_frame(
6004            frame,
6005            "bad_consumer_identity",
6006            consumer_identity.map_or_else(
6007                || "connection claim is no longer authorized for routes".to_string(),
6008                |identity| format!(
6009                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
6010                    identity.module_id
6011                ),
6012            ),
6013        )?))
6014    }
6015
6016    /// Ordinary `route.open` refusals go through here; admission and breaker
6017    /// refusals log separately with their capacity or breaker state. The daemon can
6018    /// attest which code it sent: without the event, a client's "the daemon
6019    /// refused me" and the daemon's own view could only be reconciled by
6020    /// argument. Malformed input (`invalid_project_root`) does not come here;
6021    /// rejecting a request that was never a valid open is not a refusal of one.
6022    #[allow(clippy::too_many_arguments)]
6023    fn route_open_refusal_frame(
6024        &self,
6025        ctx: &RouteCtx,
6026        caller: &RouteOpenCaller,
6027        frame: &Frame,
6028        module_id: &str,
6029        reason: &'static str,
6030        code: &'static str,
6031        message: impl Into<String>,
6032    ) -> Result<Frame, RouterError> {
6033        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
6034        let detail = if matches!(
6035            reason,
6036            "registration_not_active"
6037                | "supervisor_not_live"
6038                | "no_forwarding_connection"
6039                | "reloading"
6040        ) {
6041            // A planned restart, reload or swap is already replacing the
6042            // process; it does not need a slot in the crash-restart budget.
6043            let expected_back = (reason == "reloading").then_some(true);
6044            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
6045        } else {
6046            None
6047        };
6048        control_error_body_frame(
6049            frame,
6050            ErrorBody {
6051                code: code.to_string(),
6052                message: message.into(),
6053                detail,
6054            },
6055        )
6056    }
6057
6058    fn route_open_recovery_detail(
6059        &self,
6060        module_id: &str,
6061        corr: u64,
6062        detail: Option<serde_json::Value>,
6063        expected_back: Option<bool>,
6064    ) -> Result<Option<serde_json::Value>, RouterError> {
6065        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
6066            return Ok(detail);
6067        };
6068        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
6069        detail["state"] = serde_json::json!(status.state.to_string());
6070        if let Some(expected_back) = expected_back {
6071            detail["expected_back"] = serde_json::json!(expected_back);
6072        } else if let Some(module) = self.supervisor.get(module_id) {
6073            match module.will_recover_after_connection_loss() {
6074                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
6075                Err(err) => warn!(
6076                    %module_id,
6077                    error = %err,
6078                    "failed to read route.open recovery verdict; omitting expected_back"
6079                ),
6080            }
6081        }
6082        Ok(Some(detail))
6083    }
6084
6085    /// Answer a waiting `route.open` whose relayed bind was refused.
6086    ///
6087    /// `daemon_authored` is provenance, not a code match: the daemon
6088    /// synthesized the refusal itself (a drain, a late reply, a scope that
6089    /// ended mid-bind) or the module refused the bind with its own body. A
6090    /// daemon refusal carries the daemon-origin bit; a module's own
6091    /// rejection is relayed with the bit clear, so a module that refuses
6092    /// with `module_reloading` still cannot mint a daemon refusal.
6093    #[allow(clippy::too_many_arguments)]
6094    fn route_bind_rejection(
6095        &self,
6096        ctx: &RouteCtx,
6097        caller: &RouteOpenCaller,
6098        frame: &Frame,
6099        target_module_id: &str,
6100        body: ErrorBody,
6101        daemon_authored: bool,
6102    ) -> Result<Vec<Frame>, RouterError> {
6103        // The daemon's own commit re-check refused the bind because the
6104        // scope ended or changed after admission. The module accepted;
6105        // counting it as a module rejection would blame the module. This
6106        // branch only runs for daemon-synthesized bodies: a module that
6107        // refuses with a scope code is answered as a module rejection below.
6108        if daemon_authored {
6109            let scope_code = match body.code.as_str() {
6110                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
6111                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
6112                _ => None,
6113            };
6114            if let Some(code) = scope_code {
6115                self.observe_route_open_refusal(
6116                    ctx,
6117                    caller,
6118                    target_module_id,
6119                    "scope_changed_before_commit",
6120                    code,
6121                );
6122                return Ok(vec![control_error_body_frame(frame, body)?]);
6123            }
6124        }
6125        self.counters
6126            .increment_route_open_refused("module_rejected");
6127        info!(
6128            target: "control",
6129            code = "module_rejected",
6130            module_code = ?body.code,
6131            module_id = ?target_module_id,
6132            connection_id = ctx.connection_id.get(),
6133            principal = %caller.principal,
6134            scope = %caller.scope,
6135            harness = %caller.harness,
6136            "route.open refused"
6137        );
6138        let refusal = if daemon_authored {
6139            control_error_body_frame(frame, body)?
6140        } else {
6141            control_relayed_error_body_frame(frame, body)?
6142        };
6143        Ok(vec![refusal])
6144    }
6145
6146    /// Refuse a `route.open` because the target module's bind-relay breaker is
6147    /// open, without attempting the relay.
6148    ///
6149    /// The wire code is `module_timeout`, which is the truth (the module has
6150    /// not been answering binds) and which both SDKs already classify as
6151    /// retryable with capped backoff. Reusing it is what keeps this change out
6152    /// of both SDKs; the daemon-side distinction lives in the counter key
6153    /// instead.
6154    ///
6155    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6156    /// While a breaker is open this fires on every open to that module, and the
6157    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6158    /// produced 261 lines about a single module inside 3000 lines of daemon
6159    /// log. The rare transitions are logged at warn/info instead and the volume
6160    /// is carried by the counter, so the evidence survives without the flood.
6161    /// The debug line keeps a per-refusal record reachable for whoever turns
6162    /// the level up.
6163    #[allow(clippy::too_many_arguments)]
6164    fn route_open_breaker_refusal_frame(
6165        &self,
6166        ctx: &RouteCtx,
6167        caller: &RouteOpenCaller,
6168        frame: &Frame,
6169        module_id: &str,
6170        consecutive_timeouts: u32,
6171        retry_in: Duration,
6172        probe_in_flight: bool,
6173    ) -> Result<Frame, RouterError> {
6174        self.counters
6175            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6176        debug!(
6177            target: "control",
6178            code = "module_timeout",
6179            module_id = ?module_id,
6180            connection_id = ctx.connection_id.get(),
6181            principal = %caller.principal,
6182            scope = %caller.scope,
6183            harness = %caller.harness,
6184            consecutive_timeouts,
6185            retry_in_ms = retry_in.as_millis() as u64,
6186            probe_in_flight,
6187            "route.open refused by open bind-relay breaker"
6188        );
6189        // Say what a caller can act on. An open bind-relay breaker means the
6190        // module timed out accepting several new routes in a row. The module
6191        // is still running and its established routes keep working; only new
6192        // route.open requests are refused until the cooldown ends and one
6193        // test route (the probe) gets through. A message that only counts
6194        // failed relays reads as "the module is down" to a worker that sees it.
6195        let detail = if probe_in_flight {
6196            "one test route is already being tried; retry once it settles".to_string()
6197        } else {
6198            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6199        };
6200        control_error_frame(
6201            frame,
6202            "module_timeout",
6203            format!(
6204                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6205                 timed out in a row); {detail}; its established routes are unaffected"
6206            ),
6207        )
6208    }
6209
6210    /// `code` is daemon vocabulary and prints plainly; `module_id` is the
6211    /// requester's bytes (an unknown target is whatever the client sent) and
6212    /// is Debug-formatted so control characters land in the log escaped
6213    /// rather than as terminal sequences for whoever tails it.
6214    ///
6215    /// `reason` names the check that refused, because one wire code has
6216    /// several senders: after a module registers, `target_unavailable` can
6217    /// come from a missing role, an inactive registration, a supervisor that
6218    /// has not marked the process live, a missing forwarding connection, or a
6219    /// failed relay, and a log that records only the code cannot say which of
6220    /// them fired. It is a static, daemon-chosen label per branch, so it is
6221    /// safe to print plainly and stays a closed set.
6222    fn observe_route_open_refusal(
6223        &self,
6224        ctx: &RouteCtx,
6225        caller: &RouteOpenCaller,
6226        module_id: &str,
6227        reason: &'static str,
6228        code: &'static str,
6229    ) {
6230        self.counters.increment_route_open_refused(code);
6231        info!(
6232            target: "control",
6233            code,
6234            reason,
6235            module_id = ?module_id,
6236            connection_id = ctx.connection_id.get(),
6237            principal = %caller.principal,
6238            scope = %caller.scope,
6239            harness = %caller.harness,
6240            "route.open refused"
6241        );
6242        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6243            self.route_outages.record_not_serving(module_id, reason);
6244        }
6245    }
6246
6247    /// Record an ACCEPTED route.open.
6248    ///
6249    /// Refusals have been logged and counted since the attestation work; accepts
6250    /// were invisible, so the daemon knew every principal it stamped and wrote
6251    /// none of them down. The party that attests the identity was the only party
6252    /// not recording it, which left a credential vault unable to name the sender
6253    /// of a call that reached it (claustrum #43) and left the launch-nonce
6254    /// concurrency question unanswerable from the outside.
6255    ///
6256    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6257    /// `code`/`module_id`/`connection_id` returns both directions of the same
6258    /// decision rather than two shapes a reader has to join by hand.
6259    ///
6260    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6261    /// and the difference carries information rather than being an
6262    /// inconsistency. This line is only reachable after a successful bind to a
6263    /// REGISTERED module, so the value has already passed HELLO validation
6264    /// including the path-hazard refusal and cannot contain control bytes. A
6265    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6266    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6267    ///
6268    /// Bare is also what every other daemon line already emits (`module
6269    /// registered`, `configured module supervised`). Shipping `?module_id` here
6270    /// made this instrument the only one in the file whose ids did not answer
6271    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6272    /// line whose whole purpose is being grepped beside its sibling.
6273    ///
6274    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6275    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6276    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6277    /// one are recorded identically. A test written against that harness passes
6278    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6279    /// green assertion that cannot fail. The same limit applies to the escaping
6280    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6281    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6282    /// Fencing either needs the real formatter, not the capture layer.
6283    ///
6284    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6285    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6286    /// to record. The ephemeral port would decay within minutes and answer only a
6287    /// live question. The identity question is instead answered by counting
6288    /// distinct live connections presenting one module's `consumer_identity` --
6289    /// "is anyone else holding this secret" rather than "is this the right
6290    /// process".
6291    fn observe_route_open_accept(
6292        &self,
6293        ctx: &RouteCtx,
6294        module_id: &str,
6295        principal: &str,
6296        scope: &str,
6297    ) {
6298        self.route_outages.record_accepted(module_id);
6299        self.counters.increment_route_open_accepted(principal);
6300        debug!(
6301            target: "control",
6302            principal,
6303            module_id,
6304            connection_id = ctx.connection_id.get(),
6305            scope = %scope,
6306            "route.open accepted"
6307        );
6308    }
6309
6310    fn supervised_absent_route_open_refusal_frame(
6311        &self,
6312        ctx: &RouteCtx,
6313        caller: &RouteOpenCaller,
6314        frame: &Frame,
6315        module_id: &str,
6316        code: &'static str,
6317        status: &crate::supervise::ModuleStatus,
6318    ) -> Result<Frame, RouterError> {
6319        self.counters.increment_route_open_refused(code);
6320        info!(
6321            target: "control",
6322            code,
6323            reason = "supervised_not_registered",
6324            module_id = ?module_id,
6325            connection_id = ctx.connection_id.get(),
6326            principal = %caller.principal,
6327            scope = %caller.scope,
6328            harness = %caller.harness,
6329            state = %status.state,
6330            enabled = status.enabled,
6331            live = status.live,
6332            "route.open refused"
6333        );
6334        // A supervised module whose process has not registered is not
6335        // serving, whatever the reason; the supervisor knows this id, so it is
6336        // safe to track.
6337        self.route_outages
6338            .record_not_serving(module_id, "supervised_not_registered");
6339        let message = if let Some(pid) = status.waiting_for_previous_pid {
6340            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6341                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6342            })
6343        } else {
6344            format!(
6345                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6346                status.state, status.enabled, status.live
6347            )
6348        };
6349        // `module_warming` here means the process is starting, running or
6350        // being restarted and has not registered yet. Nothing has to be
6351        // restarted for it to serve, so the crash budget does not decide it.
6352        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6353        control_error_body_frame(
6354            frame,
6355            ErrorBody {
6356                code: code.to_string(),
6357                message,
6358                detail: self.route_open_recovery_detail(
6359                    module_id,
6360                    frame.header.corr,
6361                    None,
6362                    expected_back,
6363                )?,
6364            },
6365        )
6366    }
6367
6368    async fn handle_route_open(
6369        &self,
6370        ctx: &RouteCtx,
6371        frame: Frame,
6372        request: RouteOpenRequest,
6373        timings: &mut RouteOpenTimings,
6374    ) -> Result<Vec<Frame>, RouterError> {
6375        let RouteOpenRequest {
6376            target,
6377            mut identity,
6378            consumer_identity,
6379            consumer_capabilities,
6380            role_versions,
6381            busy_refusals,
6382            admission_facts,
6383            scope,
6384            accepts_close_reasons,
6385        } = request;
6386        let target_module_id = target_module_id(&target).to_string();
6387        timings.module_id.clone_from(&target_module_id);
6388        if self
6389            .registry
6390            .get_module_by_connection(ctx.connection_id)
6391            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6392            .is_some()
6393        {
6394            return Ok(vec![control_error_frame(
6395                &frame,
6396                "invalid_request",
6397                "module connections cannot open client routes",
6398            )?]);
6399        }
6400        debug!(
6401            connection_id = ctx.connection_id.get(),
6402            corr = frame.header.corr,
6403            module_id = %target_module_id,
6404            "handling route.open"
6405        );
6406
6407        // The caller's attested principal, requested scope and harness, for
6408        // every `route.open refused` line below. The connection's claim
6409        // binding or launch nonce is checked here, once, and the answer is
6410        // reused where the principal is enforced further down, so the order
6411        // of refusals is unchanged.
6412        let attested =
6413            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6414        let mut caller = RouteOpenCaller::new(
6415            attested.as_ref().map(|attested| &attested.principal),
6416            scope.as_ref(),
6417            &identity,
6418        );
6419
6420        // A malformed declaration is refused first, before anything about the
6421        // target is looked up: the same body would be refused against any
6422        // module, so the caller learns nothing by retrying or waiting. An empty
6423        // map declares nothing and travels as no field at all, so a provider
6424        // only ever sees a missing field or a non-empty one.
6425        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6426        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6427            self.observe_route_open_refusal(
6428                ctx,
6429                &caller,
6430                &target_module_id,
6431                "invalid_role_versions",
6432                error_codes::INVALID_REQUEST,
6433            );
6434            return Ok(vec![control_error_body_frame(
6435                &frame,
6436                ErrorBody {
6437                    code: error_codes::INVALID_REQUEST.to_string(),
6438                    message: error.to_string(),
6439                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6440                },
6441            )?]);
6442        }
6443
6444        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6445            if status.waiting_for_previous_pid.is_some() {
6446                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6447                    ctx,
6448                    &caller,
6449                    &frame,
6450                    &target_module_id,
6451                    "module_warming",
6452                    &status,
6453                )?]);
6454            }
6455        }
6456
6457        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6458        // opposite. Below, a caller learns whether a module is unregistered,
6459        // supervised-but-down (with state/enabled/live), or registered without the
6460        // requested role. Elsewhere that is an enumeration leak: a probe learning
6461        // the shape of a fleet it cannot otherwise see.
6462        //
6463        // It is not one here, and the reason is the ACCESS MODEL rather than
6464        // anything about these errors. Reaching route.open requires the
6465        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6466        // connection file, so any caller who completes it already runs as this
6467        // user -- and can read subc.jsonc for the module list and `ck module
6468        // status` for live state. The reply discloses nothing the caller cannot
6469        // read more easily from disk, while the precision is load-bearing:
6470        // `unknown_module` is retryable and a missing role is not.
6471        //
6472        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6473        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6474        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6475        let admission_registry = self
6476            .registry
6477            .route_admission_snapshot()
6478            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6479        let Some(registration) =
6480            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6481        else {
6482            if let Some((status, warming)) =
6483                self.supervisor_status(&target_module_id, frame.header.corr)?
6484            {
6485                // BEFORE the two availability codes below, because for a module
6486                // that speaks no subc wire both of them are false comfort: they
6487                // say "not right now" and are retried, and this module will
6488                // never register no matter how long the caller waits. The
6489                // absence here is the declaration being honoured, not a module
6490                // that is late.
6491                if status.protocol == ModuleProtocol::None {
6492                    return Ok(vec![self.route_open_refusal_frame(
6493                        ctx,
6494                        &caller,
6495                        &frame,
6496                        &target_module_id,
6497                        "protocol_none",
6498                        error_codes::MODULE_NO_PROTOCOL,
6499                        format!(
6500                            "module_id '{target_module_id}' is declared protocol: none; \
6501                             it speaks no subc wire and serves no routes"
6502                        ),
6503                    )?]);
6504                }
6505                let code = if warming {
6506                    "module_warming"
6507                } else {
6508                    "target_unavailable"
6509                };
6510                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6511                    ctx,
6512                    &caller,
6513                    &frame,
6514                    &target_module_id,
6515                    code,
6516                    &status,
6517                )?]);
6518            }
6519            if let Some(removed_ago_ms) =
6520                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6521            {
6522                return Ok(vec![self.route_open_refusal_frame(
6523                    ctx,
6524                    &caller,
6525                    &frame,
6526                    &target_module_id,
6527                    "removed",
6528                    error_codes::MODULE_REMOVED,
6529                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6530                )?]);
6531            }
6532            return Ok(vec![self.route_open_refusal_frame(
6533                ctx,
6534                &caller,
6535                &frame,
6536                &target_module_id,
6537                "not_registered",
6538                error_codes::UNKNOWN_MODULE,
6539                format!("module_id '{target_module_id}' is not registered"),
6540            )?]);
6541        };
6542
6543        // Best-effort only: registry readiness and forwarding reservation use
6544        // different locks, so a module can flip readiness between this read and
6545        // the relay. Modules must still tolerate an `on_bind` while not ready.
6546        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6547            .is_err()
6548        {
6549            self.counters
6550                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6551            info!(
6552                target: "control",
6553                code = error_codes::MODULE_WARMING,
6554                module_id = ?target_module_id,
6555                connection_id = ctx.connection_id.get(),
6556                principal = %caller.principal,
6557                scope = %caller.scope,
6558                harness = %caller.harness,
6559                reason = "declared_not_ready",
6560                "route.open refused"
6561            );
6562            // The module is registered but says it cannot take work, which is
6563            // an outage from the caller's side even though its process is up.
6564            self.route_outages
6565                .record_not_serving(&target_module_id, "declared_not_ready");
6566            // The registered process can declare itself ready without a
6567            // restart, so an exhausted crash budget does not prevent serving.
6568            return Ok(vec![control_error_body_frame(
6569                &frame,
6570                ErrorBody {
6571                    code: error_codes::MODULE_WARMING.to_string(),
6572                    message: format!(
6573                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6574                    ),
6575                    detail: self.route_open_recovery_detail(
6576                        &target_module_id,
6577                        frame.header.corr,
6578                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6579                        Some(true),
6580                    )?,
6581                },
6582            )?]);
6583        }
6584
6585        // Effective readiness, second half: a module that declares a capability
6586        // `need: required` is not routable while that capability has no
6587        // registered provider. It is enforced HERE, as a retryable routing
6588        // refusal, and deliberately not as spawn ordering or a boot block. The
6589        // module is still started and registered and can make its own calls;
6590        // spawn ordering is a promise that cannot be kept once a provider
6591        // crashes at runtime, and refusing to boot would stop the whole
6592        // machine, including the tools needed to fix its configuration.
6593        //
6594        // "Provided" is the evaluator's verdict, which counts a provider as
6595        // soon as it has REGISTERED, not once it is ready. Two modules that
6596        // require each other's capabilities are therefore both routable once
6597        // both register; counting readiness instead would deadlock them.
6598        //
6599        // Only new opens are refused. Routes already bound when a provider
6600        // goes away stay bound: nothing here tears them down, and the module
6601        // answers them as it can. Like the readiness read above this is
6602        // best-effort against a provider registering or leaving concurrently.
6603        if let Some(capability) = self.first_unprovided_required_capability_for(
6604            &registration.module_id,
6605            registration.capabilities.as_ref(),
6606        ) {
6607            self.counters
6608                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6609            info!(
6610                target: "control",
6611                code = error_codes::MODULE_WARMING,
6612                module_id = ?target_module_id,
6613                connection_id = ctx.connection_id.get(),
6614                principal = %caller.principal,
6615                scope = %caller.scope,
6616                harness = %caller.harness,
6617                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6618                capability = %capability,
6619                "route.open refused"
6620            );
6621            return Ok(vec![control_error_body_frame(
6622                &frame,
6623                ErrorBody {
6624                    code: error_codes::MODULE_WARMING.to_string(),
6625                    message: format!(
6626                        "module_id '{target_module_id}' requires capability '{capability}', \
6627                         which no registered module provides; retry"
6628                    ),
6629                    detail: Some(serde_json::json!({
6630                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6631                        "capability": capability,
6632                    })),
6633                },
6634            )?]);
6635        }
6636
6637        if !target_has_required_role(&target, &registration.roles) {
6638            return Ok(vec![self.route_open_refusal_frame(
6639                ctx,
6640                &caller,
6641                &frame,
6642                &target_module_id,
6643                "role_not_provided",
6644                "target_unavailable",
6645                format!("module_id '{target_module_id}' does not provide the requested target"),
6646            )?]);
6647        }
6648
6649        if registration.state != ChannelState::Active {
6650            return Ok(vec![self.route_open_refusal_frame(
6651                ctx,
6652                &caller,
6653                &frame,
6654                &target_module_id,
6655                "registration_not_active",
6656                "target_unavailable",
6657                format!("module_id '{target_module_id}' is not active"),
6658            )?]);
6659        }
6660
6661        if self
6662            .forwarding
6663            .module_is_draining(&target_module_id)
6664            .map_err(RouterError::Forwarding)?
6665        {
6666            return Ok(vec![self.route_open_refusal_frame(
6667                ctx,
6668                &caller,
6669                &frame,
6670                &target_module_id,
6671                "reloading",
6672                "module_reloading",
6673                format!("module_id '{target_module_id}' is reloading"),
6674            )?]);
6675        }
6676
6677        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6678            process_liveness.process_live(&target_module_id) == Some(false)
6679        }) {
6680            // A module the supervisor is restarting or reloading can still hold
6681            // a registration: the old process before its connection closes, or
6682            // a new one that registered while the supervisor was draining. The
6683            // forwarding table does not see that as draining, but the consumer
6684            // should still be told to retry soon, exactly as for the drain
6685            // above, rather than that the target is unavailable.
6686            if process_liveness.process_replacing(&target_module_id) {
6687                return Ok(vec![self.route_open_refusal_frame(
6688                    ctx,
6689                    &caller,
6690                    &frame,
6691                    &target_module_id,
6692                    "reloading",
6693                    "module_reloading",
6694                    format!("module_id '{target_module_id}' is reloading"),
6695                )?]);
6696            }
6697            return Ok(vec![self.route_open_refusal_frame(
6698                ctx,
6699                &caller,
6700                &frame,
6701                &target_module_id,
6702                "supervisor_not_live",
6703                "target_unavailable",
6704                format!("module_id '{target_module_id}' is not live"),
6705            )?]);
6706        }
6707
6708        if !self
6709            .forwarding
6710            .has_live_module_connection(&target_module_id)
6711            .map_err(RouterError::Forwarding)?
6712        {
6713            return Ok(vec![self.route_open_refusal_frame(
6714                ctx,
6715                &caller,
6716                &frame,
6717                &target_module_id,
6718                "no_forwarding_connection",
6719                "target_unavailable",
6720                format!("module_id '{target_module_id}' has no live forwarding connection"),
6721            )?]);
6722        }
6723
6724        if let Some(error) =
6725            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6726        {
6727            self.observe_route_open_refusal(
6728                ctx,
6729                &caller,
6730                &target_module_id,
6731                "op_not_allowed",
6732                "op_not_allowed",
6733            );
6734            return Ok(vec![error]);
6735        }
6736
6737        let principal = match (&attested, consumer_identity.is_some()) {
6738            // A claim-bound connection whose launch ended attests nothing,
6739            // and it must never fall back to opening as `direct`.
6740            (None, false) => {
6741                self.observe_route_open_refusal(
6742                    ctx,
6743                    &caller,
6744                    &target_module_id,
6745                    "registration_channel_closed",
6746                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6747                );
6748                return Ok(vec![control_error_frame(
6749                    &frame,
6750                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6751                    "the claim binding's launch has ended",
6752                )?]);
6753            }
6754            _ => match self.route_open_principal_attested(
6755                &frame,
6756                consumer_identity,
6757                attested.as_ref().map(|attested| attested.principal.clone()),
6758            )? {
6759                Ok(principal) => principal,
6760                Err(error) => {
6761                    self.observe_route_open_refusal(
6762                        ctx,
6763                        &caller,
6764                        &target_module_id,
6765                        "bad_consumer_identity",
6766                        "bad_consumer_identity",
6767                    );
6768                    return Ok(vec![error]);
6769                }
6770            },
6771        };
6772        let attested = attested.expect("an attested principal was resolved above");
6773        timings.principal = principal_label(&principal);
6774
6775        // The opener's spawn authority, read once here and carried with the
6776        // relay; nothing below reads its record again.
6777        let Ok(mut caller_capture) = attested.capture() else {
6778            self.observe_route_open_refusal(
6779                ctx,
6780                &caller,
6781                &target_module_id,
6782                "registration_channel_closed",
6783                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6784            );
6785            return Ok(vec![control_error_frame(
6786                &frame,
6787                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6788                "the opener's launch has ended",
6789            )?]);
6790        };
6791        // The caller-side checks below read the opener's own spawn: its
6792        // module from its record and its manifest from its own registration,
6793        // never another launch's active registration under the same id.
6794        let caller_module_id = match &attested.spawn {
6795            Some((record, _)) => Some(record.module_id().to_owned()),
6796            None => match &principal {
6797                Principal::Reserved { module_id } => Some(module_id.clone()),
6798                _ => None,
6799            },
6800        };
6801
6802        // Only Callosum can attest a production phone build. Consume the raw
6803        // claim here; opted-in targets receive only the honoured peer fact.
6804        let build_class = identity.build_class.take().filter(|build_class| {
6805            if caller_module_id.as_deref() == Some("callosum") {
6806                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6807            } else {
6808                if self
6809                    .build_class_warned
6810                    .lock()
6811                    .unwrap_or_else(|p| p.into_inner())
6812                    .insert(ctx.connection_id)
6813                {
6814                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6815                        "ignoring build_class from a non-Callosum opener");
6816                }
6817                false
6818            }
6819        });
6820
6821        // This is attested, control-plane policy for supervised module origins.
6822        // Keep it before route reservation and out of the opaque forwarding hot
6823        // path: data frames must never acquire a per-frame capability check.
6824        if let Some(opening_registration) = self.caller_registration(&attested, &admission_registry)
6825        {
6826            let opening_module_id = opening_registration.module_id.as_str();
6827            if let Some(capability) = denied_capability(
6828                opening_registration.capabilities.as_ref(),
6829                registration.capabilities.as_ref(),
6830            ) {
6831                warn!(
6832                    opening_module_id,
6833                    target_module_id,
6834                    capability,
6835                    "refusing route.open because an attested capability deny edge matches"
6836                );
6837                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6838                    &frame,
6839                    &target_module_id,
6840                    "capability_deny_edge",
6841                    "capability_forbidden",
6842                    format!(
6843                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
6844                    ),
6845                )?]);
6846            }
6847        }
6848
6849        if admission_facts.is_some() {
6850            let carrier_matches = caller_module_id.is_some()
6851                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
6852            if !carrier_matches {
6853                return Ok(vec![self.route_open_refusal_frame(
6854                    ctx,
6855                    &caller,
6856                    &frame,
6857                    &target_module_id,
6858                    "admission_facts_carrier_not_permitted",
6859                    "admission_facts_not_permitted",
6860                    "admission facts may only be carried by the configured reserved module",
6861                )?]);
6862            }
6863
6864            let target_allowed = self
6865                .admission_facts_targets
6866                .as_ref()
6867                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
6868            if !target_allowed {
6869                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6870                    &frame,
6871                    &target_module_id,
6872                    "admission_facts_target_not_listed",
6873                    "admission_facts_target_not_allowed",
6874                    format!(
6875                        "admission facts are not permitted for target module_id '{target_module_id}'"
6876                    ),
6877                )?]);
6878            }
6879
6880            // Keep the value opaque to subc. The downstream admission validator owns
6881            // schema and semantic checks; this daemon only enforces carrier authority
6882            // and the configured destination allowlist.
6883        }
6884
6885        // Scope admission, on the attested principal above and never on the
6886        // request body. The tag read here travels with the pending bind and is
6887        // compared with the published one at commit, so a sync between here
6888        // and the module's ack refuses the open instead of binding a stamp
6889        // that is no longer true.
6890        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
6891            None => (None, None, false),
6892            Some(selector) => {
6893                let owner_configured = match &selector.owner {
6894                    // A reserved owner counts as configured from before its
6895                    // process is spawned (see `SupervisorHandle::is_configured`).
6896                    // So an owner that has not synced its scopes yet is refused
6897                    // as retryable (`scope_not_synced`), not as one that will
6898                    // never sync.
6899                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
6900                    _ => false,
6901                };
6902                let mut scopes = self
6903                    .scopes
6904                    .write()
6905                    .unwrap_or_else(|poisoned| poisoned.into_inner());
6906                let admitted = crate::scopes::admission::admit_route(
6907                    &scopes,
6908                    &admission_registry,
6909                    &principal,
6910                    &target_module_id,
6911                    Some(selector),
6912                    owner_configured,
6913                    crate::scopes::admission::AdmissionMode::Open,
6914                )
6915                .map(|route| {
6916                    let admission = route.scope.expect("scoped admission");
6917                    let bound = scopes.reserve_bind(
6918                        &admission,
6919                        &principal,
6920                        ctx.connection_id,
6921                        selector.hold_presence,
6922                    );
6923                    (admission, bound)
6924                });
6925                match admitted {
6926                    Ok((admission, bound)) => {
6927                        (Some(bound), Some(admission.stamp), admission.stamp_required)
6928                    }
6929                    Err(refusal) => {
6930                        return Ok(vec![self.route_open_refusal_frame(
6931                            ctx,
6932                            &caller,
6933                            &frame,
6934                            &target_module_id,
6935                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6936                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6937                            refusal.message,
6938                        )?]);
6939                    }
6940                }
6941            }
6942        };
6943        // From here on a refusal names the scope by the stamp admission
6944        // issued, exactly as the `route.open accepted` line does.
6945        if let Some(stamp) = &scope_stamp {
6946            caller.scope = route_open_scope_label(stamp);
6947        }
6948        // Decided from the admitted stamp, before any field of it is stripped
6949        // for a target that lacks the capability to read it.
6950        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
6951            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
6952        }
6953
6954        // Allow resolvable missing-tail paths so a vanished directory does not
6955        // prevent reopening an existing session for cleanup. Binding does not
6956        // authorize creation of durable provider state.
6957        //
6958        // Resolve real paths rather than lexical cleanup: canonicalize the
6959        // longest existing ancestor and append the missing tail, retaining the
6960        // path's real existing ancestry even when a leaf is missing.
6961        timings.enter(RouteOpenPhase::ProjectRoot);
6962        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
6963            Ok(project) => project,
6964            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
6965        };
6966        timings.enter(RouteOpenPhase::Admission);
6967        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
6968            Ok(root) => root,
6969            Err(err) => {
6970                return Ok(vec![control_error_frame(
6971                    &frame,
6972                    "invalid_project_root",
6973                    err.to_string(),
6974                )?])
6975            }
6976        };
6977        // Compute compatibility project fields before stripping optional stamp
6978        // members. Preserve the canonical opener root and its project ID,
6979        // including absence. For rootless openers, use stamp workdir or `/`, and
6980        // opener ID, else stamp ID, else no ID. Emit these identity fields only
6981        // to targets without bind-no-project/v1.
6982        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
6983
6984        // Last gate before any relay work, and deliberately after the cheap
6985        // registry and availability checks above: those name a more precise
6986        // condition (unknown, removed, reloading) and a caller is better served
6987        // by the precise code than by this one.
6988        //
6989        // Everything below this point costs an egress permit, a reserved handle
6990        // pair and, if the module does not answer, the whole relay budget. The
6991        // reader no longer waits for that budget, so cap each target explicitly;
6992        // serial dispatch used to provide the accidental cap of one relay per
6993        // connection. Admission is a mutex-protected count and never waits.
6994        let _concurrency_guard = match self
6995            .route_bind_concurrency
6996            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
6997        {
6998            Ok(guard) => guard,
6999            Err(in_flight) => {
7000                return Ok(vec![self.route_open_target_capacity_refusal(
7001                    ctx,
7002                    &caller,
7003                    &frame,
7004                    &target_module_id,
7005                    in_flight,
7006                )?]);
7007            }
7008        };
7009
7010        // A module that has already burned the whole budget `threshold` times
7011        // in a row does not get to charge it again until a probe says it recovered.
7012        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
7013            RouteBindAdmission::Admitted { guard, probe } => {
7014                if probe {
7015                    info!(
7016                        module_id = %target_module_id,
7017                        connection_id = ctx.connection_id.get(),
7018                        "route.bind breaker half-open: admitting one probe"
7019                    );
7020                }
7021                guard
7022            }
7023            RouteBindAdmission::Refused {
7024                consecutive_timeouts,
7025                retry_in,
7026                probe_in_flight,
7027            } => {
7028                return Ok(vec![self.route_open_breaker_refusal_frame(
7029                    ctx,
7030                    &caller,
7031                    &frame,
7032                    &target_module_id,
7033                    consecutive_timeouts,
7034                    retry_in,
7035                    probe_in_flight,
7036                )?]);
7037            }
7038        };
7039
7040        let operator_app = self
7041            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
7042            .await;
7043        // Resolve the per-module budget here so the wait matches the operator's
7044        // intent for this specific target. A per-module override in
7045        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
7046        // daemons) wins over the daemon-wide default.
7047        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
7048        let relay_deadline = Instant::now() + route_bind_relay_timeout;
7049        let production_peer_build =
7050            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
7051        timings.enter(RouteOpenPhase::EgressReservation);
7052        let pending = match self
7053            .forwarding
7054            .begin_route_bind_relay_for(
7055                ctx.connection_id,
7056                ctx.egress.clone(),
7057                response_version(&frame),
7058                frame.header.corr,
7059                &target_module_id,
7060                principal.clone(),
7061                bound_scope,
7062                project_root,
7063                identity.harness.clone(),
7064                build_class,
7065                operator_app.clone(),
7066                crate::forwarding::RouteAuthority {
7067                    incarnation: self.supervisor.daemon_incarnation(),
7068                    caller: caller_capture
7069                        .as_ref()
7070                        .map(|caller| caller.authority.pair()),
7071                },
7072                relay_deadline,
7073                busy_refusals == Some(true),
7074                accepts_close_reasons,
7075            )
7076            .await
7077        {
7078            Ok(pending) => pending,
7079            Err(err) => {
7080                return Ok(vec![self.route_open_refusal_frame(
7081                    ctx,
7082                    &caller,
7083                    &frame,
7084                    &target_module_id,
7085                    "relay_reservation_failed",
7086                    forwarding_error_code(&err),
7087                    err.to_string(),
7088                )?])
7089            }
7090        };
7091        timings.enter(RouteOpenPhase::Admission);
7092        let crate::forwarding::PendingRouteBindRelay {
7093            endpoint,
7094            module_sink,
7095            negotiated_ver,
7096            client_channel,
7097            client_epoch,
7098            module_channel,
7099            module_epoch,
7100            corr: relay_corr,
7101            receiver,
7102        } = pending;
7103        let mut reservation =
7104            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
7105
7106        // Reserving egress can wait while a module reconnects or a swap cuts
7107        // over. Check the relay's captured connection, not the earlier by-id
7108        // lookup: the original module's flow/run capabilities cannot authorize
7109        // its replacement. The captured sink stays bound to that connection.
7110        let relay_registration = self
7111            .registry
7112            .route_registration_by_connection(endpoint.connection_id)
7113            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7114        let relay_capabilities = relay_registration
7115            .as_ref()
7116            .and_then(|registration| registration.capabilities.as_ref());
7117        if let Some(selector) = &scope {
7118            // Egress reservation may wait across a scope update. Recheck the
7119            // proof against the current record before sending the captured bind.
7120            if let Err(refusal) = self
7121                .scopes
7122                .read()
7123                .unwrap_or_else(|poisoned| poisoned.into_inner())
7124                .check_bind_proof(&principal, selector)
7125            {
7126                reservation.release_and_disarm();
7127                return Ok(vec![self.route_open_refusal_frame(
7128                    ctx,
7129                    &caller,
7130                    &frame,
7131                    &target_module_id,
7132                    refusal.code,
7133                    refusal.code,
7134                    refusal.message,
7135                )?]);
7136            }
7137        }
7138        if let Some(stamp) = scope_stamp.as_ref() {
7139            if let Err(refusal) = crate::scopes::check_target_required_stamp(
7140                stamp_required,
7141                &target_module_id,
7142                relay_capabilities,
7143            )
7144            .and_then(|()| {
7145                crate::scopes::check_target_flow_support(
7146                    stamp,
7147                    &target_module_id,
7148                    relay_capabilities,
7149                )
7150            })
7151            .and_then(|()| {
7152                crate::scopes::check_target_agent_run_support(
7153                    stamp,
7154                    &target_module_id,
7155                    relay_capabilities,
7156                )
7157            }) {
7158                reservation.release_and_disarm();
7159                return Ok(vec![self.route_open_refusal_frame(
7160                    ctx,
7161                    &caller,
7162                    &frame,
7163                    &target_module_id,
7164                    refusal.code,
7165                    refusal.code,
7166                    refusal.message,
7167                )?]);
7168            }
7169        }
7170
7171        // Older readers may reject unknown fields. Select optional fields from
7172        // the captured endpoint's declaration, including on unscoped binds.
7173        if scope_stamp
7174            .as_ref()
7175            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7176            && !crate::scopes::target_supports_federated(relay_capabilities)
7177        {
7178            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7179            scope_stamp = None;
7180        }
7181        if !relay_capabilities.is_some_and(|caps| {
7182            caps.provides
7183                .iter()
7184                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7185        }) {
7186            if let Some(stamp) = scope_stamp.as_mut() {
7187                stamp.workdir = None;
7188                stamp.project_id = None;
7189            }
7190        }
7191        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7192        // attribution. The run gate above has already required the target to
7193        // declare `worker-runs/v1`, which promises to read both
7194        // `on_behalf_of_agent` and `call_mode`.
7195        let worker_run = scope_stamp
7196            .as_ref()
7197            .is_some_and(crate::scopes::is_worker_run)
7198            && relay_capabilities.is_some_and(|caps| {
7199                caps.provides
7200                    .iter()
7201                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7202            });
7203        if !worker_run
7204            && !relay_capabilities.is_some_and(|caps| {
7205                caps.provides
7206                    .iter()
7207                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7208            })
7209        {
7210            if let Some(stamp) = scope_stamp.as_mut() {
7211                stamp.attributes.on_behalf_of_agent = None;
7212            }
7213        }
7214        if !relay_capabilities.is_some_and(|caps| {
7215            caps.provides
7216                .iter()
7217                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7218        }) {
7219            if let Some(stamp) = scope_stamp.as_mut() {
7220                stamp.attributes.flow_version = None;
7221                stamp.attributes.flow_code_hash = None;
7222                stamp.attributes.flow_install_id = None;
7223            }
7224        }
7225        let call_mode = if worker_run
7226            || relay_capabilities
7227                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7228        {
7229            Some(derive_call_mode(scope_stamp.as_ref()))
7230        } else {
7231            if let Some(stamp) = scope_stamp.as_mut() {
7232                stamp.expires_at_ms = None;
7233            }
7234            None
7235        };
7236
7237        debug!(
7238            connection_id = ctx.connection_id.get(),
7239            client_channel,
7240            client_epoch,
7241            module_channel,
7242            module_epoch,
7243            "reserved route handle pair"
7244        );
7245        // Rendered BEFORE the move into the relay, because the accept arm below
7246        // is where it is logged and the principal is gone by then.
7247        let route_principal_label = principal_label(&principal);
7248        let relay = ModuleControlRequest::RouteBind {
7249            route_channel: module_channel,
7250            epoch: module_epoch,
7251            target,
7252            identity,
7253            principal: Some(principal),
7254            consumer_capabilities,
7255            role_versions,
7256            admission_facts,
7257            scope: scope_stamp,
7258            call_mode,
7259        };
7260        let peer = RouteBindPeer::new()
7261            .with_observed_peer(
7262                relay_capabilities
7263                    .is_some_and(|caps| {
7264                        caps.provides
7265                            .iter()
7266                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7267                    })
7268                    .then(|| {
7269                        self.observed_peers
7270                            .lock()
7271                            .unwrap_or_else(|p| p.into_inner())
7272                            .get(&ctx.connection_id)
7273                            .cloned()
7274                            .unwrap_or_else(ObservedPeer::unobserved)
7275                    }),
7276            )
7277            .with_operator_app(
7278                self.connection_operator_app(operator_app.as_ref())
7279                    .filter(|_| {
7280                        relay_capabilities.is_some_and(|caps| {
7281                            caps.provides
7282                                .iter()
7283                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7284                        })
7285                    }),
7286            )
7287            .with_caller(caller_for_target(
7288                caller_capture.as_ref(),
7289                relay_capabilities,
7290                &target_module_id,
7291            ))
7292            .with_peer_build(
7293                (production_peer_build
7294                    && relay_capabilities.is_some_and(|caps| {
7295                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7296                    }))
7297                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7298            );
7299        let relay_body = crate::bind_compat::encode_bind(
7300            &relay,
7301            &peer,
7302            &legacy_bind_project,
7303            relay_capabilities,
7304        )
7305        .map_err(|err| {
7306            RouterError::backend(
7307                0,
7308                frame.header.corr,
7309                format!("failed to encode route.bind request: {err}"),
7310            )
7311        })?;
7312        let relay_frame = Frame::build_with_version(
7313            negotiated_ver,
7314            FrameType::Request,
7315            control_flags(),
7316            0,
7317            0,
7318            relay_corr,
7319            relay_body,
7320        )
7321        .map_err(RouterError::FrameBuild)?;
7322
7323        timings.enter(RouteOpenPhase::BindSend);
7324        let sent = module_sink.send(relay_frame).await;
7325        timings.enter(RouteOpenPhase::Admission);
7326        if let Err(err) = sent {
7327            reservation.release_and_disarm();
7328            return Ok(vec![self.route_open_refusal_frame(
7329                ctx,
7330                &caller,
7331                &frame,
7332                &target_module_id,
7333                "relay_send_failed",
7334                "target_unavailable",
7335                err.to_string(),
7336            )?]);
7337        }
7338
7339        #[cfg(test)]
7340        if let Some(hold) = &self.route_bind_relay_sent_hold {
7341            // First wait: tell the test the bind is queued. Second wait: stay
7342            // here until the test has driven whatever it wants to happen
7343            // between queueing the bind and marking it enqueued.
7344            hold.wait().await;
7345            hold.wait().await;
7346        }
7347
7348        // A missing relay is not by itself an abandoned bind: the module may
7349        // already have acked it and the route may be committed. Only a relay
7350        // dropped without any module reply needs this GOODBYE; one a reply
7351        // settled has already had its GOODBYE decided by the reply path.
7352        if self
7353            .forwarding
7354            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7355            .map_err(RouterError::Forwarding)?
7356            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7357        {
7358            self.send_abandoned_route_bind_goodbye(
7359                &module_sink,
7360                negotiated_ver,
7361                module_channel,
7362                module_epoch,
7363            );
7364        }
7365
7366        timings.enter(RouteOpenPhase::BindAckWait);
7367        let outcome = timeout_at(relay_deadline, receiver).await;
7368        timings.enter(RouteOpenPhase::Admission);
7369        match outcome {
7370            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7371                reservation.disarm();
7372                if breaker.record_accepted() {
7373                    info!(
7374                        module_id = %target_module_id,
7375                        "route.bind breaker closed: the probe was accepted"
7376                    );
7377                }
7378                self.observe_route_open_accept(
7379                    ctx,
7380                    &target_module_id,
7381                    &route_principal_label,
7382                    &caller.scope,
7383                );
7384                Ok(Vec::new())
7385            }
7386            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7387                reservation.release_and_disarm();
7388                // A module that says no in microseconds is healthy. Rejection
7389                // is a different condition with its own refusal and must not
7390                // move the breaker.
7391                breaker.record_inconclusive();
7392                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7393            }
7394            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7395                reservation.release_and_disarm();
7396                breaker.record_inconclusive();
7397                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7398            }
7399            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7400                reservation.release_and_disarm();
7401                breaker.record_inconclusive();
7402                // Fires when the module's connection closes while a relayed
7403                // bind is pending -- typically a caller racing a module restart
7404                // whose bind was relayed BEFORE the drain mark went up. Logged
7405                // because the caller sees only its own error and the fleet has
7406                // already spent one diagnosis round unable to tell this arm
7407                // from a relay timeout without daemon-side evidence.
7408                tracing::warn!(
7409                    module_id = %target_module_id,
7410                    "route.bind relay abandoned: {message}"
7411                );
7412                Ok(vec![self.route_open_refusal_frame(
7413                    ctx,
7414                    &caller,
7415                    &frame,
7416                    &target_module_id,
7417                    "relay_abandoned",
7418                    "target_unavailable",
7419                    message,
7420                )?])
7421            }
7422            Ok(Err(_)) => {
7423                reservation.release_and_disarm();
7424                breaker.record_inconclusive();
7425                Ok(vec![self.route_open_refusal_frame(
7426                    ctx,
7427                    &caller,
7428                    &frame,
7429                    &target_module_id,
7430                    "relay_waiter_canceled",
7431                    "target_unavailable",
7432                    "route.bind relay waiter was canceled before the module responded",
7433                )?])
7434            }
7435            Err(_) => {
7436                reservation.release_and_disarm();
7437                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7438                // answer at all is the one condition a fast refusal can
7439                // usefully stand in for; every other arm already answered.
7440                if let Some(opened) = breaker.record_timeout(
7441                    self.route_bind_breaker_threshold,
7442                    self.route_bind_breaker_cooldown,
7443                ) {
7444                    warn!(
7445                        module_id = %target_module_id,
7446                        consecutive_timeouts = opened.consecutive_timeouts,
7447                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7448                        reopened_after_probe = opened.reopened_after_probe,
7449                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7450                    );
7451                }
7452                // The generous budget just burned to no answer: the module is
7453                // registered and its connection is up, but its bind handler sat
7454                // on the ack for the full budget (warm-on-bind, cold configure,
7455                // or a wedged handler). Every earlier unavailability shape
7456                // fast-refuses BEFORE the relay, so this arm firing means the
7457                // slowness is module-side -- log it so the per-module timeline
7458                // is reconstructable without client audit rows.
7459                tracing::warn!(
7460                    module_id = %target_module_id,
7461                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7462                    "route.bind relay timed out: module did not ack within budget"
7463                );
7464                Ok(vec![self.route_open_refusal_frame(
7465                    ctx,
7466                    &caller,
7467                    &frame,
7468                    &target_module_id,
7469                    "relay_timed_out",
7470                    "module_timeout",
7471                    format!(
7472                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7473                        route_bind_relay_timeout
7474                    ),
7475                )?])
7476            }
7477        }
7478    }
7479
7480    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7481        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7482            snapshot: self.supervisor.spawn_snapshot(),
7483        };
7484        Ok(vec![control_response_body_frame(
7485            &frame,
7486            &response,
7487            "ClientControlResponse::SupervisorSpawnSnapshot",
7488        )?])
7489    }
7490
7491    fn handle_supervisor_spawn_subscribe(
7492        &self,
7493        ctx: &RouteCtx,
7494        frame: Frame,
7495        since: Option<SpawnCursor>,
7496    ) -> Result<Vec<Frame>, RouterError> {
7497        match self.supervisor.subscribe_spawns(
7498            ctx.connection_id,
7499            frame.header.corr,
7500            response_version(&frame),
7501            since,
7502            ctx.egress.clone(),
7503        ) {
7504            Ok(()) => Ok(Vec::new()),
7505            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7506                Ok(vec![control_error_body_frame(
7507                    &frame,
7508                    ErrorBody {
7509                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7510                        message: "spawn cursor belongs to a different daemon incarnation"
7511                            .to_string(),
7512                        detail: Some(serde_json::json!({
7513                            "current_daemon_incarnation": current
7514                        })),
7515                    },
7516                )?])
7517            }
7518            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7519                &frame,
7520                ErrorBody {
7521                    code: "spawn_cursor_too_old".to_string(),
7522                    message: "spawn cursor predates the retained event ring".to_string(),
7523                    detail: Some(serde_json::json!({
7524                        "oldest_retained_cursor": oldest
7525                    })),
7526                },
7527            )?]),
7528            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7529                0,
7530                frame.header.corr,
7531                format!("failed to open supervisor spawn subscription: {error}"),
7532            )),
7533        }
7534    }
7535
7536    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7537        // Status/configuration snapshots may wait on synchronous supervisor
7538        // locks. Keep that work off the connection's async runtime thread.
7539        let handler = self.clone();
7540        let runtime = tokio::runtime::Handle::current();
7541        // The blocking pool does not inherit the control request's tracing
7542        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7543        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7544        let corr = frame.header.corr;
7545        tokio::task::spawn_blocking(move || {
7546            runtime.block_on(
7547                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7548                    .with_subscriber(subscriber),
7549            )
7550        })
7551        .await
7552        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7553    }
7554
7555    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7556        use crate::config_gate::runtime::ApprovedDaemonView;
7557        let publication = self
7558            .config_runtime
7559            .as_ref()
7560            .and_then(|owner| owner.polled_snapshot().ok());
7561        let approved = publication
7562            .as_ref()
7563            .map(|view| view.approved_daemon.clone())
7564            .unwrap_or_else(|| {
7565                if self.config_runtime.is_some() {
7566                    ApprovedDaemonView::Unavailable
7567                } else {
7568                    ApprovedDaemonView::NotStamped
7569                }
7570            });
7571        let generation = self
7572            .registry
7573            .generation()
7574            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7575        let supervised = self.supervisor.list();
7576        let mut statuses = BTreeMap::new();
7577        let mut not_running = BTreeSet::new();
7578        for module in &supervised {
7579            let status = module.status_for_control("list").map_err(|err| {
7580                RouterError::backend(
7581                    0,
7582                    frame.header.corr,
7583                    format!("failed to read supervisor status: {err}"),
7584                )
7585            })?;
7586            if !status.enabled || !status.process_alive {
7587                not_running.insert(module.module_id().to_owned());
7588            }
7589            statuses.insert(module.module_id().to_owned(), status);
7590        }
7591        // Legacy per-process diagnostics keep their shared optional budget.
7592        // The cached tree and accounting export below does not spend it.
7593        let mut process_resources = BTreeMap::new();
7594        for module in &supervised {
7595            process_resources.insert(
7596                module.module_id().to_owned(),
7597                crate::subtree_resources::read_process(module.clone()).await,
7598            );
7599        }
7600        // Image evidence uses the same optional deadline, but an exhausted
7601        // budget must not suppress the committed resource view.
7602        let mut image_readings = BTreeMap::new();
7603        for module in &supervised {
7604            image_readings.insert(
7605                module.module_id().to_owned(),
7606                module.running_image_agreement().await,
7607            );
7608        }
7609        let readings = self.resource_tracker.list(supervised.clone());
7610        let mut modules = Vec::new();
7611        for module in supervised {
7612            let status = statuses
7613                .remove(module.module_id())
7614                .expect("each supervised module has a status snapshot");
7615            let (configured, _) = module.configuration().map_err(|err| {
7616                RouterError::backend(
7617                    0,
7618                    frame.header.corr,
7619                    format!("failed to read module configuration: {err}"),
7620                )
7621            })?;
7622            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7623                RouterError::backend(
7624                    0,
7625                    frame.header.corr,
7626                    format!("failed to read retry time: {err}"),
7627                )
7628            })?;
7629            let image = image_readings
7630                .remove(module.module_id())
7631                .expect("each supervised module has an image snapshot");
7632            let resources = process_resources.remove(module.module_id());
7633            let mut verdict =
7634                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7635            verdict.spec = Some(launch_spec_agreement(
7636                &configured,
7637                status.process_alive,
7638                status.launch_spec_digest.as_ref(),
7639            ));
7640            let pending_reload = Some(verdict);
7641            let pending_entry = match &approved {
7642                ApprovedDaemonView::Approved { config, .. } => config
7643                    .modules
7644                    .iter()
7645                    .find(|m| m.module_id == module.module_id()),
7646                _ => None,
7647            };
7648            let pending = self
7649                .pending_module_fields(
7650                    &module,
7651                    pending_entry,
7652                    false,
7653                    Self::registration_channel_in_force(
7654                        publication
7655                            .as_ref()
7656                            .and_then(|view| view.registration_declaration(module.module_id()))
7657                            .as_deref(),
7658                        pending_entry.map(|entry| entry.registration_channel),
7659                    ),
7660                )
7661                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7662            let script = configured.script.as_ref().map(|entry| {
7663                let approved = self
7664                    .config_runtime
7665                    .as_ref()
7666                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7667                crate::supervise::script::status(entry, approved.as_ref())
7668            });
7669            let configured_enabled = match &approved {
7670                ApprovedDaemonView::Approved {
7671                    config: approved, ..
7672                } => approved
7673                    .modules
7674                    .iter()
7675                    .find(|module| module.module_id == status.module_id)
7676                    .map(|module| module.enabled),
7677                ApprovedDaemonView::NotStamped => self
7678                    .capability_evaluator
7679                    .configured_enabled(&status.module_id),
7680                ApprovedDaemonView::Unavailable => None,
7681            };
7682            let admission_refused = status
7683                .admission_refused
7684                .clone()
7685                .filter(|_| status.enabled && !status.process_alive)
7686                .filter(|_| {
7687                    publication
7688                        .as_ref()
7689                        .and_then(|view| view.registration_declaration(&status.module_id))
7690                        .as_deref()
7691                        == Some("undeclared")
7692                });
7693            // Keep the retired policy field on the wire for one release so
7694            // existing status consumers still receive the platform policy.
7695            let mut entry = SupervisorEntry::new(
7696                status.module_id,
7697                status.state.to_string(),
7698                status.enabled,
7699                status.live,
7700                status.health.status,
7701            )
7702            .with_configured_enabled(configured_enabled)
7703            .with_script(script)
7704            .with_admission_refused(admission_refused)
7705            .with_next_retry_at_ms(next_retry_at_ms)
7706            .with_launch_nonce_env(Some(!cfg!(unix)))
7707            .with_launch_nonce_source(status.launch_nonce_source)
7708            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7709            .with_protocol(status.protocol)
7710            .with_pending_reload(pending_reload)
7711            .with_last_probe_ms(status.health.last_probe_ms)
7712            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7713            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7714            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7715            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7716            .with_restart_count(Some(status.restart_count))
7717            .with_max_restarts(Some(status.max_restarts))
7718            .with_lifetime_restarts(Some(status.lifetime_restarts))
7719            .with_spawn_generation(Some(status.spawn_generation))
7720            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7721            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7722            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7723            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7724            .with_resources(resources);
7725            entry.pending = pending;
7726            modules.push(entry);
7727        }
7728        for module in &mut modules {
7729            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7730                module.tree = tree.clone();
7731                module.cpu_last_hour = hour.clone();
7732            }
7733            module.tree_unavailable = readings
7734                .reasons
7735                .get(&module.module_id)
7736                .map(|reason| (*reason).to_owned());
7737            if module.tree.is_none() {
7738                module.tree_unavailable = Some(
7739                    if not_running.contains(&module.module_id) {
7740                        "not_running"
7741                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7742                        reason
7743                    } else {
7744                        "not_yet_measured"
7745                    }
7746                    .to_owned(),
7747                );
7748            }
7749        }
7750        let response = ClientControlResponse::SupervisorList {
7751            generation,
7752            modules,
7753            daemon: readings.daemon,
7754            agent_commands: readings.agent_commands,
7755        };
7756        Ok(vec![control_response_body_frame(
7757            &frame,
7758            &response,
7759            "ClientControlResponse::SupervisorList",
7760        )?])
7761    }
7762
7763    fn handle_supervisor_stderr_tail(
7764        &self,
7765        frame: Frame,
7766        module_id: String,
7767        max_lines: Option<u32>,
7768        max_bytes: Option<u32>,
7769    ) -> Result<Vec<Frame>, RouterError> {
7770        let Some(module) = self.supervisor.get(&module_id) else {
7771            return Ok(vec![control_error_frame(
7772                &frame,
7773                "unknown_module",
7774                format!("module_id '{module_id}' is not supervised"),
7775            )?]);
7776        };
7777
7778        let snapshot = module.stderr_tail(
7779            max_lines.map(|value| value as usize),
7780            max_bytes.map(|value| value as usize),
7781        );
7782
7783        let response = ClientControlResponse::SupervisorStderrTail {
7784            module_id,
7785            tail: StderrTail {
7786                capture: match snapshot.capture {
7787                    CaptureState::Captured => StderrCaptureState::Captured,
7788                    CaptureState::Incomplete { reason } => {
7789                        StderrCaptureState::Incomplete { reason }
7790                    }
7791                    CaptureState::NotCaptured { reason } => {
7792                        StderrCaptureState::NotCaptured { reason }
7793                    }
7794                },
7795                entries: snapshot
7796                    .entries
7797                    .into_iter()
7798                    .map(|entry| match entry {
7799                        TailEntry::Line {
7800                            text,
7801                            truncated,
7802                            at_ms,
7803                        } => StderrTailEntry::Line {
7804                            text,
7805                            truncated,
7806                            at_ms,
7807                        },
7808                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7809                    })
7810                    .collect(),
7811                dropped_lines: snapshot.dropped_lines,
7812            },
7813        };
7814        Ok(vec![control_response_body_frame(
7815            &frame,
7816            &response,
7817            "ClientControlResponse::SupervisorStderrTail",
7818        )?])
7819    }
7820
7821    async fn observe_control_wait<F: std::future::Future>(
7822        &self,
7823        ctx: &RouteCtx,
7824        target: Option<&str>,
7825        kind: &'static str,
7826        future: F,
7827    ) -> F::Output {
7828        self.counters
7829            .observe_reader_wait(
7830                || {
7831                    let module = self
7832                        .forwarding
7833                        .module_id_for_connection(ctx.connection_id)
7834                        .ok()
7835                        .flatten();
7836                    let principal = if module.is_some() { "module" } else { "direct" };
7837                    (
7838                        self.resolve_reader_wait_target(kind, target)
7839                            .or(module)
7840                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7841                        principal.into(),
7842                    )
7843                },
7844                kind,
7845                future,
7846            )
7847            .await
7848    }
7849
7850    /// Resolve the reader-wait module ID only from supervisor or registry
7851    /// records; never attribute a wait from the request selector alone.
7852    pub(crate) fn resolve_reader_wait_target(
7853        &self,
7854        op: &str,
7855        selector: Option<&str>,
7856    ) -> Option<String> {
7857        let selector = selector?;
7858        match op {
7859            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7860                .supervisor
7861                .get(selector)
7862                .map(|module| module.module_id().to_owned()),
7863            ops::SUPERVISOR_HEALTH_PROBE => self
7864                .registry
7865                .get_module(selector)
7866                .ok()
7867                .flatten()
7868                .map(|registration| registration.manifest.module_id),
7869            _ => None,
7870        }
7871    }
7872
7873    async fn handle_supervisor_terminals(
7874        &self,
7875        ctx: &RouteCtx,
7876        frame: Frame,
7877        module_id: String,
7878    ) -> Result<Vec<Frame>, RouterError> {
7879        let Some(module) = self.supervisor.get(&module_id) else {
7880            return Ok(vec![control_error_frame(
7881                &frame,
7882                "unknown_module",
7883                format!("module_id '{module_id}' is not supervised"),
7884            )?]);
7885        };
7886
7887        // The journal read runs on a blocking thread: it can be megabytes of
7888        // file I/O and must not occupy a runtime worker.
7889        let terminals = self
7890            .observe_control_wait(
7891                ctx,
7892                Some(module.module_id()),
7893                ops::SUPERVISOR_TERMINALS,
7894                module.read_durable_terminal_history(),
7895            )
7896            .await
7897            .map_err(|error| {
7898                RouterError::backend(
7899                    0,
7900                    frame.header.corr,
7901                    format!("failed to read terminal history: {error}"),
7902                )
7903            })?;
7904        let response = ClientControlResponse::SupervisorTerminals {
7905            module_id,
7906            terminals,
7907        };
7908        Ok(vec![control_response_body_frame(
7909            &frame,
7910            &response,
7911            "ClientControlResponse::SupervisorTerminals",
7912        )?])
7913    }
7914
7915    fn handle_supervisor_routes(
7916        &self,
7917        frame: Frame,
7918        module_id: Option<String>,
7919    ) -> Result<Vec<Frame>, RouterError> {
7920        let modules = self
7921            .forwarding
7922            .route_census(module_id.as_deref())
7923            .map_err(RouterError::Forwarding)?
7924            .into_iter()
7925            .map(|(module_id, routes)| SupervisorRouteModule {
7926                module_id,
7927                routes: routes
7928                    .into_iter()
7929                    .map(|route| SupervisorRoute {
7930                        consumer: match route.principal {
7931                            Principal::Reserved { module_id } => {
7932                                SupervisorRouteConsumer::Reserved { module_id }
7933                            }
7934                            Principal::Direct | Principal::Unverified => {
7935                                SupervisorRouteConsumer::Direct {
7936                                    connection_id: route.goodbye_target.connection_id.get(),
7937                                }
7938                            }
7939                        },
7940                        age_ms: Instant::now()
7941                            .saturating_duration_since(route.bound_at)
7942                            .as_millis()
7943                            .try_into()
7944                            .unwrap_or(u64::MAX),
7945                        draining: route.draining,
7946                        drain_reason: route.drain_reason,
7947                    })
7948                    .collect(),
7949            })
7950            .collect();
7951        let response = ClientControlResponse::SupervisorRoutes { modules };
7952        Ok(vec![control_response_body_frame(
7953            &frame,
7954            &response,
7955            "ClientControlResponse::SupervisorRoutes",
7956        )?])
7957    }
7958
7959    fn running_registration_method(
7960        &self,
7961        module: &str,
7962    ) -> Option<subc_control::RegistrationMethod> {
7963        let registration = self.registry.get_module(module).ok()??;
7964        let connection = registration.connection_id;
7965        let channel = self.supervisor.registration_spawn(connection).is_some();
7966        let nonce = if channel {
7967            None
7968        } else {
7969            self.hello_launch_nonces
7970                .lock()
7971                .ok()?
7972                .nonce(connection)
7973                .map(str::to_owned)
7974        };
7975        if !channel && nonce.is_none() {
7976            return None;
7977        }
7978        self.supervisor
7979            .registration_snapshot_is_current_live(
7980                &self.registry,
7981                module,
7982                connection,
7983                nonce.as_deref(),
7984            )
7985            .then_some(if channel {
7986                subc_control::RegistrationMethod::Channel
7987            } else {
7988                subc_control::RegistrationMethod::Nonce
7989            })
7990    }
7991
7992    async fn handle_supervisor_provenance(
7993        &self,
7994        ctx: &RouteCtx,
7995        frame: Frame,
7996        module_id: Option<String>,
7997    ) -> Result<Vec<Frame>, RouterError> {
7998        let targeted = module_id.is_some();
7999        let selected = if let Some(module_id) = module_id {
8000            let Some(module) = self.supervisor.get(&module_id) else {
8001                return Ok(vec![control_error_frame(
8002                    &frame,
8003                    "unknown_module",
8004                    format!("module_id '{module_id}' is not supervised"),
8005                )?]);
8006            };
8007            vec![module]
8008        } else {
8009            self.supervisor.list()
8010        };
8011
8012        let target = targeted.then(|| selected[0].module_id());
8013        let declarations = if let Some(owner) = &self.config_runtime {
8014            owner
8015                .on_blocking(|owner| owner.registration_declarations())
8016                .await
8017                .ok()
8018        } else {
8019            None
8020        };
8021        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
8022            let mut modules = Vec::with_capacity(selected.len());
8023            let mut extensions = Vec::with_capacity(selected.len());
8024            for module in &selected {
8025                let (status, observed_image) = module
8026                    .status_and_running_image_agreement()
8027                    .await
8028                    .map_err(|err| {
8029                        RouterError::backend(
8030                            0,
8031                            frame.header.corr,
8032                            format!("failed to read supervisor status: {err}"),
8033                        )
8034                    })?;
8035                let module_declared = self
8036                    .registry
8037                    .get_module(&status.module_id)
8038                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8039                    .and_then(|registration| registration.manifest.provenance)
8040                    .map(|build| ModuleDeclaredProvenance::Reported { build })
8041                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
8042                #[cfg(test)]
8043                let running_image = match &self.provenance_probe_override {
8044                    Some(result) => result.clone(),
8045                    None => observed_image,
8046                };
8047                #[cfg(not(test))]
8048                let running_image = observed_image;
8049                let registration = self.running_registration_method(&status.module_id);
8050                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
8051                    .with_registration(registration);
8052                extension.registration_declaration = declarations
8053                    .as_ref()
8054                    .and_then(|entries| entries.get(&status.module_id))
8055                    .cloned();
8056                if status.process_alive && status.registration_declaration.is_some() {
8057                    extension.registration_declaration = status.registration_declaration.clone();
8058                }
8059                extensions.push(extension);
8060                modules.push(SupervisorModuleProvenance {
8061                    module_id: status.module_id,
8062                    module_declared,
8063                    daemon_observed: SupervisorObservedProcess {
8064                        launch_nonce_source: status.launch_nonce_source,
8065                        pid: status.pid,
8066                        spawned_at_ms: status.spawned_at_ms,
8067                        spawned_from: status.spawned_from,
8068                        running_image,
8069                    },
8070                });
8071            }
8072            let daemon = SupervisorDaemonProvenance {
8073                daemon_build: self.daemon_provenance.build.clone(),
8074                daemon_observed: DaemonObservedProcess {
8075                    pid: self.daemon_provenance.pid,
8076                    started_at_ms: self
8077                        .daemon_provenance
8078                        .start_clock
8079                        .map(|clock| clock.started_at_ms())
8080                        .or(self.daemon_provenance.started_at_ms),
8081                    running_image: self
8082                        .daemon_provenance
8083                        .probe
8084                        .observe(
8085                            self.daemon_provenance.pid,
8086                            self.daemon_provenance.executable_path.as_deref(),
8087                            self.daemon_provenance.executable_identity.clone(),
8088                            self.daemon_provenance.process_start_time,
8089                        )
8090                        .await,
8091                },
8092            };
8093            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8094            let mut response = serde_json::to_value(response)
8095                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8096            for (entry, extension) in response["modules"]
8097                .as_array_mut()
8098                .expect("provenance modules are an array")
8099                .iter_mut()
8100                .zip(extensions)
8101            {
8102                extension.write_to(entry).map_err(|error| {
8103                    RouterError::backend(0, frame.header.corr, error.to_string())
8104                })?;
8105            }
8106            Ok(vec![control_response_body_frame(
8107                &frame,
8108                &response,
8109                "ClientControlResponse::SupervisorProvenance",
8110            )?])
8111        })
8112        .await
8113    }
8114
8115    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8116        self.refresh_capability_requirements();
8117        let publication = self
8118            .config_runtime
8119            .as_ref()
8120            .and_then(|owner| owner.polled_snapshot().ok());
8121        let generation = self
8122            .registry
8123            .generation()
8124            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8125        let modules = self
8126            .supervisor
8127            .list()
8128            .into_iter()
8129            .map(|module| {
8130                let status = module.status_for_control("health").map_err(|err| {
8131                    RouterError::backend(
8132                        0,
8133                        frame.header.corr,
8134                        format!("failed to read supervisor health: {err}"),
8135                    )
8136                })?;
8137                let module_id = status.module_id;
8138                let capability_detail = self
8139                    .capability_evaluator
8140                    .required_problem_detail(&module_id);
8141                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8142                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8143                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8144                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8145                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8146                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8147                Ok(SupervisorHealthEntry {
8148                    module_id,
8149                    status: status.health.status,
8150                    detail: append_capability_problem_detail(
8151                        status.health.detail,
8152                        capability_detail,
8153                    ),
8154                    metrics: status.health.metrics,
8155                    consecutive_failures: status.health.consecutive_failures,
8156                    late_answer_count: status.health.late_answer_count,
8157                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8158                    last_action: status.health.last_action,
8159                    last_action_ms: status.health.last_action_ms,
8160                    last_probe_ms: status.health.last_probe_ms,
8161                })
8162            })
8163            .collect::<Result<Vec<_>, RouterError>>()?;
8164        let response = ClientControlResponse::SupervisorHealth {
8165            generation,
8166            modules,
8167        };
8168        Ok(vec![control_response_body_frame(
8169            &frame,
8170            &response,
8171            "ClientControlResponse::SupervisorHealth",
8172        )?])
8173    }
8174
8175    async fn handle_supervisor_restart(
8176        &self,
8177        frame: Frame,
8178        module_id: String,
8179        drain_timeout_ms: Option<u64>,
8180        requester: Principal,
8181    ) -> Result<Vec<Frame>, RouterError> {
8182        let operation_lock = self.supervisor.operation_lock();
8183        let _operation_guard = operation_lock.lock().await;
8184        let Some(module) = self.supervisor.get(&module_id) else {
8185            return Ok(vec![control_error_frame(
8186                &frame,
8187                "unknown_module",
8188                format!("module_id '{module_id}' is not supervised"),
8189            )?]);
8190        };
8191
8192        self.route_outages.mark_operator_action(&module_id);
8193        if let Err(err) = module
8194            .restart_requested(drain_timeout_ms, Some(requester))
8195            .await
8196        {
8197            self.route_outages
8198                .operator_action_ended_unrefused(&module_id);
8199            let (code, message) = match err {
8200                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8201                crate::supervise::SuperviseError::Disabled { .. } => {
8202                    ("module_disabled", err.to_string())
8203                }
8204                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8205                    ("swap_in_progress", err.to_string())
8206                }
8207                _ => (
8208                    "target_unavailable",
8209                    format!("failed to restart module_id '{module_id}': {err}"),
8210                ),
8211            };
8212            return Ok(vec![control_error_frame(&frame, code, message)?]);
8213        }
8214
8215        let response = ClientControlResponse::SupervisorAck {
8216            module_id,
8217            applied: true,
8218        };
8219        Ok(vec![control_response_body_frame(
8220            &frame,
8221            &response,
8222            "ClientControlResponse::SupervisorAck",
8223        )?])
8224    }
8225
8226    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8227    /// when the old process has finished draining: a caller whose own lane
8228    /// rides the old process must get its reply before that drain waits on it.
8229    async fn handle_supervisor_swap(
8230        &self,
8231        frame: Frame,
8232        module_id: String,
8233        ready_timeout_ms: Option<u64>,
8234        requester: Principal,
8235    ) -> Result<Vec<Frame>, RouterError> {
8236        // The daemon-wide operation lock is held only to resolve the handle,
8237        // not across the swap. The swap can take its whole readiness budget,
8238        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8239        // holding it here would park an operator's stop behind the swap it is
8240        // meant to abort. A rescan or stop that reaches the module during the
8241        // swap is served by the swap itself (see `supervise_swap`).
8242        let module = {
8243            let operation_lock = self.supervisor.operation_lock();
8244            let _operation_guard = operation_lock.lock().await;
8245            self.supervisor.get(&module_id)
8246        };
8247        let Some(module) = module else {
8248            return Ok(vec![control_error_frame(
8249                &frame,
8250                "unknown_module",
8251                format!("module_id '{module_id}' is not supervised"),
8252            )?]);
8253        };
8254
8255        self.route_outages.mark_operator_action(&module_id);
8256        if let Err(err) = module
8257            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8258            .await
8259        {
8260            self.route_outages
8261                .operator_action_ended_unrefused(&module_id);
8262            use crate::supervise::SuperviseError;
8263            let message = err.to_string();
8264            let error = match err {
8265                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8266                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8267                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8268                    code: "swap_refused".to_string(),
8269                    message,
8270                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8271                },
8272                SuperviseError::SwapFailed {
8273                    arm,
8274                    candidate_exit,
8275                    ..
8276                } => ErrorBody {
8277                    code: "swap_failed".to_string(),
8278                    message,
8279                    detail: Some(serde_json::json!({
8280                        "arm": arm.as_str(),
8281                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8282                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8283                    })),
8284                },
8285                _ => ErrorBody::new(
8286                    "target_unavailable",
8287                    format!("failed to swap module_id '{module_id}': {message}"),
8288                ),
8289            };
8290            return Ok(vec![control_error_body_frame(&frame, error)?]);
8291        }
8292        // A completed swap kept the incumbent serving until cutover, so it
8293        // usually opened no outage; a mark left behind would make the next,
8294        // unrelated outage read as requested.
8295        self.route_outages
8296            .operator_action_ended_unrefused(&module_id);
8297
8298        let response = ClientControlResponse::SupervisorAck {
8299            module_id,
8300            applied: true,
8301        };
8302        Ok(vec![control_response_body_frame(
8303            &frame,
8304            &response,
8305            "ClientControlResponse::SupervisorAck",
8306        )?])
8307    }
8308
8309    async fn handle_supervisor_reload(
8310        &self,
8311        frame: Frame,
8312        module_id: String,
8313        requester: Principal,
8314    ) -> Result<Vec<Frame>, RouterError> {
8315        let operation_lock = self.supervisor.operation_lock();
8316        let _operation_guard = operation_lock.lock().await;
8317        let Some(module) = self.supervisor.get(&module_id) else {
8318            return Ok(vec![control_error_frame(
8319                &frame,
8320                "unknown_module",
8321                format!("module_id '{module_id}' is not supervised"),
8322            )?]);
8323        };
8324
8325        self.route_outages.mark_operator_action(&module_id);
8326        if let Err(err) = module.reload_requested(Some(requester)).await {
8327            self.route_outages
8328                .operator_action_ended_unrefused(&module_id);
8329            let (code, message) = match err {
8330                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8331                crate::supervise::SuperviseError::Disabled { .. } => {
8332                    ("module_disabled", err.to_string())
8333                }
8334                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8335                    ("swap_in_progress", err.to_string())
8336                }
8337                _ => (
8338                    "reload_failed",
8339                    format!("failed to reload module_id '{module_id}': {err}"),
8340                ),
8341            };
8342            return Ok(vec![control_error_frame(&frame, code, message)?]);
8343        }
8344
8345        let response = ClientControlResponse::SupervisorAck {
8346            module_id,
8347            applied: true,
8348        };
8349        Ok(vec![control_response_body_frame(
8350            &frame,
8351            &response,
8352            "ClientControlResponse::SupervisorAck",
8353        )?])
8354    }
8355
8356    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8357    /// the configuration comes from and whether to apply it; every mode then
8358    /// runs the same comparison, so a preview describes the apply it previews.
8359    async fn handle_supervisor_rescan(
8360        &self,
8361        frame: Frame,
8362        mode: RescanMode,
8363        requester: Principal,
8364    ) -> Result<Vec<Frame>, RouterError> {
8365        let preview = mode.previews();
8366        let Some(context) = self.rescan.clone() else {
8367            return Ok(vec![control_error_frame(
8368                &frame,
8369                "rescan_unavailable",
8370                "the daemon was not started with a reloadable config path".to_string(),
8371            )?]);
8372        };
8373
8374        let _rescan_guard = context.rescan_lock.lock().await;
8375        let rescan_checked::RescanInput {
8376            config: loaded,
8377            approved_preview,
8378            guard: _operation_guard,
8379        } = match self.rescan_input(&mode, &context).await {
8380            Ok(input) => input,
8381            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
8382        };
8383        // `load` reports a missing file as Ok(None), which is correct at boot
8384        // (no config, nothing to supervise) and catastrophic here: rescan treats
8385        // "not in the config" as "remove it", so an absent file would read as an
8386        // empty module list and retire the entire running fleet. An editor
8387        // writing via write-new-then-rename, or a half-finished edit, is enough
8388        // to open that window. Refuse instead: a config that cannot be read
8389        // carries no instruction to remove anything.
8390        let Some((config, activity_config)) = loaded else {
8391            return Ok(vec![control_error_frame(
8392                &frame,
8393                "invalid_daemon_config",
8394                format!(
8395                    "daemon config not found at {}; refusing to rescan (an absent config would \
8396                     retire every supervised module)",
8397                    context.config_path.display()
8398                ),
8399            )?]);
8400        };
8401        let (
8402            configured_port,
8403            storage_config,
8404            admission_facts_carrier_module_id,
8405            admission_facts_targets,
8406            scope_authority_owners,
8407            federated_scope_owner,
8408            privileged_operator_prompt,
8409            modules,
8410            reserved_capabilities,
8411        ) = (
8412            config.port,
8413            config.storage,
8414            config.admission_facts_carrier_module_id,
8415            config.admission_facts_targets,
8416            config.scope_authority_owners,
8417            config.federated_scope_owner,
8418            config.privileged_operator_prompt,
8419            config.modules,
8420            config.reserved_capabilities,
8421        );
8422
8423        // Collect the sections rescan cannot apply, so the REPLY carries them.
8424        //
8425        // The warning below has always been correct and has always gone only to
8426        // the journal -- addressed to whoever reads logs, while the person who
8427        // just edited the config is looking at the CLI. Naming each section
8428        // individually rather than setting a flag: "something outside modules
8429        // changed" sends the operator back to diffing their own file, which is
8430        // the work this is meant to save.
8431        let mut restart_required = Vec::new();
8432        for section in RestartRequiredSection::ALL {
8433            let changed = match section {
8434                RestartRequiredSection::Port => configured_port != context.configured_port,
8435                RestartRequiredSection::Storage => storage_config != context.storage_config,
8436                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8437                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8438                }
8439                RestartRequiredSection::AdmissionFactsTargets => {
8440                    admission_facts_targets != context.admission_facts_targets
8441                }
8442                RestartRequiredSection::ScopeAuthorityOwners => {
8443                    scope_authority_owners != context.scope_authority_owners
8444                }
8445                RestartRequiredSection::FederatedScopeOwner => {
8446                    federated_scope_owner != context.federated_scope_owner
8447                }
8448                RestartRequiredSection::PrivilegedOperatorPrompt => {
8449                    privileged_operator_prompt != context.privileged_operator_prompt
8450                }
8451            };
8452            if changed {
8453                restart_required.push(section.label().to_string());
8454            }
8455        }
8456        if !restart_required.is_empty() {
8457            warn!(
8458                config_path = %context.config_path.display(),
8459                sections = %restart_required.join(", "),
8460                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8461            );
8462        }
8463
8464        for configured in &modules {
8465            if let Err(err) = validate_spec(&configured.module_spec()) {
8466                return Ok(vec![control_error_frame(
8467                    &frame,
8468                    "invalid_daemon_config",
8469                    format!("supervisor rescan rejected daemon config: {err}"),
8470                )?]);
8471            }
8472        }
8473
8474        let configured_capabilities = modules
8475            .iter()
8476            .map(|module| (module.module_id.clone(), module.enabled))
8477            .collect::<Vec<_>>();
8478        let preview_capability_warnings = if preview {
8479            let (_, registrations) = self.runtime_capability_snapshot()?;
8480            let current_modules = self
8481                .supervisor
8482                .list()
8483                .into_iter()
8484                .map(|module| module.module_id().to_string())
8485                .collect::<BTreeSet<_>>();
8486            let resulting_modules = configured_capabilities.clone();
8487            let removed = current_modules
8488                .into_iter()
8489                .filter(|module_id| {
8490                    !resulting_modules
8491                        .iter()
8492                        .any(|(configured_id, _)| configured_id == module_id)
8493                })
8494                .collect::<Vec<_>>();
8495            // A candidate preview also names providers the candidate disables.
8496            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8497            let disabled = match &mode {
8498                RescanMode::Candidate(_) => resulting_modules
8499                    .iter()
8500                    .filter(|(_, enabled)| !enabled)
8501                    .map(|(module_id, _)| module_id.clone())
8502                    .collect::<Vec<_>>(),
8503                _ => Vec::new(),
8504            };
8505            self.capability_evaluator.preview_warnings(
8506                resulting_modules,
8507                &removed,
8508                &disabled,
8509                &registrations,
8510            )
8511        } else {
8512            Vec::new()
8513        };
8514        let reconciled = match (&mode, approved_preview.as_ref()) {
8515            (RescanMode::Preview, Some(approved)) => Ok((
8516                config_gate::preview_approved_daemon(approved, &modules),
8517                Vec::new(),
8518            )),
8519            (RescanMode::Candidate(candidate), _) => self
8520                .preview_candidate(&context, modules, candidate)
8521                .map(|result| (result, Vec::new())),
8522            _ => {
8523                self.reconcile_supervised_modules(
8524                    &context.supervisor,
8525                    modules,
8526                    preview,
8527                    requester.clone(),
8528                )
8529                .await
8530            }
8531        };
8532        let (result, changed) = match reconciled {
8533            Ok(result) => result,
8534            Err(message) => {
8535                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8536            }
8537        };
8538        if !preview {
8539            if let Some(ledger) = &self.activity {
8540                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8541                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8542            }
8543            if let Err(code) = self.configure_activity(activity_config).await {
8544                warn!(
8545                    code,
8546                    "activity retention could not be applied during rescan"
8547                );
8548            }
8549            self.capability_evaluator
8550                .configure(configured_capabilities, reserved_capabilities);
8551            self.capability_evaluator.wake_deadline_loop();
8552            self.refresh_capability_requirements();
8553        }
8554        let mut result = result;
8555        result.restart_required = restart_required;
8556        result.capability_warnings = preview_capability_warnings;
8557        let response = ClientControlResponse::SupervisorRescan { result };
8558        Ok(vec![control_response_body_frame(
8559            &frame,
8560            &response,
8561            "ClientControlResponse::SupervisorRescan",
8562        )?])
8563    }
8564
8565    async fn handle_supervisor_release_reserved(
8566        &self,
8567        frame: Frame,
8568        module_id: String,
8569    ) -> Result<Vec<Frame>, RouterError> {
8570        let Some(context) = self.rescan.clone() else {
8571            return Ok(vec![control_error_frame(
8572                &frame,
8573                "release_unavailable",
8574                "reserved-id release requires a daemon started with a reloadable config path",
8575            )?]);
8576        };
8577        let operation_lock = self.supervisor.operation_lock();
8578        let _operation_guard = operation_lock.lock().await;
8579        let approved = if let Some(owner) = &self.config_runtime {
8580            // Observe the file as a proposal, but decide membership solely from
8581            // approved bytes. A proposed re-add must not retain a removed id.
8582            match owner
8583                .on_blocking(|owner| {
8584                    owner.observe_file_proposal()?;
8585                    owner.approved_daemon_configuration()
8586                })
8587                .await
8588            {
8589                Ok(config) => config,
8590                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8591            }
8592        } else {
8593            None
8594        };
8595        let loaded = if let Some(approved) = approved {
8596            Ok(Some(approved))
8597        } else {
8598            crate::daemon_config::load(&context.config_path)
8599        };
8600        let loaded = match loaded {
8601            Ok(Some(config)) => config,
8602            Ok(None) => {
8603                return Ok(vec![control_error_frame(
8604                    &frame,
8605                    "invalid_daemon_config",
8606                    format!(
8607                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8608                        context.config_path.display()
8609                    ),
8610                )?])
8611            }
8612            Err(err) => {
8613                return Ok(vec![control_error_frame(
8614                    &frame,
8615                    "invalid_daemon_config",
8616                    format!("unable to verify reserved-id release against daemon config: {err}"),
8617                )?])
8618            }
8619        };
8620        if loaded
8621            .modules
8622            .iter()
8623            .any(|configured| configured.module_id == module_id)
8624        {
8625            return Ok(vec![control_error_frame(
8626                &frame,
8627                "reserved_module_configured",
8628                format!(
8629                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8630                ),
8631            )?]);
8632        }
8633        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8634            return Ok(vec![control_error_frame(
8635                &frame,
8636                "reserved_gate_not_retained",
8637                format!(
8638                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8639                ),
8640            )?]);
8641        }
8642
8643        let response = ClientControlResponse::SupervisorAck {
8644            module_id,
8645            applied: true,
8646        };
8647        Ok(vec![control_response_body_frame(
8648            &frame,
8649            &response,
8650            "ClientControlResponse::SupervisorAck",
8651        )?])
8652    }
8653
8654    /// Compare the configured module set with the supervised one, changing
8655    /// nothing. The staged spec each supervised module holds is what the
8656    /// configured entry is compared with.
8657    fn plan_rescan(
8658        &self,
8659        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8660    ) -> Result<RescanPlan, String> {
8661        let mut current = BTreeMap::new();
8662        for module in self.supervisor.list() {
8663            let (spec, health) = module.configuration().map_err(|err| {
8664                format!(
8665                    "failed to read configuration for module_id '{}': {err}",
8666                    module.module_id()
8667                )
8668            })?;
8669            let enabled = module
8670                .status()
8671                .map_err(|err| {
8672                    format!(
8673                        "failed to read status for module_id '{}': {err}",
8674                        module.module_id()
8675                    )
8676                })?
8677                .enabled;
8678            current.insert(
8679                module.module_id().to_string(),
8680                (module, spec, health, enabled),
8681            );
8682        }
8683        let configured = configured_modules
8684            .into_iter()
8685            .map(|module| (module.module_id.clone(), module))
8686            .collect::<BTreeMap<_, _>>();
8687
8688        let added = configured
8689            .keys()
8690            .filter(|module_id| !current.contains_key(*module_id))
8691            .cloned()
8692            .collect::<Vec<_>>();
8693        let removed = current
8694            .keys()
8695            .filter(|module_id| !configured.contains_key(*module_id))
8696            .cloned()
8697            .collect::<Vec<_>>();
8698        let mut changed_pending_reload = Vec::new();
8699        let mut changed_pending = Vec::new();
8700        let mut configuration_changes = BTreeSet::new();
8701        let mut enabled_changes = BTreeSet::new();
8702        let mut unchanged = 0_u32;
8703        let publication = self
8704            .config_runtime
8705            .as_ref()
8706            .and_then(|owner| owner.polled_snapshot().ok());
8707
8708        for (module_id, configured_module) in &configured {
8709            let Some((module, current_spec, current_health, current_enabled)) =
8710                current.get(module_id)
8711            else {
8712                continue;
8713            };
8714            // Compare the whole launch spec so a future launch field cannot
8715            // accidentally become a live-only policy change. Health is stored
8716            // separately and applies live without replacing the process.
8717            let launch_changed = *current_spec != configured_module.module_spec();
8718            let configuration_changed =
8719                launch_changed || *current_health != configured_module.health;
8720            let pending = self.pending_module_fields(
8721                module,
8722                Some(configured_module),
8723                configuration_changed,
8724                Self::registration_channel_in_force(
8725                    publication
8726                        .as_ref()
8727                        .and_then(|view| view.registration_declaration(module_id))
8728                        .as_deref(),
8729                    publication
8730                        .as_ref()
8731                        .and_then(|view| match &view.approved_daemon {
8732                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8733                                config,
8734                                ..
8735                            } => config
8736                                .modules
8737                                .iter()
8738                                .find(|entry| entry.module_id == *module_id)
8739                                .map(|entry| entry.registration_channel),
8740                            _ => None,
8741                        }),
8742                ),
8743            )?;
8744            let has_pending = !pending.is_empty();
8745            if has_pending {
8746                changed_pending.push(subc_control::SupervisorPendingModule {
8747                    module_id: module_id.clone(),
8748                    fields: pending
8749                        .into_iter()
8750                        .map(|mut field| {
8751                            field.value = None;
8752                            field
8753                        })
8754                        .collect(),
8755                });
8756            }
8757            // Applying a rescan also replaces the recorded config value, even
8758            // when an operator already put the runtime in the requested state.
8759            let enabled_changed = *current_enabled != configured_module.enabled
8760                || self
8761                    .capability_evaluator
8762                    .configured_enabled(module_id)
8763                    .is_some_and(|enabled| enabled != configured_module.enabled);
8764            if configuration_changed {
8765                configuration_changes.insert(module_id.clone());
8766            }
8767            if launch_changed {
8768                changed_pending_reload.push(module_id.clone());
8769            }
8770            if enabled_changed {
8771                enabled_changes.insert(module_id.clone());
8772            }
8773            if !configuration_changed && !enabled_changed && !has_pending {
8774                unchanged = unchanged.saturating_add(1);
8775            }
8776        }
8777        Ok(RescanPlan {
8778            current,
8779            configured,
8780            added,
8781            removed,
8782            changed_pending_reload,
8783            changed_pending,
8784            configuration_changes,
8785            enabled_changes,
8786            unchanged,
8787        })
8788    }
8789
8790    /// Reconcile the running module set against the configured one.
8791    ///
8792    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8793    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8794    /// deliberately shares this function with the executing path rather than
8795    /// computing the same diff somewhere else -- two implementations of one
8796    /// decision agree until they do not, and the whole value of a preview is that
8797    /// it describes the operation that will actually run.
8798    async fn reconcile_supervised_modules(
8799        &self,
8800        supervisor: &Supervisor,
8801        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8802        preview: bool,
8803        requester: Principal,
8804    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8805        let plan = self.plan_rescan(configured_modules)?;
8806
8807        // Everything above this point is pure computation over two snapshots.
8808        // Everything below MUTATES. The preview returns here so the boundary is a
8809        // single early return rather than a condition repeated at each mutation
8810        // site, where one missed guard would apply part of a change the caller was
8811        // told would not happen.
8812        if preview {
8813            return Ok((plan.preview_result(), Vec::new()));
8814        }
8815        let changed = plan
8816            .configuration_changes
8817            .union(&plan.enabled_changes)
8818            .cloned()
8819            .collect::<Vec<_>>();
8820        let RescanPlan {
8821            current,
8822            configured,
8823            added,
8824            removed,
8825            changed_pending_reload,
8826            changed_pending,
8827            configuration_changes,
8828            enabled_changes,
8829            unchanged,
8830        } = plan;
8831        // The staged generation moves before the first change rather than
8832        // after the last, so a rescan that fails partway still invalidates
8833        // every earlier `supervisor.rescan_checked` preview: part of its diff
8834        // may have run.
8835        if !(added.is_empty()
8836            && removed.is_empty()
8837            && configuration_changes.is_empty()
8838            && changed_pending.is_empty()
8839            && enabled_changes.is_empty())
8840        {
8841            if let Some(context) = &self.rescan {
8842                context
8843                    .generation
8844                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8845            }
8846        }
8847
8848        for module_id in &removed {
8849            let module = &current
8850                .get(module_id)
8851                .expect("removed module came from current supervisor state")
8852                .0;
8853            module
8854                .retire_requested(Some(requester.clone()))
8855                .await
8856                .map_err(|err| {
8857                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8858                })?;
8859            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8860            //
8861            // `handle_route_open` resolves an absent module in three steps:
8862            // registry, then supervisor status, then tombstone. Retiring first
8863            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8864            // went with the teardown above, the supervisor entry went with
8865            // `retire`, and the tombstone does not exist yet -- so a route.open
8866            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8867            // it") for a module that was deliberately removed and whose caller
8868            // should get `module_removed` (TERMINAL, carrying a removal age).
8869            //
8870            // Writing the tombstone first closes it: during the window the
8871            // supervisor entry still answers, so the caller gets
8872            // `target_unavailable` -- retryable, and TRUE, because the module
8873            // is mid-teardown. After both statements it is `module_removed`.
8874            // No instant remains where a removed module reads as one that
8875            // never existed.
8876            //
8877            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8878            // the absence of a test beside a fix invites deletion: these are
8879            // two sync statements with no await between them, so reaching the
8880            // window needs a second worker thread to land exactly between them
8881            // and there is no hook to force it. MEASURED: the 25 daemon_config
8882            // tests pass identically with the old order and the new one, so
8883            // the existing suite cannot see this and a green run is not
8884            // evidence either way. What the suite does hold is the
8885            // post-condition -- a removed module answers `module_removed` --
8886            // which this preserves.
8887            //
8888            // Found by an Athena panel reading the shipped tree against a
8889            // design note (2026-09-19), as the one concrete instance of that
8890            // note's class that survived contact with source. Direction is
8891            // benign: retryable where terminal was intended, never the reverse.
8892            self.supervisor.record_rescan_removal(module_id);
8893            self.supervisor.retire(module_id);
8894            self.route_outages.forget(module_id);
8895        }
8896
8897        for module_id in configured.keys() {
8898            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8899                continue;
8900            };
8901            let configured_module = configured
8902                .get(module_id)
8903                .expect("configured module id came from configured map");
8904            if configuration_changes.contains(module_id) {
8905                module
8906                    .update_configuration(
8907                        configured_module.module_spec(),
8908                        configured_module.health.clone(),
8909                        configured_module.drain_timeout_ms,
8910                    )
8911                    .await
8912                    .map_err(|err| {
8913                        format!(
8914                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8915                        )
8916                    })?;
8917            }
8918            // Config-only drift is applied by the evaluator's config update;
8919            // do not turn it into a runtime start or stop.
8920            if *current_enabled != configured_module.enabled {
8921                // A rescan that starts or stops a module applies an operator's
8922                // edit to the config, so the resulting outage was asked for.
8923                self.route_outages.mark_operator_action(module_id);
8924                module
8925                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8926                    .await
8927                    .map_err(|err| {
8928                        self.route_outages.operator_action_ended_unrefused(module_id);
8929                        format!(
8930                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8931                            configured_module.enabled
8932                        )
8933                    })?;
8934            }
8935        }
8936
8937        for module_id in &added {
8938            let configured_module = configured
8939                .get(module_id)
8940                .expect("added module id came from configured map");
8941            supervisor
8942                .supervise_configured_requested_async(
8943                    configured_module.module_spec(),
8944                    configured_module.enabled,
8945                    configured_module.health.clone(),
8946                    configured_module.drain_timeout_ms,
8947                    configured_module.restart,
8948                    configured_module.register_timeout,
8949                    Some(requester.clone()),
8950                )
8951                .await
8952                .map_err(|err| {
8953                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8954                })?;
8955        }
8956
8957        if let Some(context) = &self.rescan {
8958            let mut entries = context
8959                .module_entries
8960                .lock()
8961                .unwrap_or_else(|e| e.into_inner());
8962            entries.record(&configured, &added, &removed);
8963        }
8964
8965        Ok((
8966            SupervisorRescanResult {
8967                added,
8968                removed,
8969                changed_pending_reload,
8970                changed_pending,
8971                enabled_changes: enabled_changes.iter().cloned().collect(),
8972                unchanged,
8973                preview: false,
8974                // Filled by the caller, which is the only layer that can see the
8975                // previous config to diff against.
8976                restart_required: Vec::new(),
8977                capability_warnings: Vec::new(),
8978                module_actions: Vec::new(),
8979                earlier_pending: Vec::new(),
8980                expect: None,
8981            },
8982            changed,
8983        ))
8984    }
8985
8986    async fn handle_supervisor_set_enabled(
8987        &self,
8988        frame: Frame,
8989        module_id: String,
8990        enabled: bool,
8991        requester: Principal,
8992    ) -> Result<Vec<Frame>, RouterError> {
8993        let operation_lock = self.supervisor.operation_lock();
8994        let _operation_guard = operation_lock.lock().await;
8995        let Some(module) = self.supervisor.get(&module_id) else {
8996            return Ok(vec![control_error_frame(
8997                &frame,
8998                "unknown_module",
8999                format!("module_id '{module_id}' is not supervised"),
9000            )?]);
9001        };
9002
9003        // Enabling counts as well as disabling: a module an operator starts
9004        // is refused until it registers, and that wait was asked for.
9005        self.route_outages.mark_operator_action(&module_id);
9006        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
9007            Ok(applied) => applied,
9008            Err(err) => {
9009                self.route_outages
9010                    .operator_action_ended_unrefused(&module_id);
9011                return Ok(vec![control_error_frame(
9012                    &frame,
9013                    if err.is_config_gate_error() {
9014                        "config_gated"
9015                    } else {
9016                        "target_unavailable"
9017                    },
9018                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
9019                )?]);
9020            }
9021        };
9022        if !applied {
9023            // Already in the requested state: nothing was made unavailable,
9024            // so the mark must not outlive this request.
9025            self.route_outages
9026                .operator_action_ended_unrefused(&module_id);
9027        }
9028
9029        self.capability_evaluator.wake_deadline_loop();
9030        self.refresh_capability_requirements();
9031        let response = ClientControlResponse::SupervisorAck { module_id, applied };
9032        Ok(vec![control_response_body_frame(
9033            &frame,
9034            &response,
9035            "ClientControlResponse::SupervisorAck",
9036        )?])
9037    }
9038
9039    async fn handle_supervisor_health_probe(
9040        &self,
9041        ctx: &RouteCtx,
9042        frame: Frame,
9043        module_id: String,
9044    ) -> Result<Vec<Frame>, RouterError> {
9045        self.refresh_capability_requirements();
9046        let Some(registration) = self
9047            .registry
9048            .get_module(&module_id)
9049            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
9050        else {
9051            return Ok(vec![control_error_frame(
9052                &frame,
9053                "unknown_module",
9054                format!("module_id '{module_id}' is not registered"),
9055            )?]);
9056        };
9057
9058        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
9059        // named for it. Making `module_registration_grants_op` return false
9060        // unconditionally reddens five tests, and every one is named for something
9061        // else -- capability relay, probe/bind demultiplexing, supervision-only
9062        // probing. They exercise a successful advertisement check on the way to their
9063        // own subject.
9064        //
9065        // Real protection, fragile in a specific way: narrowing any of those tests to
9066        // focus on its stated subject would silently remove coverage nobody knows
9067        // they are carrying. Recorded here rather than as a sixth test, because the
9068        // useful fact is WHICH tests hold the guard up -- a new test would add
9069        // coverage without telling the next person what the existing ones quietly do.
9070        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
9071        {
9072            return Ok(vec![control_error_frame(
9073                &frame,
9074                "health_not_advertised",
9075                format!("module_id '{module_id}' did not advertise health.check"),
9076            )?]);
9077        }
9078
9079        self.observe_control_wait(
9080            ctx,
9081            Some(&registration.manifest.module_id),
9082            ops::SUPERVISOR_HEALTH_PROBE,
9083            async {
9084                let deadline = Instant::now() + self.health_probe_timeout;
9085                let pending = match self.forwarding.begin_module_control_rpc_for(
9086                    &module_id,
9087                    MODULE_CONTROL_OP_HEALTH_CHECK,
9088                    deadline,
9089                ) {
9090                    Ok(pending) => pending,
9091                    Err(err) => {
9092                        return Ok(vec![control_error_frame(
9093                            &frame,
9094                            forwarding_error_code(&err),
9095                            err.to_string(),
9096                        )?])
9097                    }
9098                };
9099
9100                let PendingModuleControlRpc {
9101                    endpoint,
9102                    module_sink,
9103                    negotiated_ver,
9104                    corr: probe_corr,
9105                    receiver,
9106                } = pending;
9107                let mut guard =
9108                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9109                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9110                    .map_err(|err| {
9111                        RouterError::backend(
9112                            0,
9113                            frame.header.corr,
9114                            format!("failed to encode health.check request: {err}"),
9115                        )
9116                    })?;
9117                let probe_frame = Frame::build_with_version(
9118                    negotiated_ver,
9119                    FrameType::Request,
9120                    control_flags(),
9121                    0,
9122                    0,
9123                    probe_corr,
9124                    probe_body,
9125                )
9126                .map_err(RouterError::FrameBuild)?;
9127
9128                // Queue admission and the reply share one deadline, so a module that
9129                // stops reading cannot park the requesting connection's reader forever.
9130                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9131                    Ok(Ok(())) => {}
9132                    Ok(Err(err)) => {
9133                        return Ok(vec![control_error_frame(
9134                            &frame,
9135                            "target_unavailable",
9136                            err.to_string(),
9137                        )?]);
9138                    }
9139                    Err(_) => {
9140                        return Ok(vec![control_error_frame(
9141                            &frame,
9142                            "module_timeout",
9143                            format!(
9144                                "module_id '{module_id}' did not answer health.check within {:?}",
9145                                self.health_probe_timeout
9146                            ),
9147                        )?]);
9148                    }
9149                }
9150
9151                match timeout_at(deadline, receiver).await {
9152                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9153                        Ok(vec![control_error_frame(
9154                            &frame,
9155                            "invalid_control_body",
9156                            "health.check returned an unexpected config response",
9157                        )?])
9158                    }
9159                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9160                        guard.disarm();
9161                        let Some(report) = response.health_report() else {
9162                            return Ok(vec![control_error_frame(
9163                                &frame,
9164                                "invalid_control_body",
9165                                "health.check RPC returned a non-health response",
9166                            )?]);
9167                        };
9168                        // Metrics go out whole here. The supervisor's cached snapshot
9169                        // caps this blob (see truncate_health_metrics), and this path
9170                        // exists precisely to answer without that cap -- so applying it
9171                        // here would leave no way to see what the cached view drops.
9172                        let HealthReport {
9173                            status,
9174                            detail,
9175                            metrics,
9176                        } = report;
9177                        let capability_detail = self
9178                            .capability_evaluator
9179                            .required_problem_detail(&module_id);
9180                        let response = ClientControlResponse::SupervisorHealthProbe {
9181                            module_id,
9182                            status,
9183                            detail: append_capability_problem_detail(detail, capability_detail),
9184                            metrics,
9185                        };
9186                        Ok(vec![control_response_body_frame(
9187                            &frame,
9188                            &response,
9189                            "ClientControlResponse::SupervisorHealthProbe",
9190                        )?])
9191                    }
9192                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9193                        guard.disarm();
9194                        // The module refused the health probe with its own body, so
9195                        // the refusal is relayed without the daemon-origin flag
9196                        // (bit 6): a client must not read it as the daemon's own
9197                        // refusal, which it may treat as never forwarded.
9198                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9199                    }
9200                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9201                        guard.disarm();
9202                        Ok(vec![control_error_frame(
9203                            &frame,
9204                            "target_unavailable",
9205                            message,
9206                        )?])
9207                    }
9208                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9209                        guard.disarm();
9210                        Ok(vec![control_error_frame(
9211                            &frame,
9212                            "invalid_control_body",
9213                            message,
9214                        )?])
9215                    }
9216                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9217                        guard.disarm();
9218                        Ok(vec![control_error_frame(
9219                            &frame,
9220                            "invalid_control_body",
9221                            format!("expected module-control op '{expected}', got '{actual}'"),
9222                        )?])
9223                    }
9224                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9225                        guard.disarm();
9226                        Ok(vec![control_error_frame(
9227                            &frame,
9228                            "module_timeout",
9229                            format!(
9230                                "module_id '{module_id}' answered health.check after {:?}",
9231                                self.health_probe_timeout
9232                            ),
9233                        )?])
9234                    }
9235                    Ok(Err(_)) => Ok(vec![control_error_frame(
9236                        &frame,
9237                        "target_unavailable",
9238                        "health.check waiter was canceled before the module responded",
9239                    )?]),
9240                    Err(_) => Ok(vec![control_error_frame(
9241                        &frame,
9242                        "module_timeout",
9243                        format!(
9244                            "module_id '{module_id}' did not answer health.check within {:?}",
9245                            self.health_probe_timeout
9246                        ),
9247                    )?]),
9248                }
9249            },
9250        )
9251        .await
9252    }
9253
9254    fn supervisor_status(
9255        &self,
9256        module_id: &str,
9257        corr: u64,
9258    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9259        self.supervisor
9260            .get(module_id)
9261            .map(|module| {
9262                let warming = module.is_warming_for_control("status").map_err(|err| {
9263                    RouterError::backend(
9264                        0,
9265                        corr,
9266                        format!(
9267                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9268                        ),
9269                    )
9270                })?;
9271                module.status_for_control("status").map_err(|err| {
9272                    RouterError::backend(
9273                        0,
9274                        corr,
9275                        format!(
9276                            "failed to read supervisor status for module_id '{module_id}': {err}"
9277                        ),
9278                    )
9279                }).map(|status| (status, warming))
9280            })
9281            .transpose()
9282    }
9283
9284    fn guard_module_control_op(
9285        &self,
9286        frame: &Frame,
9287        module_id: &str,
9288        op: &str,
9289    ) -> Result<Option<Frame>, RouterError> {
9290        if self.module_grants_op(module_id, op, frame.header.corr)? {
9291            return Ok(None);
9292        }
9293
9294        Ok(Some(control_error_frame(
9295            frame,
9296            "op_not_allowed",
9297            format!("module_id '{module_id}' did not grant control op '{op}'"),
9298        )?))
9299    }
9300
9301    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9302        self.registry
9303            .grants_control_op(module_id, op)
9304            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9305    }
9306
9307    fn handle_status_update(
9308        &self,
9309        endpoint: ModuleEndpointId,
9310        frame: Frame,
9311    ) -> Result<Vec<Frame>, RouterError> {
9312        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9313            Ok(update) => update,
9314            Err(err) => {
9315                // Forward-compat: a newer module may push a channel-0 op this subc
9316                // version doesn't know. The control contract says unknown push ops
9317                // are IGNORED, never answered with an error. Only a malformed body
9318                // for an op we DO know is a real error worth surfacing.
9319                if is_known_module_push_op(&frame.body) {
9320                    return Ok(vec![control_error_frame(
9321                        &frame,
9322                        "invalid_control_body",
9323                        format!("malformed module control push body: {err}"),
9324                    )?]);
9325                }
9326                return Ok(Vec::new());
9327            }
9328        };
9329
9330        match update {
9331            ModuleControlPush::RouteStatus {
9332                route_channel,
9333                route_epoch,
9334                status,
9335            } => {
9336                self.forwarding
9337                    .cache_status(endpoint, route_channel, route_epoch, status)
9338                    .map_err(RouterError::Forwarding)?;
9339            }
9340        }
9341        Ok(Vec::new())
9342    }
9343
9344    fn handle_route_poll(
9345        &self,
9346        ctx: &RouteCtx,
9347        frame: Frame,
9348        route_channel: u16,
9349        route_epoch: u32,
9350        kind: PollKind,
9351    ) -> Result<Vec<Frame>, RouterError> {
9352        let snapshot = self
9353            .forwarding
9354            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9355            .map_err(RouterError::Forwarding)?;
9356        let response = match (kind, snapshot) {
9357            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9358                ClientControlResponse::RoutePoll {
9359                    route_channel,
9360                    route_epoch,
9361                    status,
9362                    live: None,
9363                }
9364            }
9365            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9366                route_channel,
9367                route_epoch,
9368                status: None,
9369                live: None,
9370            },
9371            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9372                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9373                // is what makes reporting `true` correct rather than a
9374                // confident guess. `process_live` returns None only when the
9375                // module id has no supervisor snapshot at all -- an
9376                // externally-started module the daemon did not spawn -- and
9377                // for those the supervisor has no opinion to offer, ever. It
9378                // is never None for a supervised module in an unknown state:
9379                // a supervised module always has a snapshot, and the answer
9380                // comes from `state == Running && process_alive`.
9381                //
9382                // The route is Bound, so the module completed a HELLO on a
9383                // live connection; "the process this route points at is
9384                // running" is therefore attested by the binding rather than
9385                // assumed. Reporting `false` for an unsupervised module would
9386                // be the actual lie -- it would tell a client its healthy
9387                // route is dead because the daemon does not manage the
9388                // process.
9389                //
9390                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9391                // module whose liveness is genuinely unknown, e.g. a snapshot
9392                // that has not been populated yet -- THIS DEFAULT BECOMES
9393                // WRONG and must split: unsupervised stays true, unknown
9394                // becomes null so the client can tell the two apart. The
9395                // response field is already `Option<bool>`, so the wire can
9396                // carry that distinction today.
9397                let live = self
9398                    .process_liveness
9399                    .as_ref()
9400                    .and_then(|source| source.process_live(&module_id))
9401                    .unwrap_or(true);
9402                ClientControlResponse::RoutePoll {
9403                    route_channel,
9404                    route_epoch,
9405                    status: None,
9406                    live: Some(live),
9407                }
9408            }
9409            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9410                route_channel,
9411                route_epoch,
9412                status: None,
9413                live: Some(false),
9414            },
9415        };
9416
9417        Ok(vec![control_response_body_frame(
9418            &frame,
9419            &response,
9420            "ClientControlResponse::RoutePoll",
9421        )?])
9422    }
9423
9424    pub(crate) fn observe_module_control_completion(
9425        &self,
9426        completion: ModuleControlRpcCompletion,
9427    ) -> bool {
9428        match completion {
9429            ModuleControlRpcCompletion::Unknown => false,
9430            ModuleControlRpcCompletion::Settled => true,
9431            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9432                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9433                info!(
9434                    module_id = %module_id,
9435                    latency_ms,
9436                    "late health.check answer proves the module is alive"
9437                );
9438                match self
9439                    .supervisor
9440                    .record_late_health_answer(&module_id, latency_ms)
9441                {
9442                    Ok(true) => {}
9443                    Ok(false) => debug!(
9444                        module_id = %module_id,
9445                        latency_ms,
9446                        "late health.check answer has no active supervisor snapshot"
9447                    ),
9448                    Err(err) => warn!(
9449                        module_id = %module_id,
9450                        latency_ms,
9451                        error = %err,
9452                        "failed to record late health.check answer"
9453                    ),
9454                }
9455                true
9456            }
9457        }
9458    }
9459
9460    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9461    /// the module connection whose frame is being handled, or to the client that
9462    /// relay was opened for.
9463    ///
9464    /// This runs on the MODULE connection's frame handler, where returning `Err`
9465    /// ends that connection -- and a module connection carries every client's
9466    /// routes to that module, so ending it costs the whole fleet its tools.
9467    /// `ConnectionClosing` carries the id of the connection that is closing, and
9468    /// when that id is a CLIENT's, the condition is entirely about that one
9469    /// client's route.open. A client-scoped condition has no authority over a
9470    /// shared module connection, so it is logged and the single relay is dropped:
9471    /// the client is going away, and `complete_pending_relay` already removed the
9472    /// relay before failing, so there is nothing left to settle. Anything that
9473    /// relay still reserved is released by that client's own connection teardown,
9474    /// which is already under way -- that is what "closing" means.
9475    ///
9476    /// Every other failure is a statement about THIS connection and stays fatal:
9477    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9478    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9479    /// frames correctly.
9480    fn refuse_to_end_module_connection_for_a_client(
9481        &self,
9482        module_connection_id: ConnectionId,
9483        corr: u64,
9484        err: ForwardingError,
9485    ) -> Result<(), RouterError> {
9486        if let ForwardingError::ConnectionClosing { connection_id } = err {
9487            if connection_id != module_connection_id {
9488                warn!(
9489                    module_connection_id = module_connection_id.get(),
9490                    client_connection_id = connection_id.get(),
9491                    corr,
9492                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9493                );
9494                return Ok(());
9495            }
9496        }
9497        Err(RouterError::Forwarding(err))
9498    }
9499
9500    fn handle_module_relay_response(
9501        &self,
9502        connection_id: ConnectionId,
9503        frame: Frame,
9504    ) -> Result<Vec<Frame>, RouterError> {
9505        let mut secondary_error = None;
9506        let outcome = match frame.header.ty {
9507            FrameType::Response => match module_control_response_probe(&frame.body) {
9508                Ok(probe) if probe.op == "route.bind" => {
9509                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9510                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9511                            RouteBindRelayOutcome::Accepted
9512                        }
9513                        Ok(other) => {
9514                            let message =
9515                                format!("route.bind response carried unexpected body: {other:?}");
9516                            secondary_error = Some(control_error_frame(
9517                                &frame,
9518                                "invalid_control_body",
9519                                message.clone(),
9520                            )?);
9521                            RouteBindRelayOutcome::ModuleGone(message)
9522                        }
9523                        Err(err) => {
9524                            let message = format!("malformed route.bind response body: {err}");
9525                            secondary_error = Some(control_error_frame(
9526                                &frame,
9527                                "invalid_control_body",
9528                                message.clone(),
9529                            )?);
9530                            RouteBindRelayOutcome::ModuleGone(message)
9531                        }
9532                    }
9533                }
9534                Ok(probe) => {
9535                    let outcome = if matches!(
9536                        probe.op.as_str(),
9537                        "config.review" | "consent/v1" | "projects.enumerate"
9538                    ) {
9539                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9540                    } else {
9541                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9542                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9543                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9544                                "malformed {} response body: {err}",
9545                                probe.op
9546                            )),
9547                        }
9548                    };
9549                    let completion = self
9550                        .forwarding
9551                        .complete_module_control_rpc(
9552                            connection_id,
9553                            frame.header.corr,
9554                            Some(&probe.op),
9555                            outcome,
9556                        )
9557                        .map_err(RouterError::Forwarding)?;
9558                    if !self.observe_module_control_completion(completion) {
9559                        debug!(
9560                            connection_id = connection_id.get(),
9561                            corr = frame.header.corr,
9562                            op = %probe.op,
9563                            "dropping late or unknown module-control RPC response"
9564                        );
9565                    }
9566                    return Ok(Vec::new());
9567                }
9568                Err(err) => {
9569                    if let Some(expected_op) = self
9570                        .forwarding
9571                        .pending_module_control_op(connection_id, frame.header.corr)
9572                        .map_err(RouterError::Forwarding)?
9573                    {
9574                        let completion = self
9575                            .forwarding
9576                            .complete_module_control_rpc(
9577                                connection_id,
9578                                frame.header.corr,
9579                                None,
9580                                ModuleControlRpcOutcome::MalformedResponse(format!(
9581                                    "malformed {expected_op} response body: {err}"
9582                                )),
9583                            )
9584                            .map_err(RouterError::Forwarding)?;
9585                        if !self.observe_module_control_completion(completion) {
9586                            debug!(
9587                                connection_id = connection_id.get(),
9588                                corr = frame.header.corr,
9589                                "dropping late malformed module-control RPC response"
9590                            );
9591                        }
9592                        return Ok(Vec::new());
9593                    }
9594                    let message = format!("malformed route.bind response body: {err}");
9595                    secondary_error = Some(control_error_frame(
9596                        &frame,
9597                        "invalid_control_body",
9598                        message.clone(),
9599                    )?);
9600                    RouteBindRelayOutcome::ModuleGone(message)
9601                }
9602            },
9603            FrameType::Error => {
9604                if self
9605                    .forwarding
9606                    .pending_module_control_op(connection_id, frame.header.corr)
9607                    .map_err(RouterError::Forwarding)?
9608                    .is_some()
9609                {
9610                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9611                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9612                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9613                            "malformed module-control ERROR body: {err}"
9614                        )),
9615                    };
9616                    let completion = self
9617                        .forwarding
9618                        .complete_module_control_rpc(
9619                            connection_id,
9620                            frame.header.corr,
9621                            None,
9622                            outcome,
9623                        )
9624                        .map_err(RouterError::Forwarding)?;
9625                    if !self.observe_module_control_completion(completion) {
9626                        debug!(
9627                            connection_id = connection_id.get(),
9628                            corr = frame.header.corr,
9629                            "dropping late or unknown module-control RPC error"
9630                        );
9631                    }
9632                    return Ok(Vec::new());
9633                }
9634                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9635                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9636                    Err(err) => {
9637                        let message = format!("malformed route.bind ERROR body: {err}");
9638                        secondary_error = Some(control_error_frame(
9639                            &frame,
9640                            "invalid_control_body",
9641                            message.clone(),
9642                        )?);
9643                        RouteBindRelayOutcome::ModuleGone(message)
9644                    }
9645                }
9646            }
9647            ty => {
9648                return Ok(vec![control_error_frame(
9649                    &frame,
9650                    "unsupported_control_frame",
9651                    format!("unsupported module channel-0 frame {ty:?}"),
9652                )?])
9653            }
9654        };
9655
9656        let settled =
9657            self.forwarding
9658                .complete_pending_relay(connection_id, frame.header.corr, outcome);
9659        let completion = match settled {
9660            Ok(completion) => completion,
9661            Err(err) => {
9662                self.refuse_to_end_module_connection_for_a_client(
9663                    connection_id,
9664                    frame.header.corr,
9665                    err,
9666                )?;
9667                return Ok(secondary_error.into_iter().collect());
9668            }
9669        };
9670        if let Some(target) = completion.abandoned.as_ref() {
9671            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9672        }
9673        if !completion.settled {
9674            debug!(
9675                connection_id = connection_id.get(),
9676                corr = frame.header.corr,
9677                frame_type = ?frame.header.ty,
9678                "dropping late or unknown route.bind relay response"
9679            );
9680        }
9681        Ok(secondary_error.into_iter().collect())
9682    }
9683
9684    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9685        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9686        // GOODBYE ends the connection's logical session even when its socket
9687        // stays open. Use disconnect teardown so verdicts, client notices and
9688        // scope authority are released at the same lifecycle boundary.
9689        self.cleanup_connection_with_end_reason(
9690            connection_id,
9691            RegistrationEndReason::ExplicitGoodbye,
9692        )
9693        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9694        Ok(Vec::new())
9695    }
9696}
9697
9698impl Default for ControlHandler {
9699    fn default() -> Self {
9700        Self::new(Arc::new(Registry::default()))
9701    }
9702}
9703
9704impl crate::supervise::SwapPromotionObserver for ControlHandler {
9705    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9706        self.apply_registration_capabilities(registration);
9707    }
9708}
9709
9710fn capability_requirement_status(status: RequirementStatus) -> CapabilityRequirementStatus {
9711    CapabilityRequirementStatus {
9712        consumer: status.consumer,
9713        capability: status.capability,
9714        need: match status.need {
9715            subc_protocol::manifest::CapabilityNeed::Required => "required".to_string(),
9716            subc_protocol::manifest::CapabilityNeed::Optional => "optional".to_string(),
9717        },
9718        verdict: status.verdict.as_str().to_string(),
9719        episode_seq: status.episode_seq,
9720        config_satisfiable: status.config_satisfiable,
9721        runtime_available: status.runtime_available,
9722        detail: status.detail,
9723    }
9724}
9725
9726fn append_capability_problem_detail(
9727    detail: Option<String>,
9728    capability_detail: Option<String>,
9729) -> Option<String> {
9730    match (detail, capability_detail) {
9731        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9732        (Some(detail), None) => Some(detail),
9733        (None, Some(capability_detail)) => Some(capability_detail),
9734        (None, None) => None,
9735    }
9736}
9737
9738fn subc_ops() -> Vec<String> {
9739    SUBC_CONTROL_OPS
9740        .iter()
9741        .map(|op| (*op).to_string())
9742        .collect()
9743}
9744
9745fn module_subc_ops() -> Vec<String> {
9746    SUBC_CONTROL_OPS
9747        .iter()
9748        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9749        .map(|op| (*op).to_string())
9750        .collect()
9751}
9752
9753#[cfg(test)]
9754fn module_baseline_control_ops() -> Vec<String> {
9755    MODULE_BASELINE_CONTROL_OPS
9756        .iter()
9757        .map(|op| (*op).to_string())
9758        .collect()
9759}
9760
9761fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9762    let mut seen = HashSet::new();
9763    let mut effective = Vec::new();
9764    for op in MODULE_BASELINE_CONTROL_OPS {
9765        if seen.insert((*op).to_string()) {
9766            effective.push((*op).to_string());
9767        }
9768    }
9769    for op in declared.unwrap_or_default() {
9770        if seen.insert(op.clone()) {
9771            effective.push(op);
9772        }
9773    }
9774    effective
9775}
9776
9777fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9778    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9779}
9780
9781fn target_module_id(target: &RouteTarget) -> &str {
9782    match target {
9783        RouteTarget::ToolProvider { module_id }
9784        | RouteTarget::ManagementSurface { module_id }
9785        | RouteTarget::InternalService { module_id, .. } => module_id,
9786    }
9787}
9788
9789fn target_has_required_role(
9790    target: &RouteTarget,
9791    roles: &[crate::registry::AdmissionRole],
9792) -> bool {
9793    use crate::registry::AdmissionRole;
9794    roles.iter().any(|role| match (target, role) {
9795        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9796        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9797        (
9798            RouteTarget::InternalService { service_id, .. },
9799            AdmissionRole::InternalService(provided),
9800        ) => service_id == provided,
9801        _ => false,
9802    })
9803}
9804
9805fn is_routable_role(role: &ProviderRole) -> bool {
9806    matches!(
9807        role,
9808        ProviderRole::ToolProvider { .. }
9809            | ProviderRole::ManagementSurface { .. }
9810            | ProviderRole::InternalService { .. }
9811    )
9812}
9813
9814#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9815enum ControlRequestBodyError {
9816    UnknownOp,
9817    InvalidBody,
9818}
9819
9820#[derive(Debug, Deserialize)]
9821struct ControlOpProbe {
9822    op: String,
9823}
9824
9825fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9826    serde_json::from_slice(body).or_else(|original| {
9827        #[derive(Deserialize)]
9828        struct ConsentProbe {
9829            protocol: String,
9830        }
9831        match serde_json::from_slice::<ConsentProbe>(body) {
9832            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9833                Ok(ControlOpProbe { op: probe.protocol })
9834            }
9835            _ => Err(original),
9836        }
9837    })
9838}
9839
9840/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9841/// this set is treated as a forward-compat unknown and ignored rather than errored.
9842const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9843
9844fn is_known_module_push_op(body: &[u8]) -> bool {
9845    serde_json::from_slice::<ControlOpProbe>(body)
9846        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9847        .unwrap_or(false)
9848}
9849
9850fn is_known_module_request_op(body: &[u8]) -> bool {
9851    serde_json::from_slice::<ControlOpProbe>(body)
9852        .map(|probe| is_module_to_subc_op(&probe.op))
9853        .unwrap_or(false)
9854}
9855
9856fn is_module_to_subc_op(op: &str) -> bool {
9857    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9858}
9859
9860fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9861    debug!(
9862        op = %op,
9863        connection_id = connection_id.get(),
9864        corr,
9865        "control dispatch"
9866    );
9867}
9868
9869fn log_slow_control_dispatch(
9870    dispatch_started_at: Option<StdInstant>,
9871    op: &'static str,
9872    connection_id: ConnectionId,
9873    corr: u64,
9874    route_open_timings: Option<&RouteOpenTimings>,
9875) {
9876    let Some(dispatch_started_at) = dispatch_started_at else {
9877        return;
9878    };
9879    // Use the same monotonic clock as the phase timers and relay deadline.
9880    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9881    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9882        if let Some(timings) = route_open_timings {
9883            warn!(
9884                op = %op,
9885                connection_id = connection_id.get(),
9886                corr,
9887                elapsed_ms = elapsed.as_millis() as u64,
9888                module_id = ?timings.module_id,
9889                principal = %timings.principal,
9890                admission_ms = timings.admission.as_millis() as u64,
9891                project_root_ms = timings.project_root.as_millis() as u64,
9892                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9893                bind_send_ms = timings.bind_send.as_millis() as u64,
9894                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9895                "slow control dispatch"
9896            );
9897            return;
9898        }
9899        warn!(
9900            op = %op,
9901            connection_id = connection_id.get(),
9902            corr,
9903            elapsed_ms = elapsed.as_millis() as u64,
9904            "slow control dispatch"
9905        );
9906    }
9907}
9908
9909/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9910#[cfg(test)]
9911type TestCallerLookup =
9912    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9913
9914/// Every new client operation needs an explicit privilege decision here.
9915fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9916    request.privileged_operation()
9917}
9918
9919trait PrivilegedRequest {
9920    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9921}
9922
9923impl PrivilegedRequest for ClientControlRequest {
9924    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9925        let request = self;
9926        match request {
9927        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9928            Some(PrivilegedOperation::Restart { module_id })
9929        }
9930        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9931            Some(PrivilegedOperation::Swap { module_id })
9932        }
9933        ClientControlRequest::SupervisorReload { module_id } => {
9934            Some(PrivilegedOperation::Reload { module_id })
9935        }
9936        ClientControlRequest::SupervisorRescan { preview } => {
9937            if *preview {
9938                None
9939            } else {
9940                Some(PrivilegedOperation::Rescan)
9941            }
9942        }
9943        // Only the well-formed apply asks for approval. A preview changes
9944        // nothing, and any other combination is refused before it touches
9945        // anything, so prompting the operator for it would ask about a request
9946        // that cannot run.
9947        ClientControlRequest::SupervisorRescanChecked {
9948            preview,
9949            candidate,
9950            expect,
9951        } => (!*preview && candidate.is_none() && expect.is_some())
9952            .then_some(PrivilegedOperation::Rescan),
9953        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9954            Some(PrivilegedOperation::SetEnabled {
9955                module_id,
9956                enabled: *enabled,
9957            })
9958        }
9959        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9960            Some(PrivilegedOperation::ReleaseReserved { module_id })
9961        }
9962        ClientControlRequest::ServerDescribe {}
9963        // The announcement uses the same client admission as supervisor.restart,
9964        // but cannot stop anything itself and needs no operator confirmation.
9965        | ClientControlRequest::DaemonShutdownIntent { .. }
9966        | ClientControlRequest::CatalogList { .. }
9967        | ClientControlRequest::RouteOpen { .. }
9968        | ClientControlRequest::RoutePoll { .. }
9969        | ClientControlRequest::SupervisorList {}
9970        | ClientControlRequest::SupervisorHealth {}
9971        | ClientControlRequest::SupervisorHealthProbe { .. }
9972        | ClientControlRequest::SupervisorRoutes { .. }
9973        | ClientControlRequest::SupervisorProvenance { .. }
9974        | ClientControlRequest::SupervisorStderrTail { .. }
9975        | ClientControlRequest::SupervisorTerminals { .. }
9976        | ClientControlRequest::SupervisorSpawnSnapshot {}
9977        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9978    }
9979    }
9980}
9981
9982fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9983    match request {
9984        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9985        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9986        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
9987        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
9988        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
9989        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
9990        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
9991        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
9992        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
9993        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
9994        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
9995        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
9996        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
9997        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
9998        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
9999        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
10000        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
10001        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
10002        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
10003        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
10004        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
10005    }
10006}
10007
10008/// The caller of one `route.open`, as its `route.open refused` line names it.
10009///
10010/// A connection id alone cannot name a caller after the fact: ids restart at
10011/// every daemon restart, so the same number belongs to different modules
10012/// before and after one. These three fields are what the refused line needs
10013/// to be attributable on its own, and they are rendered with the same helpers
10014/// as the `route.open accepted` line so both directions grep alike.
10015struct RouteOpenCaller {
10016    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
10017    /// when the request presented a consumer identity whose launch nonce did
10018    /// not verify. The claimed module id is never printed as a principal.
10019    principal: String,
10020    /// `none` for an unscoped open; the admitted stamp's label once scope
10021    /// admission issued one; before that, the requested selector's label.
10022    scope: String,
10023    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
10024    /// because it is a string the caller chose.
10025    harness: String,
10026}
10027
10028impl RouteOpenCaller {
10029    fn new(
10030        principal: Option<&Principal>,
10031        scope: Option<&ScopeSelector>,
10032        identity: &BindIdentity,
10033    ) -> Self {
10034        Self {
10035            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
10036            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
10037            harness: bounded_log_text(&identity.harness),
10038        }
10039    }
10040
10041    /// For a refusal that has no parsed request at hand: names whatever the
10042    /// frame still says, and `unknown` where it says nothing parseable.
10043    fn unknown() -> Self {
10044        Self {
10045            principal: "unknown".to_string(),
10046            scope: "unknown".to_string(),
10047            harness: "unknown".to_string(),
10048        }
10049    }
10050}
10051
10052/// Longest client-chosen text (a scope ref, a harness) a route.open log line
10053/// prints before cutting it.
10054const MAX_LOGGED_TEXT_CHARS: usize = 64;
10055
10056/// `value` Debug-quoted, so control characters land escaped and cannot forge
10057/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
10058/// `…` inside the quotes so one request cannot flood the line.
10059fn bounded_log_text(value: &str) -> String {
10060    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
10061    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
10062        bounded.push('…');
10063    }
10064    format!("{bounded:?}")
10065}
10066
10067/// The `scope=` field of the `route.open accepted` line, from the stamp that
10068/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
10069/// so a ref holding control characters cannot forge a log line, and cut to 64
10070/// characters with a trailing `…` to bound the line. The bind proof and the
10071/// scope's attributes never appear.
10072fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
10073    use subc_protocol::scope::ScopeKind;
10074    let kind = match stamp.kind {
10075        ScopeKind::Head => "head",
10076        ScopeKind::Worker => "worker",
10077        ScopeKind::Ephemeral => "ephemeral",
10078        ScopeKind::Federated => "federated",
10079        _ => "unknown",
10080    };
10081    format!(
10082        "{kind}/{}/{}@{}",
10083        principal_label(&stamp.owner),
10084        bounded_log_text(&stamp.scope_ref),
10085        stamp.scope_epoch
10086    )
10087}
10088
10089/// The `scope=` field of a `route.open refused` line for an open refused
10090/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
10091/// The kind is not known yet, so the literal `requested` stands in its place.
10092/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
10093/// owner it has not been checked against the configured modules: a quoted
10094/// owner means the value was never validated. The bind proof never appears.
10095fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10096    let epoch = selector
10097        .scope_epoch
10098        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10099    format!(
10100        "requested/{}/{}@{epoch}",
10101        bounded_log_text(&principal_label(&selector.owner)),
10102        bounded_log_text(&selector.scope_ref),
10103    )
10104}
10105
10106fn principal_label(principal: &Principal) -> String {
10107    match principal {
10108        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10109        Principal::Direct => "direct".to_string(),
10110        other => format!("{other:?}"),
10111    }
10112}
10113
10114fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10115    match request {
10116        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10117        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10118            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10119        }
10120        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10121        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10122        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10123        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10124        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10125            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10126        }
10127        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10128        _ => "unsupported",
10129    }
10130}
10131
10132fn parse_client_control_request(
10133    body: &[u8],
10134) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10135    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10136        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10137            Ok(probe)
10138                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10139                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10140            {
10141                ControlRequestBodyError::InvalidBody
10142            }
10143            Ok(_) => ControlRequestBodyError::UnknownOp,
10144            Err(_) => ControlRequestBodyError::InvalidBody,
10145        };
10146        (err, classification)
10147    })
10148}
10149
10150fn parse_module_control_request_from_module(
10151    body: &[u8],
10152) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10153    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10154        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10155            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10156            Ok(_) => ControlRequestBodyError::UnknownOp,
10157            Err(_) => ControlRequestBodyError::InvalidBody,
10158        };
10159        (err, classification)
10160    })
10161}
10162
10163#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10164enum ProviderRoleKind {
10165    ToolProvider,
10166    PipelineStage,
10167    ManagementSurface,
10168    InternalService,
10169}
10170
10171fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10172    match role {
10173        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10174        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10175        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10176        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10177    }
10178}
10179
10180fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10181    roles.iter().map(provider_role_kind).collect()
10182}
10183
10184/// Most refused scope records named individually in the log per sync; the
10185/// `refused` count on the accepted line is always complete.
10186const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10187
10188/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10189#[derive(Debug, Default, PartialEq, Eq)]
10190struct ScopeOutcomeCounts {
10191    created: usize,
10192    replaced: usize,
10193    updated: usize,
10194    unchanged: usize,
10195    refused: usize,
10196}
10197
10198impl ScopeOutcomeCounts {
10199    fn of(results: &[ScopeRecordResult]) -> Self {
10200        let mut counts = Self::default();
10201        for result in results {
10202            let slot = match result.outcome {
10203                ScopeRecordOutcome::Created => &mut counts.created,
10204                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10205                ScopeRecordOutcome::Updated => &mut counts.updated,
10206                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10207                ScopeRecordOutcome::Refused => &mut counts.refused,
10208            };
10209            *slot += 1;
10210        }
10211        counts
10212    }
10213}
10214
10215#[cfg(test)]
10216mod scope_outcome_count_tests {
10217    use super::*;
10218
10219    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10220        ScopeRecordResult {
10221            scope_ref: "r".to_string(),
10222            scope_epoch: 1,
10223            outcome,
10224            code: None,
10225            message: None,
10226            version: None,
10227            parent_state: None,
10228        }
10229    }
10230
10231    /// Each outcome lands in its own count, so a refused record can never be
10232    /// hidden inside the total the log already printed.
10233    #[test]
10234    fn every_outcome_is_counted_in_its_own_field() {
10235        let results = [
10236            result(ScopeRecordOutcome::Created),
10237            result(ScopeRecordOutcome::Created),
10238            result(ScopeRecordOutcome::Replaced),
10239            result(ScopeRecordOutcome::Updated),
10240            result(ScopeRecordOutcome::Unchanged),
10241            result(ScopeRecordOutcome::Refused),
10242            result(ScopeRecordOutcome::Refused),
10243            result(ScopeRecordOutcome::Refused),
10244        ];
10245        assert_eq!(
10246            ScopeOutcomeCounts::of(&results),
10247            ScopeOutcomeCounts {
10248                created: 2,
10249                replaced: 1,
10250                updated: 1,
10251                unchanged: 1,
10252                refused: 3,
10253            }
10254        );
10255    }
10256}
10257
10258/// Return whether a catalog change can create a newly violating live route.
10259/// Removing an attested claim is intentionally excluded: it makes fewer routes
10260/// forbidden and therefore must leave the existing route census untouched.
10261fn capability_census_trigger(
10262    old: Option<&CapabilityDeclarations>,
10263    new: Option<&CapabilityDeclarations>,
10264) -> bool {
10265    let old_provides = old
10266        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10267        .unwrap_or_default();
10268    let old_denies = old
10269        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10270        .unwrap_or_default();
10271    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10272        provides: Vec::new(),
10273        requires: Vec::new(),
10274        must_never_reach: Vec::new(),
10275    });
10276
10277    new.provides
10278        .iter()
10279        .any(|capability| !old_provides.contains(capability))
10280        || new
10281            .must_never_reach
10282            .iter()
10283            .any(|capability| !old_denies.contains(capability))
10284}
10285
10286fn catalog_update_frozen_field_message(
10287    registered: &ModuleManifest,
10288    provides: &[ProviderRole],
10289) -> Option<String> {
10290    let old_has_provides = !registered.provides.is_empty();
10291    let new_has_provides = !provides.is_empty();
10292    if old_has_provides != new_has_provides {
10293        return Some(format!(
10294            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10295            registered.module_id
10296        ));
10297    }
10298
10299    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10300        return Some(format!(
10301            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10302            registered.module_id
10303        ));
10304    }
10305
10306    let registered_concurrency = manifest_concurrency(registered);
10307    let mut candidate = registered.clone();
10308    candidate.provides = provides.to_vec();
10309    let candidate_concurrency = manifest_concurrency(&candidate);
10310    if candidate_concurrency != registered_concurrency {
10311        return Some(format!(
10312            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10313            registered.module_id, registered_concurrency, candidate_concurrency
10314        ));
10315    }
10316
10317    // control_ops live beside the manifest in the HELLO body, not inside
10318    // ModuleManifest, so a provides-only catalog.update cannot change them.
10319    None
10320}
10321
10322fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10323    manifest.provides.iter().any(is_routable_role)
10324}
10325
10326/// Returns the routable-provider concurrency subc should enforce for this manifest.
10327///
10328/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10329/// InternalService has no role-specific concurrency field, so it retains the
10330/// existing ModuleManaged default for backward compatibility.
10331fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10332    manifest
10333        .provides
10334        .iter()
10335        .find_map(|provider| match provider {
10336            ProviderRole::ToolProvider { concurrency, .. }
10337            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10338            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10339        })
10340        .unwrap_or(Concurrency::ModuleManaged)
10341}
10342
10343/// True when the manifest carries a ManagementSurface role whose concurrency
10344/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10345/// bytes because the typed manifest deliberately erases that distinction: the
10346/// default exists for wire compatibility, and this probe exists so the default
10347/// stays observable. Any parse irregularity returns false -- the caller only
10348/// logs, and a malformed body already failed registration upstream.
10349fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10350    let has_management_surface = manifest
10351        .provides
10352        .iter()
10353        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10354    if !has_management_surface {
10355        return false;
10356    }
10357    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10358        return false;
10359    };
10360    let Some(provides) = raw
10361        .get("manifest")
10362        .and_then(|manifest| manifest.get("provides"))
10363        .and_then(serde_json::Value::as_array)
10364    else {
10365        return false;
10366    };
10367    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10368    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10369    // against the management_surface_manifest_without_concurrency golden, not
10370    // recalled (the externally-tagged guess was this function's first bug).
10371    provides.iter().any(|role| {
10372        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10373            && role.get("concurrency").is_none()
10374    })
10375}
10376
10377fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10378    if peer_version != PROTOCOL_VERSION {
10379        return Err(format!(
10380            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10381        ));
10382    }
10383    Ok(PROTOCOL_VERSION)
10384}
10385
10386fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10387    Frame::build_with_version(
10388        response_version(frame),
10389        FrameType::Pong,
10390        frame.header.flags,
10391        0,
10392        0,
10393        frame.header.corr,
10394        Vec::new(),
10395    )
10396    .map_err(RouterError::FrameBuild)
10397}
10398
10399pub(crate) fn control_error_frame(
10400    frame: &Frame,
10401    code: &'static str,
10402    message: impl Into<String>,
10403) -> Result<Frame, RouterError> {
10404    control_error_body_frame(
10405        frame,
10406        ErrorBody {
10407            code: code.to_string(),
10408            message: message.into(),
10409            detail: None,
10410        },
10411    )
10412}
10413
10414/// A channel-0 ERROR for a refusal the daemon decided itself: every
10415/// route.open refusal, the drain `module_reloading` and scope-change/end
10416/// bodies, spawn-subscription and supervisor refusals. Carries the
10417/// daemon-origin bit, which is what lets a client treat `module_reloading`
10418/// as proof that its request never reached a module. Response, push,
10419/// goodbye and relay-request frames keep the plain control flags in their
10420/// own builders.
10421pub(crate) fn control_error_body_frame(
10422    frame: &Frame,
10423    error: ErrorBody,
10424) -> Result<Frame, RouterError> {
10425    control_error_frame_with_flags(frame, error, daemon_error_flags())
10426}
10427
10428/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10429/// refused route.bind answered as a route.open refusal, or a refused
10430/// module-control RPC. Plain control flags — the code and message are
10431/// module-chosen, so the frame must not claim daemon authorship, even when
10432/// the module picks a daemon code like `module_reloading`.
10433fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10434    control_error_frame_with_flags(frame, error, control_flags())
10435}
10436
10437fn control_error_frame_with_flags(
10438    frame: &Frame,
10439    error: ErrorBody,
10440    flags: Flags,
10441) -> Result<Frame, RouterError> {
10442    let body = serde_json::to_vec(&error).map_err(|err| {
10443        RouterError::backend(
10444            0,
10445            frame.header.corr,
10446            format!("failed to encode control ERROR: {err}"),
10447        )
10448    })?;
10449
10450    Frame::build_with_version(
10451        response_version(frame),
10452        FrameType::Error,
10453        flags,
10454        0,
10455        0,
10456        frame.header.corr,
10457        body,
10458    )
10459    .map_err(RouterError::FrameBuild)
10460}
10461
10462pub(crate) fn control_response_body_frame<T: Serialize>(
10463    frame: &Frame,
10464    reply: &T,
10465    label: &'static str,
10466) -> Result<Frame, RouterError> {
10467    let body = serde_json::to_vec(reply).map_err(|err| {
10468        RouterError::backend(
10469            0,
10470            frame.header.corr,
10471            format!("failed to encode {label}: {err}"),
10472        )
10473    })?;
10474
10475    Frame::build_with_version(
10476        response_version(frame),
10477        FrameType::Response,
10478        control_flags(),
10479        0,
10480        0,
10481        frame.header.corr,
10482        body,
10483    )
10484    .map_err(RouterError::FrameBuild)
10485}
10486
10487/// Map a forwarding failure to the wire code a client sees.
10488///
10489/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10490/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10491/// chosen here decides whether a caller retries or gives up.
10492///
10493/// That makes attribution the load-bearing property, not merely having a code. A
10494/// permanent fault published as a retryable one produces a fleet-wide retry storm
10495/// against something that can never recover; a transient fault published as
10496/// permanent gives up on work that would have succeeded. Both look correct in a
10497/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10498/// the mapping per variant rather than merely asserting that some code exists.
10499///
10500/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10501/// two codes on the same side of the boundary passes it. Measured rather than
10502/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10503/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10504/// a test named for something else that happens to assert the string.
10505///
10506/// That accidental coverage is deliberately left alone rather than promoted to a
10507/// named test, because it guards a property this function does not promise.
10508/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10509/// specific code within a class, so identity is free to change and only the
10510/// partition is a contract. Splitting it out would assert a guarantee nothing
10511/// depends on — and a suite that promises more than the code does is the harder
10512/// thing to correct later, because the next reader cannot tell which assertions
10513/// are load-bearing.
10514///
10515/// Pin identity here the moment a consumer branches on a specific code.
10516/// The spawn a HELLO would register as and the provider declarations it
10517/// requests, carried from the HELLO's checks to the point the registry
10518/// accepts it.
10519struct HelloAuthority {
10520    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10521    requested: ProviderDeclarations,
10522    /// Whether admitting this HELLO froze the spawn's requested declarations,
10523    /// so a refusal after admission undoes that freeze and no other.
10524    froze: std::sync::atomic::AtomicBool,
10525}
10526
10527fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10528    match err {
10529        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10530        ForwardingError::NoModuleConnection => "target_unavailable",
10531        ForwardingError::ModuleReloading { .. } => "module_reloading",
10532        ForwardingError::ClientRouteChannelExhausted { .. }
10533        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10534        ForwardingError::StaleModuleEndpoint
10535        | ForwardingError::UnknownReservation { .. }
10536        | ForwardingError::ConnectionClosing { .. }
10537        | ForwardingError::ClientEgressClosed { .. }
10538        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10539        // Only a swap candidate's registration can produce this, and it means
10540        // exactly what a second active HELLO for a live id means.
10541        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10542        ForwardingError::RelayCorrelationExhausted
10543        | ForwardingError::RouteOpenBuild(_)
10544        | ForwardingError::Poisoned => "forwarding_error",
10545    }
10546}
10547
10548fn response_version(frame: &Frame) -> u8 {
10549    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10550        frame.header.ver
10551    } else {
10552        PROTOCOL_VERSION
10553    }
10554}
10555
10556pub(crate) fn control_flags() -> Flags {
10557    Flags::new(false, Priority::Passive, false)
10558}
10559
10560/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10561/// channel. The target is the module (a client never saw the route), so this
10562/// takes the module path: delivered late rather than dropped when the module's
10563/// queue is momentarily full, and never closing its connection.
10564fn send_goodbye_target_best_effort(
10565    counters: &DaemonCounters,
10566    target: &GoodbyeTarget,
10567    context: &'static str,
10568) {
10569    let Ok(frame) = Frame::build_with_version(
10570        target.negotiated_ver,
10571        FrameType::Goodbye,
10572        control_flags(),
10573        target.channel,
10574        target.epoch,
10575        0,
10576        Vec::new(),
10577    ) else {
10578        return;
10579    };
10580    crate::forwarding::send_module_route_goodbye(
10581        counters,
10582        &target.sink,
10583        frame,
10584        target.module_id.as_deref(),
10585        context,
10586    );
10587}
10588
10589fn route_close_reason_for_opener(
10590    reason: RouteCloseReason,
10591    accepts_close_reasons: Option<&[String]>,
10592) -> RouteCloseReason {
10593    if reason == RouteCloseReason::AuthorityChanged
10594        && !accepts_close_reasons
10595            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10596    {
10597        // Older readers forbid reopening for unknown reasons. Reload already
10598        // permits reopening and, like an authority change, requires a new bind.
10599        RouteCloseReason::Reload
10600    } else {
10601        reason
10602    }
10603}
10604
10605pub(crate) fn send_route_control_pushes(
10606    forwarding: &ForwardingTable,
10607    routes: Vec<EndpointRoute>,
10608    push: ClientControlPush,
10609) {
10610    let reason = match &push {
10611        ClientControlPush::RouteClosing { reason, .. }
10612        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10613    };
10614    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10615    for route in routes {
10616        let recipient_reason =
10617            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10618        let target = route.goodbye_target;
10619        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10620            existing.connection_id == target.connection_id && *reason == recipient_reason
10621        }) {
10622            debug_assert_eq!(
10623                existing.negotiated_ver, target.negotiated_ver,
10624                "one connection cannot negotiate multiple frame versions"
10625            );
10626            if !channels.contains(&target.channel) {
10627                channels.push(target.channel);
10628            }
10629            continue;
10630        }
10631        let channel = target.channel;
10632        targets.push((target, recipient_reason, vec![channel]));
10633    }
10634    for (target, recipient_reason, mut channels) in targets {
10635        channels.sort_unstable();
10636        let mut push = push.clone();
10637        match &mut push {
10638            ClientControlPush::RouteClosing {
10639                channels: covered,
10640                reason,
10641                ..
10642            }
10643            | ClientControlPush::RouteClosed {
10644                channels: covered,
10645                reason,
10646                ..
10647            } => {
10648                *covered = channels;
10649                *reason = recipient_reason;
10650            }
10651        }
10652        let body = match serde_json::to_vec(&push) {
10653            Ok(body) => body,
10654            Err(err) => {
10655                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10656                continue;
10657            }
10658        };
10659        let frame = match Frame::build_with_version(
10660            target.negotiated_ver,
10661            FrameType::Push,
10662            control_flags(),
10663            0,
10664            0,
10665            0,
10666            body.clone(),
10667        ) {
10668            Ok(frame) => frame,
10669            Err(err) => {
10670                warn!(
10671                    route_channel = target.channel,
10672                    error = %err,
10673                    "failed to build route lifecycle control PUSH frame"
10674                );
10675                continue;
10676            }
10677        };
10678        if let Err(err) = target.sink.try_send(frame) {
10679            if target.close_on_delivery_failure() {
10680                warn!(
10681                    target_connection_id = target.connection_id.get(),
10682                    route_channel = target.channel,
10683                    error = %err,
10684                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10685                );
10686                let _ = forwarding.escalate_client_delivery_failure(
10687                    target.connection_id,
10688                    target.channel,
10689                    target.epoch,
10690                    CloseReason::new(
10691                        "route_lifecycle_push_delivery_failed",
10692                        format!(
10693                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10694                            target.channel
10695                        ),
10696                    ),
10697                    crate::forwarding::UndeliveredFrame {
10698                        module_id: target.module_id.as_deref(),
10699                        sink: &target.sink,
10700                    },
10701                );
10702            }
10703        }
10704    }
10705}
10706
10707#[cfg(test)]
10708mod tests {
10709    include!("control/agent_commands_tests.rs");
10710    include!("control/supervisor_health_vectors_tests.rs");
10711    include!("control/resource_revision_tests.rs");
10712    include!("control/route_open_recovery_tests.rs");
10713    #[tokio::test]
10714    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10715        let registry = Arc::new(Registry::default());
10716        let handler = ControlHandler::new(registry);
10717        assert_eq!(
10718            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10719            None
10720        );
10721        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10722        hello_via_sink(
10723            &handler,
10724            &ctx,
10725            &mut rx,
10726            hello_frame("daemon", PROTOCOL_VERSION, 1),
10727        )
10728        .await;
10729        assert_eq!(
10730            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10731            Some("daemon".into())
10732        );
10733        assert_eq!(
10734            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10735            None
10736        );
10737        assert_eq!(
10738            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10739            None,
10740            "a registered module is not necessarily supervised"
10741        );
10742        assert_eq!(
10743            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10744            None,
10745            "aggregate provenance has no single target"
10746        );
10747        assert_eq!(
10748            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10749            None
10750        );
10751    }
10752
10753    mod peer_manifest {
10754        include!("peer_manifest_tests.rs");
10755    }
10756    mod catalog_declarations {
10757        include!("control/catalog_tests.rs");
10758    }
10759    mod activity_read {
10760        include!("activity_read_tests.rs");
10761    }
10762
10763    mod lifecycle_activity {
10764        include!("control_lifecycle_tests.rs");
10765    }
10766    #[cfg(unix)]
10767    #[tokio::test]
10768    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10769        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10770        let path = dir.join("subc.jsonc");
10771        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10772            "program":"/bin/sleep","args":["60"],"protocol":"none",
10773            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10774        }}}).to_string()).unwrap();
10775        let mut configured = crate::daemon_config::load(&path)
10776            .unwrap()
10777            .unwrap()
10778            .modules
10779            .pop()
10780            .unwrap();
10781        let registry = std::sync::Arc::new(crate::Registry::default());
10782        let handle = crate::SupervisorHandle::new();
10783        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10784            .with_handle(handle.clone());
10785        let module = supervisor
10786            .supervise_configured_with_health(
10787                configured.module_spec(),
10788                true,
10789                configured.health.clone(),
10790                None,
10791                configured.restart,
10792            )
10793            .unwrap();
10794        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10795        let before = module.status().unwrap().pid;
10796        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10797        configured.health.cadence = std::time::Duration::from_secs(3600);
10798        let health_only = handler
10799            .reconcile_supervised_modules(
10800                &supervisor,
10801                vec![configured.clone()],
10802                false,
10803                Principal::Direct,
10804            )
10805            .await
10806            .unwrap();
10807        assert!(
10808            health_only.0.changed_pending_reload.is_empty(),
10809            "health policy is already applied live"
10810        );
10811        assert_eq!(module.status().unwrap().pid, before);
10812        assert_eq!(
10813            module.configuration().unwrap().1.http,
10814            configured.health.http
10815        );
10816        configured.args = vec!["61".into()];
10817        let launch = handler
10818            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10819            .await
10820            .unwrap();
10821        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10822        assert_eq!(
10823            module.status().unwrap().pid,
10824            before,
10825            "a launch edit is stored until reload"
10826        );
10827        module.drain().await.unwrap();
10828    }
10829    use cortexkit_test_support::ScratchDir;
10830    use std::{
10831        collections::BTreeMap,
10832        fmt,
10833        path::PathBuf,
10834        sync::{Arc, Mutex},
10835        time::Duration,
10836    };
10837
10838    use serde_json::{json, Value};
10839    use subc_protocol::{
10840        manifest::{
10841            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10842            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10843        },
10844        session::HealthStatus,
10845        FrameType,
10846    };
10847
10848    use super::*;
10849    use crate::{
10850        forwarding::{DataRoute, DataRouteState},
10851        registry::ChannelState,
10852        router::FrameSink,
10853        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10854        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10855        RouteCtx, Router,
10856    };
10857    use tokio::{
10858        sync::mpsc,
10859        time::{sleep, Instant},
10860    };
10861    use tracing::{
10862        field::{Field, Visit},
10863        Event, Subscriber,
10864    };
10865    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10866
10867    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10868    ///
10869    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10870    /// is only populated for `tests/*.rs` integration test binaries -- this file
10871    /// compiles as part of the library target, which gets neither. The binary
10872    /// lives in the profile folder this test was built into,
10873    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10874    /// from the test's own path.
10875    ///
10876    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10877    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10878    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10879    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10880    /// `NotFound`, which reads as a broken test rather than an unbuilt
10881    /// dependency -- so state the cause and the remedy instead. Deliberately a
10882    /// panic and not a silent skip: a test that quietly passes when it could not
10883    /// run is worse than one that fails, because it reports health it never
10884    /// verified.
10885    fn fake_aft_stub_path() -> PathBuf {
10886        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10887        assert!(
10888            path.exists(),
10889            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10890             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10891            path.display()
10892        );
10893        path
10894    }
10895
10896    /// Whether clients retry `code` in place: the predicate itself, never a copy
10897    /// of its set. A copied list breaks silently when a code is added to or
10898    /// removed from the real one, and a stale copy here would let exactly the
10899    /// failure this test exists to catch pass.
10900    fn client_retries(code: &str) -> bool {
10901        subc_protocol::error_codes::is_retryable_route_open(code)
10902    }
10903
10904    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10905    /// of failure is worse than publishing none. A permanent fault dressed as
10906    /// retryable makes every client in the fleet retry forever against something
10907    /// that cannot recover; a transient fault dressed as permanent abandons work
10908    /// that would have succeeded.
10909    ///
10910    /// Asserting "a code exists" cannot catch either, because the string is free
10911    /// to say anything. This enumerates every variant and pins which side of the
10912    /// retry boundary it lands on, so a new variant must be classified here
10913    /// deliberately rather than inheriting whichever arm it was appended to.
10914    #[test]
10915    fn retryability_of_forwarding_codes_matches_the_failure() {
10916        // Transient by nature: the target is booting, reloading, or its endpoint
10917        // was swapped mid-flight. Retrying is how these resolve.
10918        let transient = [
10919            ForwardingError::NoModuleConnection,
10920            ForwardingError::ModuleReloading {
10921                module_id: "m".into(),
10922            },
10923            ForwardingError::StaleModuleEndpoint,
10924            ForwardingError::UnknownReservation {
10925                client_channel: 1,
10926                module_channel: 1,
10927            },
10928            ForwardingError::ConnectionClosing {
10929                connection_id: ConnectionId::new(1),
10930            },
10931            ForwardingError::ClientEgressClosed {
10932                connection_id: ConnectionId::new(1),
10933            },
10934            ForwardingError::ModuleEgressUnavailable {
10935                connection_id: ConnectionId::new(1),
10936            },
10937        ];
10938        for err in transient {
10939            let code = forwarding_error_code(&err);
10940            assert!(
10941                client_retries(code),
10942                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10943            );
10944        }
10945
10946        // Not fixed by retrying. Channel and correlation exhaustion need the
10947        // caller to close routes, and a poisoned lock is a daemon that cannot
10948        // recover at all — the worst thing to advertise as retryable, since every
10949        // client would storm a daemon that will never answer.
10950        let permanent = [
10951            ForwardingError::ConnectionRoleConflict {
10952                connection_id: ConnectionId::new(1),
10953            },
10954            ForwardingError::ClientRouteChannelExhausted {
10955                connection_id: ConnectionId::new(1),
10956            },
10957            ForwardingError::ModuleRouteChannelExhausted {
10958                endpoint: ModuleEndpointId {
10959                    connection_id: ConnectionId::new(1),
10960                    generation: 1,
10961                },
10962            },
10963            ForwardingError::RelayCorrelationExhausted,
10964            ForwardingError::RouteOpenBuild("x".into()),
10965            ForwardingError::Poisoned,
10966        ];
10967        for err in permanent {
10968            let code = forwarding_error_code(&err);
10969            assert!(
10970                !client_retries(code),
10971                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10972            );
10973        }
10974    }
10975
10976    /// The principal is the daemon's answer to "who is calling", and modules
10977    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10978    /// plexus gates connector invocation. So a stamp is an authorization input in
10979    /// another process, not a label — and both possible answers SUCCEED, which is
10980    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10981    /// first-party capability to something that never proved it; a supervised one
10982    /// stamped `Direct` silently strips a module of capability it is entitled to.
10983    ///
10984    /// Neither shows up in a test that only checks the bind succeeded. Before this
10985    /// test the only coverage was accidental —
10986    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
10987    /// stamped principal on its way past, so narrowing that wire-shape test to its
10988    /// stated subject would have deleted the last assertion on this value. It
10989    /// still asserts the stamp, which is now redundancy rather than the only
10990    /// guard: both fail under the same mutation, and this one names the reason.
10991    /// SCOPE: this handler's supervisor has spawned nothing, so
10992    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
10993    /// is unreachable here. Both assertions below are refusals, and a mutant that
10994    /// refuses everything would satisfy them.
10995    ///
10996    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
10997    /// spawns a supervised consumer, reads its live nonce, and asserts the module
10998    /// observed `principal.kind == "reserved"` carrying that module_id — verified
10999    /// at source rather than assumed, since a citation is a claim about another
11000    /// file and ages like one. Recorded because a harness that structurally
11001    /// cannot reach an arm reports "none" for that arm identically to one that
11002    /// covers it and found nothing.
11003    #[tokio::test]
11004    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
11005        let handler = ControlHandler::default();
11006        let frame =
11007            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
11008
11009        // Absent consumer_identity is the ordinary case: a human at a terminal, or
11010        // any process holding the connection file. Nothing was proved, so nothing
11011        // may be granted beyond the unattested floor.
11012        let stamped = handler
11013            .route_open_principal(ConnectionId::new(1), &frame, None)
11014            .unwrap()
11015            .unwrap();
11016        assert_eq!(
11017            stamped,
11018            Principal::Direct,
11019            "a caller that proved nothing must not be stamped as a supervised module"
11020        );
11021
11022        // A claimed module_id with a nonce no supervised child was given is a
11023        // forgery attempt, not a weaker caller: it must be REFUSED rather than
11024        // quietly demoted to Direct, or an impersonation attempt looks identical
11025        // to an ordinary unattested connection.
11026        let forged = handler
11027            .route_open_principal(
11028                ConnectionId::new(1),
11029                &frame,
11030                Some(ConsumerIdentity {
11031                    module_id: "aft".to_string(),
11032                    launch_nonce: "not-a-real-nonce".to_string(),
11033                }),
11034            )
11035            .unwrap();
11036        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
11037        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
11038    }
11039
11040    /// The test above hands `route_open_principal` an identity it built itself,
11041    /// which proves the stamping rule and nothing about where the identity comes
11042    /// from. The real producer is a wire body, and the two are joined by a serde
11043    /// field name that nothing else asserts.
11044    ///
11045    /// That join fails quietly in one specific way: an unrecognised key is simply
11046    /// absent after parsing, so a renamed or misspelled `consumer_identity`
11047    /// yields `None` and every supervised module silently drops to `Direct`.
11048    /// Capability-wise that is the safe direction, but it surfaces far from its
11049    /// cause — as a module mysteriously refused bash — and it would pass every
11050    /// test that builds its own input.
11051    ///
11052    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
11053    /// would break every client the moment the daemon gains a field, trading a
11054    /// quiet demotion for a hard refusal on additive change. Asserting the join
11055    /// instead means a rename breaks a test here rather than the fleet.
11056    #[test]
11057    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
11058        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"}}"#;
11059        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
11060        let ClientControlRequest::RouteOpen {
11061            consumer_identity, ..
11062        } = parsed
11063        else {
11064            panic!("route.open body must parse as RouteOpen");
11065        };
11066        assert_eq!(
11067            consumer_identity,
11068            Some(ConsumerIdentity {
11069                module_id: "aft".to_string(),
11070                launch_nonce: "n".to_string(),
11071            }),
11072            "the wire field name must reach the value route_open_principal reads"
11073        );
11074    }
11075
11076    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
11077        ModuleManifest::builder(module_id, "0.1.0")
11078            .protocol_ver(protocol_ver)
11079            .provides(vec![ProviderRole::ToolProvider {
11080                tools: vec![Tool {
11081                    name: "read".to_string(),
11082                    description: None,
11083                    execution_mode: ExecutionMode::Pure,
11084                    schema: json!({"type": "object"}),
11085                }],
11086                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
11087                concurrency: Concurrency::ModuleManaged,
11088                emits_push: true,
11089                sub_supervises: true,
11090            }])
11091            .build()
11092    }
11093
11094    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11095        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11096    }
11097
11098    fn hello_frame_with_control_ops(
11099        module_id: &str,
11100        protocol_ver: u8,
11101        corr: u64,
11102        control_ops: Option<Vec<String>>,
11103    ) -> Frame {
11104        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11105    }
11106
11107    fn hello_frame_with_nonce(
11108        module_id: &str,
11109        protocol_ver: u8,
11110        corr: u64,
11111        launch_nonce: Option<&str>,
11112    ) -> Frame {
11113        hello_frame_full(
11114            module_id,
11115            protocol_ver,
11116            corr,
11117            None,
11118            launch_nonce.map(ToOwned::to_owned),
11119        )
11120    }
11121
11122    fn hello_frame_full(
11123        module_id: &str,
11124        protocol_ver: u8,
11125        corr: u64,
11126        control_ops: Option<Vec<String>>,
11127        launch_nonce: Option<String>,
11128    ) -> Frame {
11129        let body = serde_json::to_vec(&ModuleHelloBody {
11130            manifest: manifest(module_id, protocol_ver),
11131            protocol_ver,
11132            control_ops,
11133            launch_nonce,
11134        })
11135        .unwrap();
11136        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11137    }
11138
11139    fn hello_frame_with_rich_ui(
11140        module_id: &str,
11141        protocol_ver: u8,
11142        corr: u64,
11143        launch_nonce: Option<&str>,
11144        rich_ui: Value,
11145    ) -> Frame {
11146        let mut body = serde_json::to_value(ModuleHelloBody {
11147            manifest: manifest(module_id, protocol_ver),
11148            protocol_ver,
11149            control_ops: None,
11150            launch_nonce: launch_nonce.map(str::to_string),
11151        })
11152        .unwrap();
11153        body["manifest"]["rich_ui"] = rich_ui;
11154        Frame::build(
11155            FrameType::Hello,
11156            control_flags(),
11157            0,
11158            0,
11159            corr,
11160            serde_json::to_vec(&body).unwrap(),
11161        )
11162        .unwrap()
11163    }
11164
11165    fn non_routable_hello_frame_with_control_ops(
11166        module_id: &str,
11167        corr: u64,
11168        control_ops: Option<Vec<String>>,
11169    ) -> Frame {
11170        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11171        manifest.provides.clear();
11172        let body = serde_json::to_vec(&ModuleHelloBody {
11173            manifest,
11174            protocol_ver: PROTOCOL_VERSION,
11175            control_ops,
11176            launch_nonce: None,
11177        })
11178        .unwrap();
11179        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11180    }
11181
11182    fn capability_grammar_hello_frame(
11183        capabilities: Value,
11184        runtime_computed: Option<Value>,
11185        corr: u64,
11186    ) -> Frame {
11187        let mut body = serde_json::to_value(ModuleHelloBody {
11188            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11189            protocol_ver: PROTOCOL_VERSION,
11190            control_ops: None,
11191            launch_nonce: None,
11192        })
11193        .expect("HELLO body serializes");
11194        body["manifest"]["capabilities"] = capabilities;
11195        if let Some(runtime_computed) = runtime_computed {
11196            body["runtime_computed"] = runtime_computed;
11197        }
11198        Frame::build(
11199            FrameType::Hello,
11200            control_flags(),
11201            0,
11202            0,
11203            corr,
11204            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11205        )
11206        .expect("HELLO frame builds")
11207    }
11208
11209    fn channel_request(channel: u16, corr: u64) -> Frame {
11210        Frame::build(
11211            FrameType::Request,
11212            Flags::new(true, Priority::Interactive, false),
11213            channel,
11214            0,
11215            corr,
11216            b"opaque".to_vec(),
11217        )
11218        .unwrap()
11219    }
11220
11221    fn route_ctx(
11222        connection_id: ConnectionId,
11223    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11224        let (tx, rx) = mpsc::channel(8);
11225        (
11226            RouteCtx {
11227                connection_id,
11228                egress: FrameSink::new(tx),
11229            },
11230            rx,
11231        )
11232    }
11233
11234    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11235        serde_json::from_slice(&frame.body).unwrap()
11236    }
11237
11238    /// Register a module over a connection that has a sink and return the
11239    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11240    /// module's own sink rather than returning it as a reply, so the ack is
11241    /// taken off `rx` here and whatever the test reads next is what followed it.
11242    async fn hello_via_sink(
11243        handler: &ControlHandler,
11244        ctx: &RouteCtx,
11245        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11246        hello: Frame,
11247    ) -> Frame {
11248        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11249        assert!(
11250            replies.is_empty(),
11251            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11252        );
11253        let ack = rx
11254            .try_recv()
11255            .expect("HELLO_ACK is queued on the module sink")
11256            .frame;
11257        assert_eq!(ack.header.ty, FrameType::HelloAck);
11258        ack
11259    }
11260
11261    fn parse_error(frame: &Frame) -> Value {
11262        serde_json::from_slice(&frame.body).unwrap()
11263    }
11264
11265    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11266        serde_json::from_slice(&frame.body).unwrap()
11267    }
11268
11269    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11270        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11271            route_channel,
11272            route_epoch: 0,
11273            kind,
11274        })
11275        .unwrap();
11276        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11277    }
11278
11279    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11280        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11281            module_id: module_id.to_string(),
11282        })
11283        .unwrap();
11284        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11285    }
11286
11287    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11288        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11289    }
11290
11291    // Exercise retired opener fields without putting them back in BindIdentity.
11292    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11293        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11294        let mut frame = route_open_frame(corr, module_id, root);
11295        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11296        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11297        frame.body = serde_json::to_vec(&body).unwrap();
11298        frame
11299    }
11300
11301    fn route_open_frame_with_consumer_capabilities(
11302        corr: u64,
11303        module_id: &str,
11304        _project_root: ScratchDir,
11305        consumer_capabilities: Option<Vec<String>>,
11306    ) -> Frame {
11307        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11308            busy_refusals: None,
11309            target: RouteTarget::ToolProvider {
11310                module_id: module_id.to_string(),
11311            },
11312            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11313            consumer_identity: None,
11314            consumer_capabilities,
11315            role_versions: None,
11316            admission_facts: None,
11317            scope: None,
11318        })
11319        .unwrap();
11320        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11321    }
11322
11323    fn route_open_frame_with_role_versions(
11324        corr: u64,
11325        module_id: &str,
11326        _project_root: ScratchDir,
11327        role_versions: Option<BTreeMap<String, String>>,
11328    ) -> Frame {
11329        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11330            busy_refusals: None,
11331            target: RouteTarget::ToolProvider {
11332                module_id: module_id.to_string(),
11333            },
11334            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11335            consumer_identity: None,
11336            consumer_capabilities: None,
11337            role_versions,
11338            admission_facts: None,
11339            scope: None,
11340        })
11341        .unwrap();
11342        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11343    }
11344
11345    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11346        entries
11347            .iter()
11348            .map(|(role, version)| (role.to_string(), version.to_string()))
11349            .collect()
11350    }
11351
11352    fn route_open_frame_with_admission_facts(
11353        corr: u64,
11354        module_id: &str,
11355        _project_root: ScratchDir,
11356        consumer_identity: Option<subc_control::ConsumerIdentity>,
11357        facts: Option<Value>,
11358    ) -> Frame {
11359        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11360            busy_refusals: None,
11361            target: RouteTarget::ToolProvider {
11362                module_id: module_id.to_string(),
11363            },
11364            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11365            consumer_identity,
11366            consumer_capabilities: None,
11367            role_versions: None,
11368            admission_facts: facts,
11369            scope: None,
11370        })
11371        .unwrap();
11372        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11373    }
11374
11375    #[derive(Clone, Default)]
11376    struct EventCapture {
11377        events: Arc<Mutex<Vec<CapturedEvent>>>,
11378    }
11379
11380    #[derive(Clone, Debug)]
11381    struct CapturedEvent {
11382        target: String,
11383        level: tracing::Level,
11384        fields: BTreeMap<String, String>,
11385    }
11386
11387    impl EventCapture {
11388        fn events(&self) -> Vec<CapturedEvent> {
11389            self.events.lock().unwrap().clone()
11390        }
11391    }
11392
11393    impl<S> Layer<S> for EventCapture
11394    where
11395        S: Subscriber,
11396    {
11397        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11398            let mut visitor = EventFieldVisitor::default();
11399            event.record(&mut visitor);
11400            self.events.lock().unwrap().push(CapturedEvent {
11401                target: event.metadata().target().to_string(),
11402                level: *event.metadata().level(),
11403                fields: visitor.fields,
11404            });
11405        }
11406    }
11407
11408    #[derive(Default)]
11409    struct EventFieldVisitor {
11410        fields: BTreeMap<String, String>,
11411    }
11412
11413    impl Visit for EventFieldVisitor {
11414        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11415            self.fields
11416                .insert(field.name().to_string(), format!("{value:?}"));
11417        }
11418    }
11419
11420    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11421        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11422            status,
11423            detail: Some("warming".to_string()),
11424            metrics: Some(json!({"queue_depth": 3})),
11425        })
11426        .unwrap();
11427        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11428    }
11429
11430    fn route_bind_ack(corr: u64) -> Frame {
11431        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11432        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11433    }
11434
11435    fn unique_project_root(label: &str) -> ScratchDir {
11436        ScratchDir::new(label)
11437    }
11438
11439    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11440        match parse_route_poll(frame) {
11441            ClientControlResponse::RoutePoll {
11442                status: None,
11443                live: Some(live),
11444                ..
11445            } => assert_eq!(live, expected_live),
11446            other => panic!("unexpected route.poll response: {other:?}"),
11447        }
11448    }
11449
11450    fn bind_liveness_route(
11451        registry: &Registry,
11452        forwarding: &ForwardingTable,
11453        module_id: &str,
11454    ) -> (RouteCtx, u16, u32) {
11455        let module_connection = ConnectionId::new(101);
11456        let client_connection = ConnectionId::new(202);
11457        let registration = registry
11458            .register_with_control_ops(
11459                manifest(module_id, PROTOCOL_VERSION),
11460                PROTOCOL_VERSION,
11461                module_connection,
11462                module_baseline_control_ops(),
11463            )
11464            .unwrap();
11465        let (module_tx, _module_rx) = mpsc::channel(8);
11466        let endpoint = forwarding
11467            .register_module_connection(
11468                module_connection,
11469                module_id.to_string(),
11470                PROTOCOL_VERSION,
11471                manifest_concurrency(&registration.manifest),
11472                FrameSink::new(module_tx),
11473            )
11474            .unwrap();
11475        let (client_ctx, _client_rx) = route_ctx(client_connection);
11476        let pending = forwarding
11477            .begin_route_bind_relay_for_test(
11478                client_connection,
11479                client_ctx.egress.clone(),
11480                1,
11481                module_id,
11482            )
11483            .unwrap();
11484        assert_eq!(pending.endpoint, endpoint);
11485        let route_channel = pending.client_channel;
11486        let route_epoch = pending.client_epoch;
11487        forwarding
11488            .complete_pending_relay(
11489                module_connection,
11490                pending.corr,
11491                RouteBindRelayOutcome::Accepted,
11492            )
11493            .unwrap();
11494        (client_ctx, route_channel, route_epoch)
11495    }
11496
11497    struct FakeProcessLiveness {
11498        live: Option<bool>,
11499    }
11500
11501    impl ModuleProcessLiveness for FakeProcessLiveness {
11502        fn process_live(&self, _module_id: &str) -> Option<bool> {
11503            self.live
11504        }
11505    }
11506
11507    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11508    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11509    {
11510        let registry = Arc::new(Registry::default());
11511        let supervisor_handle = SupervisorHandle::new();
11512        let supervisor = Supervisor::new_for_test(
11513            Arc::clone(&registry),
11514            RestartPolicy::new(1, Duration::from_millis(10)),
11515        )
11516        .with_handle(supervisor_handle.clone());
11517        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11518        let module = supervisor
11519            .spawn(ModuleSpec {
11520                script: None,
11521                carry_containment: false,
11522                module_id: "stderr-tail-wire".to_string(),
11523                program: fake_aft_stub_path(),
11524                args: Vec::new(),
11525                env: vec![
11526                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11527                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11528                ],
11529                reserved: false,
11530                reserved_prefixes: Vec::new(),
11531                protocol: ModuleProtocol::Subc,
11532                overlap: Default::default(),
11533            })
11534            .unwrap();
11535
11536        let deadline = Instant::now() + Duration::from_secs(5);
11537        loop {
11538            let tail = module.stderr_tail(None, None);
11539            if tail
11540                .entries
11541                .iter()
11542                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11543                && tail.entries.iter().any(|entry| {
11544                    matches!(
11545                        entry,
11546                        TailEntry::Line {
11547                            truncated: true,
11548                            ..
11549                        }
11550                    )
11551                })
11552            {
11553                break;
11554            }
11555            assert!(
11556                Instant::now() < deadline,
11557                "module did not produce a truncated line and restart boundary: {tail:?}"
11558            );
11559            sleep(Duration::from_millis(10)).await;
11560        }
11561
11562        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11563        let request = ClientControlRequest::SupervisorStderrTail {
11564            module_id: "stderr-tail-wire".to_string(),
11565            max_lines: None,
11566            max_bytes: None,
11567        };
11568        let frame = Frame::build(
11569            FrameType::Request,
11570            control_flags(),
11571            0,
11572            0,
11573            1,
11574            serde_json::to_vec(&request).unwrap(),
11575        )
11576        .unwrap();
11577        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11578        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11579        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11580            serde_json::from_slice(&responses[0].body).unwrap()
11581        else {
11582            panic!("expected supervisor.stderr_tail response");
11583        };
11584
11585        assert!(
11586            tail.entries
11587                .iter()
11588                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11589            "the control response lost the restart boundary"
11590        );
11591        let Some(StderrTailEntry::Line {
11592            text,
11593            truncated,
11594            at_ms,
11595        }) = tail.entries.iter().find(|entry| {
11596            matches!(
11597                entry,
11598                StderrTailEntry::Line {
11599                    truncated: true,
11600                    ..
11601                }
11602            )
11603        })
11604        else {
11605            panic!("the control response lost the truncated line");
11606        };
11607        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11608        assert!(*truncated);
11609        assert!(
11610            at_ms.is_some(),
11611            "the control response lost the line's capture time"
11612        );
11613    }
11614
11615    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11616    /// read done on the worker thread would stall every other task until it
11617    /// finished; the read must run off the worker so this test's own task keeps
11618    /// running while the read is paused.
11619    #[tokio::test(flavor = "current_thread")]
11620    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11621        let dir = ScratchDir::new("terminals-off-worker");
11622        let journal_path = dir.join("terminals.jsonl");
11623        let registry = Arc::new(Registry::default());
11624        let supervisor_handle = SupervisorHandle::new();
11625        let supervisor =
11626            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11627                .with_handle(supervisor_handle.clone())
11628                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11629        let module = supervisor
11630            .spawn(ModuleSpec {
11631                script: None,
11632                carry_containment: false,
11633                module_id: "terminal-off-worker".to_string(),
11634                program: fake_aft_stub_path(),
11635                args: Vec::new(),
11636                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11637                reserved: false,
11638                reserved_prefixes: Vec::new(),
11639                protocol: ModuleProtocol::Subc,
11640                overlap: Default::default(),
11641            })
11642            .unwrap();
11643        let deadline = Instant::now() + Duration::from_secs(5);
11644        while module.terminal_history().entries.len() != 2 {
11645            assert!(Instant::now() < deadline, "module did not record two exits");
11646            sleep(Duration::from_millis(10)).await;
11647        }
11648
11649        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11650        let handler =
11651            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11652        let frame = Frame::build(
11653            FrameType::Request,
11654            control_flags(),
11655            0,
11656            0,
11657            1,
11658            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11659                module_id: "terminal-off-worker".to_string(),
11660            })
11661            .unwrap(),
11662        )
11663        .unwrap();
11664        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11665        let spawned_at = std::time::Instant::now();
11666        let read = tokio::spawn({
11667            let handler = Arc::clone(&handler);
11668            async move { handler.handle_control_frame(&ctx, frame).await }
11669        });
11670        // Waiting for the pause from a blocking thread keeps this task pending,
11671        // so the runtime's single worker is free to run the read task.
11672        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11673            .await
11674            .unwrap()
11675            .expect("the history read reached its pause");
11676        let elapsed = spawned_at.elapsed();
11677        assert!(
11678            elapsed < Duration::from_secs(2) && !read.is_finished(),
11679            "this task could not run while the history read was paused \
11680             (resumed after {elapsed:?}, read finished: {})",
11681            read.is_finished()
11682        );
11683
11684        drop(release);
11685        let responses = read.await.unwrap().unwrap();
11686        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11687        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11688            panic!("expected supervisor.terminals response");
11689        };
11690        assert_eq!(terminals.entries.len(), 2);
11691        assert_eq!(terminals.journal_skipped_lines, 0);
11692        assert_eq!(terminals.journal_read_errors, 0);
11693    }
11694
11695    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11696    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11697        let registry = Arc::new(Registry::default());
11698        let supervisor_handle = SupervisorHandle::new();
11699        let supervisor =
11700            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11701                .with_handle(supervisor_handle.clone());
11702        let module = supervisor
11703            .spawn(ModuleSpec {
11704                script: None,
11705                carry_containment: false,
11706                module_id: "terminal-golden".to_string(),
11707                program: fake_aft_stub_path(),
11708                args: Vec::new(),
11709                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11710                reserved: false,
11711                reserved_prefixes: Vec::new(),
11712                protocol: ModuleProtocol::Subc,
11713                overlap: Default::default(),
11714            })
11715            .unwrap();
11716
11717        let deadline = Instant::now() + Duration::from_secs(5);
11718        while module.terminal_history().entries.len() != 2 {
11719            assert!(
11720                Instant::now() < deadline,
11721                "module did not retain two terminal exits: {:?}",
11722                module.terminal_history()
11723            );
11724            sleep(Duration::from_millis(10)).await;
11725        }
11726
11727        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11728        let request = ClientControlRequest::SupervisorTerminals {
11729            module_id: "terminal-golden".to_string(),
11730        };
11731        let frame = Frame::build(
11732            FrameType::Request,
11733            control_flags(),
11734            0,
11735            0,
11736            1,
11737            serde_json::to_vec(&request).unwrap(),
11738        )
11739        .unwrap();
11740        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11741        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11742        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11743        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11744            panic!("expected supervisor.terminals response");
11745        };
11746        assert_eq!(terminals.entries.len(), 2);
11747        assert_eq!(terminals.dropped, 0);
11748
11749        let mut rendered = serde_json::to_value(response).unwrap();
11750        // Wall-clock fields are the observation contract, but not stable fixture
11751        // bytes; normalize only them after the real handler has shaped the response.
11752        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11753        for (index, entry) in rendered["entries"]
11754            .as_array_mut()
11755            .expect("terminal response entries array")
11756            .iter_mut()
11757            .enumerate()
11758        {
11759            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11760        }
11761
11762        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11763            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11764        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11765        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11766            std::fs::write(&golden_path, &serialized).unwrap();
11767        }
11768        let expected: Value =
11769            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11770        assert_eq!(rendered, expected);
11771    }
11772
11773    #[test]
11774    fn hello_registers_manifest_and_returns_ack() {
11775        let registry = Arc::new(Registry::default());
11776        let handler = ControlHandler::new(Arc::clone(&registry));
11777        let conn = ConnectionId::new(1);
11778
11779        let responses = handler
11780            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11781            .unwrap();
11782
11783        assert_eq!(responses.len(), 1);
11784        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11785        assert_eq!(responses[0].header.channel, 0);
11786        assert_eq!(responses[0].header.corr, 7);
11787        let ack = parse_ack(&responses[0]);
11788        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11789        assert!(ack
11790            .subc_capabilities
11791            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11792        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11793        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11794        assert!(ack
11795            .subc_ops
11796            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11797        assert!(ack
11798            .subc_ops
11799            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11800        assert!(ack
11801            .subc_ops
11802            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11803
11804        let registration = registry.get_module("aft").unwrap().unwrap();
11805        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11806        assert_eq!(registration.state, ChannelState::Active);
11807        assert_eq!(registration.connection_id, conn);
11808        assert_eq!(registration.control_ops, module_baseline_control_ops());
11809        assert!(registration.manifest.display_name.is_none());
11810    }
11811
11812    #[test]
11813    fn hello_display_name_refuses_invalid_manifest_by_field() {
11814        let registry = Arc::new(Registry::default());
11815        let handler = ControlHandler::new(Arc::clone(&registry));
11816        for (index, invalid) in [
11817            json!(""),
11818            json!("a".repeat(41)),
11819            json!(" Routing"),
11820            json!("a\nb"),
11821            json!("a\u{202e}b"),
11822            json!(7),
11823        ]
11824        .into_iter()
11825        .enumerate()
11826        {
11827            let module_id = format!("bad-display-name-{index}");
11828            let mut body = serde_json::to_value(ModuleHelloBody {
11829                manifest: manifest(&module_id, PROTOCOL_VERSION),
11830                protocol_ver: PROTOCOL_VERSION,
11831                control_ops: None,
11832                launch_nonce: None,
11833            })
11834            .unwrap();
11835            body["manifest"]["display_name"] = invalid;
11836            let hello = Frame::build(
11837                FrameType::Hello,
11838                control_flags(),
11839                0,
11840                0,
11841                7,
11842                serde_json::to_vec(&body).unwrap(),
11843            )
11844            .unwrap();
11845            let response = handler
11846                .handle_control(ConnectionId::new(100 + index as u64), hello)
11847                .unwrap();
11848            assert_eq!(response[0].header.ty, FrameType::Error);
11849            let error = parse_error(&response[0]);
11850            assert_eq!(error["code"], "invalid_manifest");
11851            assert!(error["message"].as_str().unwrap().contains("display_name"));
11852            assert!(registry.get_module(&module_id).unwrap().is_none());
11853        }
11854    }
11855
11856    #[test]
11857    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11858        let invalid_identifiers = [
11859            ("case_change", "credentials-Provider/v1"),
11860            ("leading_zero", "credentials-provider/v01"),
11861            ("trailing_hyphen", "credentials-provider-/v1"),
11862            ("consecutive_hyphens", "credentials--provider/v1"),
11863            ("uppercase", "Credentials-provider/v1"),
11864            ("missing_v", "credentials-provider/1"),
11865            ("whitespace", "credentials provider/v1"),
11866            ("zero_version", "credentials-provider/v0"),
11867            ("out_of_range_version", "credentials-provider/v4294967296"),
11868            (
11869                "overlength_name",
11870                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11871            ),
11872        ];
11873        let mut cases = invalid_identifiers
11874            .into_iter()
11875            .map(|(name, identifier)| {
11876                (
11877                    format!("identifier_{name}"),
11878                    "capabilities.provides[0]".to_string(),
11879                    identifier.to_string(),
11880                    json!({ "provides": [identifier] }),
11881                    None,
11882                )
11883            })
11884            .collect::<Vec<_>>();
11885        cases.extend([
11886            (
11887                "unknown_need".to_string(),
11888                "capabilities.requires[0].need".to_string(),
11889                "deferred".to_string(),
11890                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11891                None,
11892            ),
11893            (
11894                "duplicate_provides".to_string(),
11895                "capabilities.provides[1]".to_string(),
11896                "credentials-provider/v1".to_string(),
11897                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11898                None,
11899            ),
11900            (
11901                "duplicate_must_never_reach".to_string(),
11902                "capabilities.must_never_reach[1]".to_string(),
11903                "credentials-provider/v1".to_string(),
11904                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11905                None,
11906            ),
11907            (
11908                "duplicate_requires_same_need".to_string(),
11909                "capabilities.requires[1]".to_string(),
11910                "credentials-provider/v1".to_string(),
11911                json!({ "requires": [
11912                    { "capability": "credentials-provider/v1", "need": "required" },
11913                    { "capability": "credentials-provider/v1", "need": "required" }
11914                ] }),
11915                None,
11916            ),
11917            (
11918                "duplicate_requires_conflicting_need".to_string(),
11919                "capabilities.requires[1]".to_string(),
11920                "credentials-provider/v1".to_string(),
11921                json!({ "requires": [
11922                    { "capability": "credentials-provider/v1", "need": "required" },
11923                    { "capability": "credentials-provider/v1", "need": "optional" }
11924                ] }),
11925                None,
11926            ),
11927            (
11928                "capabilities_root_pointer".to_string(),
11929                "runtime_computed[0]".to_string(),
11930                "/capabilities".to_string(),
11931                json!({}),
11932                Some(json!(["/capabilities"])),
11933            ),
11934            (
11935                "capabilities_descendant_pointer".to_string(),
11936                "runtime_computed[0]".to_string(),
11937                "/capabilities/provides".to_string(),
11938                json!({}),
11939                Some(json!(["/capabilities/provides"])),
11940            ),
11941            (
11942                "malformed_pointer_without_leading_slash".to_string(),
11943                "runtime_computed[0]".to_string(),
11944                "capabilities".to_string(),
11945                json!({}),
11946                Some(json!(["capabilities"])),
11947            ),
11948            (
11949                "malformed_pointer_escape".to_string(),
11950                "runtime_computed[0]".to_string(),
11951                "/roles/~2/tools".to_string(),
11952                json!({}),
11953                Some(json!(["/roles/~2/tools"])),
11954            ),
11955            (
11956                "unknown_capabilities_field".to_string(),
11957                "capabilities.future".to_string(),
11958                "<array>".to_string(),
11959                json!({ "future": [] }),
11960                None,
11961            ),
11962        ]);
11963
11964        for (index, (name, field, value, capabilities, runtime_computed)) in
11965            cases.into_iter().enumerate()
11966        {
11967            let registry = Arc::new(Registry::default());
11968            let handler = ControlHandler::new(Arc::clone(&registry));
11969            let response = handler
11970                .handle_control(
11971                    ConnectionId::new((index + 1) as u64),
11972                    capability_grammar_hello_frame(
11973                        capabilities,
11974                        runtime_computed,
11975                        index as u64 + 1,
11976                    ),
11977                )
11978                .expect("invalid HELLO returns a refusal");
11979
11980            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11981            let error = parse_error(&response[0]);
11982            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11983            let message = error["message"]
11984                .as_str()
11985                .expect("error message is a string");
11986            assert!(
11987                message.contains(&field),
11988                "{name}: field missing from {message}"
11989            );
11990            assert!(
11991                message.contains(&value),
11992                "{name}: value missing from {message}"
11993            );
11994            assert_eq!(
11995                registry
11996                    .active_registration_count()
11997                    .expect("registry reads"),
11998                0,
11999                "{name}: refused HELLO must not create a catalog entry"
12000            );
12001        }
12002    }
12003
12004    #[test]
12005    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
12006        let registry = Arc::new(Registry::default());
12007        let handler = ControlHandler::new(Arc::clone(&registry));
12008        let capabilities = json!({
12009            "provides": ["credentials-provider/v1"],
12010            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
12011            "must_never_reach": ["federation-transport/v1"]
12012        });
12013        let response = handler
12014            .handle_control(
12015                ConnectionId::new(99),
12016                capability_grammar_hello_frame(
12017                    capabilities.clone(),
12018                    Some(json!(["/roles/0/tools"])),
12019                    99,
12020                ),
12021            )
12022            .expect("valid HELLO registers");
12023        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12024
12025        let request = Frame::build(
12026            FrameType::Request,
12027            control_flags(),
12028            0,
12029            0,
12030            100,
12031            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12032                .expect("catalog request serializes"),
12033        )
12034        .expect("catalog request frame builds");
12035        let response = handler
12036            .handle_catalog_list(request, None)
12037            .expect("catalog list succeeds");
12038        let ClientControlResponse::CatalogList { modules, .. } =
12039            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
12040        else {
12041            panic!("catalog request must return catalog.list");
12042        };
12043        assert_eq!(modules.len(), 1);
12044        assert_eq!(
12045            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
12046            capabilities
12047        );
12048    }
12049
12050    #[test]
12051    fn catalog_list_mirrors_management_operation_description() {
12052        let registry = Arc::new(Registry::default());
12053        let handler = ControlHandler::new(Arc::clone(&registry));
12054        let description = "List managed records and return their identifiers and metadata.";
12055        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
12056        manifest.provides = vec![ProviderRole::ManagementSurface {
12057            operations: vec![ManagementOperation {
12058                name: "records.list".to_string(),
12059                kind: ManagementOperationKind::Query,
12060                description: Some(description.to_string()),
12061            }],
12062            config_schema: json!({"type": "object"}),
12063            observability: vec![ObservabilitySurface {
12064                name: "records.stats".to_string(),
12065                kind: ObservabilityKind::Snapshot,
12066            }],
12067            identity_scope: vec![IdentityScope::Project],
12068            concurrency: Concurrency::ModuleManaged,
12069        }];
12070        registry
12071            .register_with_control_ops(
12072                manifest,
12073                PROTOCOL_VERSION,
12074                ConnectionId::new(99),
12075                Vec::new(),
12076            )
12077            .expect("described management manifest registers");
12078
12079        let request = Frame::build(
12080            FrameType::Request,
12081            control_flags(),
12082            0,
12083            0,
12084            100,
12085            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12086                .expect("catalog request serializes"),
12087        )
12088        .expect("catalog request frame builds");
12089        let response = handler
12090            .handle_catalog_list(request, None)
12091            .expect("catalog list succeeds");
12092        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12093        assert_eq!(
12094            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12095            "catalog.list must preserve the declared operation description verbatim"
12096        );
12097    }
12098
12099    #[test]
12100    fn catalog_list_mirrors_registered_operation_delivery() {
12101        let registry = Arc::new(Registry::default());
12102        let handler = ControlHandler::new(Arc::clone(&registry));
12103        let delivery =
12104            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12105        let mut body = serde_json::to_value(ModuleHelloBody {
12106            manifest: manifest("watch-management", PROTOCOL_VERSION),
12107            protocol_ver: PROTOCOL_VERSION,
12108            control_ops: None,
12109            launch_nonce: None,
12110        })
12111        .unwrap();
12112        body["manifest"]["provides"] = json!([{
12113            "role": "management_surface",
12114            "operations": [
12115                {"name": "status", "kind": "query"},
12116                {"name": "future", "kind": "query"},
12117                {"name": "reset", "kind": "mutate"}
12118            ],
12119            "config_schema": {}, "observability": [], "identity_scope": []
12120        }]);
12121        body["manifest"]["operation_delivery"] = delivery.clone();
12122        let hello = Frame::build(
12123            FrameType::Hello,
12124            control_flags(),
12125            0,
12126            0,
12127            99,
12128            serde_json::to_vec(&body).unwrap(),
12129        )
12130        .unwrap();
12131        let response = handler
12132            .handle_control(ConnectionId::new(99), hello)
12133            .unwrap();
12134        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12135
12136        let (_, registrations) = registry.list_modules().unwrap();
12137        let registered = &registrations[0].manifest;
12138        assert!(registered.is_watch_operation("status"));
12139        assert!(!registered.is_watch_operation("future"));
12140        assert!(!registered.is_watch_operation("reset"));
12141        assert!(!registered.is_watch_operation("missing"));
12142
12143        let request = Frame::build(
12144            FrameType::Request,
12145            control_flags(),
12146            0,
12147            0,
12148            100,
12149            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12150        )
12151        .unwrap();
12152        let response = handler.handle_catalog_list(request, None).unwrap();
12153        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12154        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12155        let ClientControlResponse::CatalogList { modules, .. } =
12156            serde_json::from_slice(&response[0].body).unwrap()
12157        else {
12158            panic!("expected catalog.list");
12159        };
12160        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12161    }
12162
12163    #[test]
12164    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12165        let registry = Arc::new(Registry::default());
12166        let supervisor = SupervisorHandle::new();
12167        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12168        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12169        let descriptor = json!({
12170            "schema": "ckios.richui.manifest/1",
12171            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12172            "bytes": 4096,
12173            "chunks": 4
12174        });
12175        let connection = ConnectionId::new(201);
12176        let hello = handler
12177            .handle_control(
12178                connection,
12179                hello_frame_with_rich_ui(
12180                    "vault",
12181                    PROTOCOL_VERSION,
12182                    201,
12183                    Some("the-real-nonce"),
12184                    descriptor.clone(),
12185                ),
12186            )
12187            .unwrap();
12188        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12189
12190        let request =
12191            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12192        let provides = registry
12193            .get_module_by_connection(connection)
12194            .unwrap()
12195            .unwrap()
12196            .manifest
12197            .provides;
12198        handler
12199            .handle_catalog_update(connection, request, provides, None, Some(false))
12200            .unwrap();
12201
12202        let request = Frame::build(
12203            FrameType::Request,
12204            control_flags(),
12205            0,
12206            0,
12207            203,
12208            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12209        )
12210        .unwrap();
12211        let response = handler.handle_catalog_list(request, None).unwrap();
12212        let ClientControlResponse::CatalogList { modules, .. } =
12213            serde_json::from_slice(&response[0].body).unwrap()
12214        else {
12215            panic!("expected catalog.list");
12216        };
12217        assert_eq!(
12218            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12219            descriptor
12220        );
12221        assert!(modules[0].nonce_verified);
12222    }
12223
12224    fn hello_with_role_declarations(declarations: Value) -> Frame {
12225        let mut body = serde_json::to_value(ModuleHelloBody {
12226            manifest: manifest("role-test", PROTOCOL_VERSION),
12227            protocol_ver: PROTOCOL_VERSION,
12228            control_ops: None,
12229            launch_nonce: None,
12230        })
12231        .unwrap();
12232        body["manifest"]["role_declarations"] = declarations;
12233        Frame::build(
12234            FrameType::Hello,
12235            control_flags(),
12236            0,
12237            0,
12238            301,
12239            serde_json::to_vec(&body).unwrap(),
12240        )
12241        .unwrap()
12242    }
12243
12244    fn update_role_declarations_frame(declarations: Value) -> Frame {
12245        Frame::build(
12246            FrameType::Request,
12247            control_flags(),
12248            0,
12249            0,
12250            303,
12251            serde_json::to_vec(&json!({
12252                "op": "catalog.update_role_declarations",
12253                "role_declarations": declarations,
12254            }))
12255            .unwrap(),
12256        )
12257        .unwrap()
12258    }
12259
12260    #[tokio::test]
12261    async fn role_declarations_update_replaces_then_clears_catalog() {
12262        let registry = Arc::new(Registry::default());
12263        let handler = ControlHandler::new(Arc::clone(&registry));
12264        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12265        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12266        hello_via_sink(
12267            &handler,
12268            &ctx,
12269            &mut rx,
12270            hello_with_role_declarations(initial.clone()),
12271        )
12272        .await;
12273        assert_eq!(
12274            role_declarations_catalog(&handler).0["role_declarations"],
12275            initial
12276        );
12277        let before = registry.get_module("role-test").unwrap().unwrap();
12278        for declarations in [
12279            json!({"media-provider/v1": {"engines": ["new"]}}),
12280            json!({}),
12281        ] {
12282            let response = handler
12283                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12284                .await
12285                .unwrap();
12286            assert_eq!(response[0].header.ty, FrameType::Response);
12287            assert_eq!(
12288                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12289                json!({"op": "catalog.update_role_declarations"})
12290            );
12291            let (raw, entry) = role_declarations_catalog(&handler);
12292            assert_eq!(
12293                serde_json::to_value(entry.role_declarations).unwrap(),
12294                declarations
12295            );
12296            if declarations.as_object().unwrap().is_empty() {
12297                assert!(raw.get("role_declarations").is_none());
12298            } else {
12299                assert_eq!(raw["role_declarations"], declarations);
12300            }
12301            let after = registry.get_module("role-test").unwrap().unwrap();
12302            let mut expected = before.manifest.clone();
12303            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12304            assert_eq!(after.manifest, expected);
12305            assert_eq!(after.ready, before.ready);
12306        }
12307    }
12308
12309    #[tokio::test]
12310    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12311        let registry = Arc::new(Registry::default());
12312        let handler = ControlHandler::new(registry);
12313        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12314        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12315        hello_via_sink(
12316            &handler,
12317            &ctx,
12318            &mut rx,
12319            hello_with_role_declarations(initial.clone()),
12320        )
12321        .await;
12322        for (invalid, reason) in [
12323            (json!(null), "role_declarations must be an object"),
12324            (json!([]), "role_declarations must be an object"),
12325            (
12326                json!({"bad key": {}}),
12327                "role_declarations key must use capability-name grammar",
12328            ),
12329            (
12330                json!({"media-provider/v1": []}),
12331                "role_declarations values must be objects",
12332            ),
12333            (
12334                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12335                "role_declarations exceeds 16384 compact JSON bytes",
12336            ),
12337        ] {
12338            let response = handler
12339                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12340                .await
12341                .unwrap();
12342            let error = parse_error(&response[0]);
12343            assert_eq!(error["code"], "invalid_role_declarations");
12344            assert_eq!(error["message"], reason);
12345            assert_eq!(
12346                role_declarations_catalog(&handler).0["role_declarations"],
12347                initial
12348            );
12349        }
12350    }
12351
12352    #[tokio::test]
12353    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12354        let registry = Arc::new(Registry::default());
12355        let handler = ControlHandler::new(Arc::clone(&registry));
12356        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12357        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12358        hello_via_sink(
12359            &handler,
12360            &owner,
12361            &mut owner_rx,
12362            hello_with_role_declarations(initial.clone()),
12363        )
12364        .await;
12365        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12366        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12367        let response = handler
12368            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12369            .await
12370            .unwrap();
12371        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12372        hello_via_sink(
12373            &handler,
12374            &other,
12375            &mut other_rx,
12376            hello_frame("other", PROTOCOL_VERSION, 304),
12377        )
12378        .await;
12379        let response = handler
12380            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12381            .await
12382            .unwrap();
12383        assert_eq!(response[0].header.ty, FrameType::Response);
12384        assert_eq!(
12385            serde_json::to_value(
12386                registry
12387                    .get_module("role-test")
12388                    .unwrap()
12389                    .unwrap()
12390                    .manifest
12391                    .role_declarations
12392            )
12393            .unwrap(),
12394            initial
12395        );
12396        assert_eq!(
12397            serde_json::to_value(
12398                registry
12399                    .get_module("other")
12400                    .unwrap()
12401                    .unwrap()
12402                    .manifest
12403                    .role_declarations
12404            )
12405            .unwrap(),
12406            replacement
12407        );
12408    }
12409
12410    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12411        let request = Frame::build(
12412            FrameType::Request,
12413            control_flags(),
12414            0,
12415            0,
12416            302,
12417            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12418        )
12419        .unwrap();
12420        let response = handler.handle_catalog_list(request, None).unwrap();
12421        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12422        let ClientControlResponse::CatalogList { mut modules, .. } =
12423            serde_json::from_slice(&response[0].body).unwrap()
12424        else {
12425            panic!("expected catalog.list");
12426        };
12427        (raw["modules"][0].clone(), modules.remove(0))
12428    }
12429
12430    #[test]
12431    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12432        let registry = Arc::new(Registry::default());
12433        let handler = ControlHandler::new(Arc::clone(&registry));
12434        let declarations = json!({
12435            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12436            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12437        });
12438        let connection = ConnectionId::new(301);
12439        let response = handler
12440            .handle_control(
12441                connection,
12442                hello_with_role_declarations(declarations.clone()),
12443            )
12444            .unwrap();
12445        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12446        let registered = registry
12447            .get_module_by_connection(connection)
12448            .unwrap()
12449            .unwrap()
12450            .manifest;
12451        // Compared as JSON values, not bytes: object key order is not part of
12452        // the relay's promise, and workspace builds unify serde_json's
12453        // preserve_order feature, which changes the order a literal keeps.
12454        assert_eq!(
12455            serde_json::to_value(&registered.role_declarations).unwrap(),
12456            declarations
12457        );
12458        let (raw, entry) = role_declarations_catalog(&handler);
12459        assert_eq!(raw["role_declarations"], declarations);
12460        assert_eq!(entry.role_declarations, registered.role_declarations);
12461
12462        let request =
12463            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12464        handler
12465            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12466            .unwrap();
12467        let (raw, entry) = role_declarations_catalog(&handler);
12468        assert_eq!(raw["role_declarations"], declarations);
12469        assert_eq!(entry.role_declarations, registered.role_declarations);
12470    }
12471
12472    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12473        let registry = Arc::new(Registry::default());
12474        let handler = ControlHandler::new(Arc::clone(&registry));
12475        let capture = EventCapture::default();
12476        let _subscriber =
12477            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12478        let response = handler
12479            .handle_control(
12480                ConnectionId::new(301),
12481                hello_with_role_declarations(declarations),
12482            )
12483            .unwrap();
12484        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12485        assert!(registry
12486            .get_module_by_connection(ConnectionId::new(301))
12487            .unwrap()
12488            .unwrap()
12489            .manifest
12490            .role_declarations
12491            .is_empty());
12492        let (raw, entry) = role_declarations_catalog(&handler);
12493        assert!(raw.get("role_declarations").is_none());
12494        assert!(entry.role_declarations.is_empty());
12495        let warnings: Vec<_> = capture
12496            .events()
12497            .into_iter()
12498            .filter(|event| {
12499                event.fields.get("message").map(String::as_str)
12500                    == Some("dropping whole role_declarations map from HELLO")
12501            })
12502            .collect();
12503        assert_eq!(warnings.len(), 1);
12504        assert_eq!(warnings[0].level, tracing::Level::WARN);
12505        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12506        assert_eq!(warnings[0].fields["reason"], reason);
12507    }
12508
12509    #[test]
12510    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12511        for value in [
12512            json!(null),
12513            json!(false),
12514            json!(0),
12515            json!("opaque"),
12516            json!([]),
12517        ] {
12518            assert_hello_drops_role_declarations_with_warning(
12519                json!({"routing/v1": {}, "broken/v1": value}),
12520                "role_declarations values must be objects",
12521            );
12522        }
12523        assert_hello_drops_role_declarations_with_warning(
12524            json!([]),
12525            "role_declarations must be an object",
12526        );
12527    }
12528
12529    #[test]
12530    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12531        assert_hello_drops_role_declarations_with_warning(
12532            json!({"routing/v1": {}, "bad key": {}}),
12533            "role_declarations key must use capability-name grammar",
12534        );
12535    }
12536
12537    #[test]
12538    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12539        assert_hello_drops_role_declarations_with_warning(
12540            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12541            "role_declarations exceeds 16384 compact JSON bytes",
12542        );
12543    }
12544
12545    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12546        let mut body = serde_json::to_value(ModuleHelloBody {
12547            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12548            protocol_ver: PROTOCOL_VERSION,
12549            control_ops: None,
12550            launch_nonce: None,
12551        })
12552        .unwrap();
12553        body["manifest"]["provides"] = json!([{
12554            "role": "management_surface",
12555            "operations": [
12556                {"name": "diagnostics.findings", "kind": "query"},
12557                {"name": "reset", "kind": "mutate"}
12558            ],
12559            "config_schema": {}, "observability": [], "identity_scope": []
12560        }]);
12561        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12562        if let Some(flow_operations) = flow_operations {
12563            body["manifest"]["flow_operations"] = flow_operations;
12564        }
12565        Frame::build(
12566            FrameType::Hello,
12567            control_flags(),
12568            0,
12569            0,
12570            401,
12571            serde_json::to_vec(&body).unwrap(),
12572        )
12573        .unwrap()
12574    }
12575
12576    #[test]
12577    fn catalog_list_mirrors_flow_operations_unchanged() {
12578        // Order is kept as declared (not sorted) and an empty list stays an
12579        // affirmative "none", distinct from an absent declaration.
12580        for (capability, flow_operations) in [
12581            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12582            ("call-modes/v1", json!(["diagnostics.findings"])),
12583            ("flow-scopes/v1", json!([])),
12584        ] {
12585            let registry = Arc::new(Registry::default());
12586            let handler = ControlHandler::new(Arc::clone(&registry));
12587            let connection = ConnectionId::new(401);
12588            let response = handler
12589                .handle_control(
12590                    connection,
12591                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12592                )
12593                .unwrap();
12594            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12595            let registered = registry
12596                .get_module_by_connection(connection)
12597                .unwrap()
12598                .unwrap()
12599                .manifest;
12600            assert_eq!(
12601                serde_json::to_value(&registered.flow_operations).unwrap(),
12602                flow_operations
12603            );
12604            let (raw, entry) = role_declarations_catalog(&handler);
12605            assert_eq!(raw["flow_operations"], flow_operations);
12606            assert_eq!(entry.flow_operations, registered.flow_operations);
12607        }
12608
12609        let registry = Arc::new(Registry::default());
12610        let handler = ControlHandler::new(Arc::clone(&registry));
12611        let response = handler
12612            .handle_control(
12613                ConnectionId::new(401),
12614                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12615            )
12616            .unwrap();
12617        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12618        let (raw, entry) = role_declarations_catalog(&handler);
12619        assert!(raw.get("flow_operations").is_none());
12620        assert_eq!(entry.flow_operations, None);
12621    }
12622
12623    #[test]
12624    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12625        let oversized: serde_json::Map<String, Value> = (0..257)
12626            .map(|n| (format!("tool:t{n}"), json!(true)))
12627            .collect();
12628        for (capabilities, map, valid) in [
12629            (
12630                json!(["scope-federated/v1"]),
12631                json!({"tool:read":true,"management:reset":true}),
12632                true,
12633            ),
12634            (json!(["scope-federated/v1"]), json!({}), true),
12635            (json!([]), json!({"tool:read":true}), false),
12636            (
12637                json!(["scope-federated/v1"]),
12638                json!({"tool:valid":true,"tool:bad":false}),
12639                false,
12640            ),
12641            (
12642                json!(["scope-federated/v1"]),
12643                json!({"tool:valid":true,"management:missing":true}),
12644                false,
12645            ),
12646            (
12647                json!(["scope-federated/v1"]),
12648                Value::Object(oversized),
12649                false,
12650            ),
12651        ] {
12652            let capture = EventCapture::default();
12653            let _subscriber = tracing::subscriber::set_default(
12654                tracing_subscriber::registry().with(capture.clone()),
12655            );
12656            let registry = Arc::new(Registry::default());
12657            let handler = ControlHandler::new(Arc::clone(&registry));
12658            let hello = hello_with_flow_operations(capabilities, None);
12659            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12660            body["manifest"]["operation_deferral"] = map.clone();
12661            let hello = Frame::build(
12662                FrameType::Hello,
12663                control_flags(),
12664                0,
12665                0,
12666                401,
12667                serde_json::to_vec(&body).unwrap(),
12668            )
12669            .unwrap();
12670            let response = handler
12671                .handle_control(ConnectionId::new(401), hello)
12672                .unwrap();
12673            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12674            let (raw, entry) = role_declarations_catalog(&handler);
12675            if valid {
12676                assert_eq!(raw["operation_deferral"], map);
12677                assert_eq!(
12678                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12679                    map
12680                );
12681            } else {
12682                assert!(entry.operation_deferral.is_none());
12683                assert!(raw.get("operation_deferral").is_none());
12684                assert_eq!(
12685                    capture
12686                        .events()
12687                        .iter()
12688                        .filter(|event| event.fields.get("message").map(String::as_str)
12689                            == Some("dropping operation_deferral from HELLO"))
12690                        .count(),
12691                    1
12692                );
12693            }
12694        }
12695    }
12696
12697    fn assert_hello_drops_flow_operations_with_warning(
12698        capabilities: Value,
12699        flow_operations: Value,
12700        reason: &str,
12701    ) {
12702        let registry = Arc::new(Registry::default());
12703        let handler = ControlHandler::new(Arc::clone(&registry));
12704        let capture = EventCapture::default();
12705        let _subscriber =
12706            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12707        let response = handler
12708            .handle_control(
12709                ConnectionId::new(401),
12710                hello_with_flow_operations(capabilities, Some(flow_operations)),
12711            )
12712            .unwrap();
12713        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12714        let registered = registry
12715            .get_module_by_connection(ConnectionId::new(401))
12716            .unwrap()
12717            .expect("the module still registers")
12718            .manifest;
12719        assert_eq!(registered.module_id, "flow-ops");
12720        assert_eq!(registered.flow_operations, None);
12721        let (raw, entry) = role_declarations_catalog(&handler);
12722        assert_eq!(raw["module_id"], "flow-ops");
12723        assert!(raw.get("flow_operations").is_none());
12724        assert_eq!(entry.flow_operations, None);
12725        let warnings: Vec<_> = capture
12726            .events()
12727            .into_iter()
12728            .filter(|event| {
12729                event.fields.get("message").map(String::as_str)
12730                    == Some("dropping flow_operations from HELLO")
12731            })
12732            .collect();
12733        assert_eq!(warnings.len(), 1);
12734        assert_eq!(warnings[0].level, tracing::Level::WARN);
12735        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12736        assert_eq!(warnings[0].fields["reason"], reason);
12737    }
12738
12739    #[test]
12740    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12741        assert_hello_drops_flow_operations_with_warning(
12742            json!(["flow-scopes/v1"]),
12743            json!(["diagnostics.findings", "missing"]),
12744            "flow_operations names 'missing', which is not a declared management operation",
12745        );
12746    }
12747
12748    #[test]
12749    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12750        assert_hello_drops_flow_operations_with_warning(
12751            json!([]),
12752            json!(["diagnostics.findings"]),
12753            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12754        );
12755        // A run-only capability does not admit flows either.
12756        assert_hello_drops_flow_operations_with_warning(
12757            json!(["agent-run-scopes/v1"]),
12758            json!([]),
12759            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12760        );
12761    }
12762
12763    #[test]
12764    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12765        assert_hello_drops_flow_operations_with_warning(
12766            json!(["flow-scopes/v1"]),
12767            json!(["reset", "reset"]),
12768            "flow_operations names 'reset' more than once",
12769        );
12770        assert_hello_drops_flow_operations_with_warning(
12771            json!(["flow-scopes/v1"]),
12772            json!(vec!["reset"; 257]),
12773            "flow_operations lists 257 names, more than 256",
12774        );
12775        assert_hello_drops_flow_operations_with_warning(
12776            json!(["flow-scopes/v1"]),
12777            json!("reset"),
12778            "flow_operations must be an array of operation names",
12779        );
12780    }
12781
12782    #[test]
12783    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12784        let registry = Arc::new(Registry::default());
12785        let handler = ControlHandler::new(registry.clone());
12786        let descriptor = json!({
12787            "schema": "ckios.richui.manifest/1",
12788            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12789            "bytes": 128,
12790            "chunks": 2
12791        });
12792        let malformed = [
12793            ("schema", json!("")),
12794            ("schema", json!("a".repeat(65))),
12795            ("schema", json!("Bad schema")),
12796            (
12797                "manifest_digest",
12798                json!(format!("sha256:{}", "A".repeat(64))),
12799            ),
12800            ("manifest_digest", json!("sha256:abc")),
12801            ("bytes", json!(0)),
12802            ("bytes", json!(16_777_217)),
12803            ("bytes", json!("128")),
12804            ("chunks", json!(0)),
12805            ("chunks", json!(1025)),
12806            ("chunks", json!("2")),
12807        ];
12808        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12809            let mut invalid = descriptor.clone();
12810            invalid[field] = invalid_value;
12811            let response = handler
12812                .handle_control(
12813                    ConnectionId::new(210 + index as u64),
12814                    hello_frame_with_rich_ui(
12815                        &format!("bad-rich-ui-{index}"),
12816                        PROTOCOL_VERSION,
12817                        210 + index as u64,
12818                        None,
12819                        invalid,
12820                    ),
12821                )
12822                .unwrap();
12823            assert_eq!(response[0].header.ty, FrameType::Error);
12824            let error = parse_error(&response[0]);
12825            assert_eq!(error["code"], "invalid_manifest");
12826            assert!(error["message"]
12827                .as_str()
12828                .unwrap()
12829                .contains(&format!("rich_ui.{field}")));
12830            assert!(registry
12831                .get_module(&format!("bad-rich-ui-{index}"))
12832                .unwrap()
12833                .is_none());
12834        }
12835    }
12836
12837    #[test]
12838    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12839        let registry = Arc::new(Registry::default());
12840        let handler = ControlHandler::new(Arc::clone(&registry));
12841        let connection = ConnectionId::new(219);
12842        registry
12843            .register_with_control_ops(
12844                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12845                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12846                        "bad schema",
12847                        format!("sha256:{}", "a".repeat(64)),
12848                        128,
12849                        2,
12850                    )))
12851                    .build(),
12852                PROTOCOL_VERSION,
12853                connection,
12854                Vec::new(),
12855            )
12856            .unwrap();
12857        let request =
12858            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12859        let response = handler
12860            .handle_catalog_update(connection, request, Vec::new(), None, None)
12861            .unwrap();
12862        assert_eq!(response[0].header.ty, FrameType::Error);
12863        let error = parse_error(&response[0]);
12864        assert_eq!(error["code"], "invalid_manifest");
12865        assert!(error["message"]
12866            .as_str()
12867            .unwrap()
12868            .contains("rich_ui.schema"));
12869    }
12870
12871    #[test]
12872    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12873        let registry = Arc::new(Registry::default());
12874        let supervisor = SupervisorHandle::new();
12875        supervisor.open_swap("provider", "candidate-nonce".to_string());
12876        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12877        let connection = ConnectionId::new(218);
12878        let hello = handler
12879            .handle_control(
12880                connection,
12881                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12882            )
12883            .unwrap();
12884        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12885        assert!(registry.list_modules().unwrap().1.is_empty());
12886
12887        registry.promote_candidate("provider").unwrap().unwrap();
12888        let request = Frame::build(
12889            FrameType::Request,
12890            control_flags(),
12891            0,
12892            0,
12893            219,
12894            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12895        )
12896        .unwrap();
12897        let response = handler.handle_catalog_list(request, None).unwrap();
12898        let ClientControlResponse::CatalogList { modules, .. } =
12899            serde_json::from_slice(&response[0].body).unwrap()
12900        else {
12901            panic!("expected catalog.list");
12902        };
12903        assert_eq!(modules.len(), 1);
12904        assert!(modules[0].nonce_verified);
12905    }
12906
12907    #[test]
12908    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12909        for provenance_json in [
12910            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12911            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12912        ] {
12913            let registry = Arc::new(Registry::default());
12914            let handler = ControlHandler::new(registry);
12915            let hello = Frame::build(
12916                FrameType::Hello,
12917                control_flags(),
12918                0,
12919                0,
12920                220,
12921                serde_json::to_vec(&ModuleHelloBody {
12922                    manifest: ModuleManifest::builder("built", "0.1.0")
12923                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12924                        .build(),
12925                    protocol_ver: PROTOCOL_VERSION,
12926                    control_ops: None,
12927                    launch_nonce: None,
12928                })
12929                .unwrap(),
12930            )
12931            .unwrap();
12932            assert_eq!(
12933                handler
12934                    .handle_control(ConnectionId::new(220), hello)
12935                    .unwrap()[0]
12936                    .header
12937                    .ty,
12938                FrameType::HelloAck
12939            );
12940            let request = Frame::build(
12941                FrameType::Request,
12942                control_flags(),
12943                0,
12944                0,
12945                221,
12946                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12947            )
12948            .unwrap();
12949            let response = handler.handle_catalog_list(request, None).unwrap();
12950            let ClientControlResponse::CatalogList { modules, .. } =
12951                serde_json::from_slice(&response[0].body).unwrap()
12952            else {
12953                panic!("expected catalog.list");
12954            };
12955            assert_eq!(modules.len(), 1);
12956            assert_eq!(
12957                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12958                format!(
12959                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12960                )
12961                .as_bytes()
12962            );
12963        }
12964    }
12965
12966    #[test]
12967    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12968        let registry = Arc::new(Registry::default());
12969        let handler = ControlHandler::new(Arc::clone(&registry));
12970        let hello = Frame::build(
12971            FrameType::Hello,
12972            control_flags(),
12973            0,
12974            0,
12975            220,
12976            serde_json::to_vec(&ModuleHelloBody {
12977                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12978                protocol_ver: PROTOCOL_VERSION,
12979                control_ops: None,
12980                launch_nonce: Some("unverified".to_string()),
12981            })
12982            .unwrap(),
12983        )
12984        .unwrap();
12985        assert_eq!(
12986            handler
12987                .handle_control(ConnectionId::new(220), hello)
12988                .unwrap()[0]
12989                .header
12990                .ty,
12991            FrameType::HelloAck
12992        );
12993        let request = Frame::build(
12994            FrameType::Request,
12995            control_flags(),
12996            0,
12997            0,
12998            221,
12999            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13000        )
13001        .unwrap();
13002        let response = handler.handle_catalog_list(request, None).unwrap();
13003        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
13004        assert!(wire["modules"][0].get("provenance").is_none());
13005        let ClientControlResponse::CatalogList { modules, .. } =
13006            serde_json::from_slice(&response[0].body).unwrap()
13007        else {
13008            panic!("expected catalog.list");
13009        };
13010        assert_eq!(
13011            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
13012            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
13013        );
13014        assert!(!modules[0].nonce_verified);
13015        assert!(modules[0].provenance.is_none());
13016    }
13017
13018    // Preserve the legacy-field byte pins while discovery adds optional facts.
13019    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
13020        assert_eq!(entry.first_party, Some(false));
13021        entry.incarnation = None;
13022        entry.spawn = None;
13023        entry.first_party = None;
13024        entry.origin = None;
13025        entry.requested_declarations_digest = None;
13026        entry.approved_declarations_digest = None;
13027        entry
13028    }
13029
13030    #[test]
13031    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
13032        let registry = Arc::new(Registry::default());
13033        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13034            [("vault".to_string(), true), ("squatter".to_string(), true)],
13035            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13036        );
13037        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
13038        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13039            provides: vec!["credentials-provider/v1".to_string()],
13040            requires: Vec::new(),
13041            must_never_reach: Vec::new(),
13042        });
13043        let frame = Frame::build(
13044            FrameType::Hello,
13045            control_flags(),
13046            0,
13047            0,
13048            77,
13049            serde_json::to_vec(&ModuleHelloBody {
13050                manifest: squatter,
13051                protocol_ver: PROTOCOL_VERSION,
13052                control_ops: None,
13053                launch_nonce: None,
13054            })
13055            .expect("HELLO serializes"),
13056        )
13057        .expect("HELLO frame builds");
13058        let response = handler
13059            .handle_control(ConnectionId::new(77), frame)
13060            .expect("reserved claim receives a typed refusal");
13061        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13062        assert_eq!(
13063            registry
13064                .active_registration_count()
13065                .expect("registry reads"),
13066            0,
13067            "a reserved capability refusal must not leave a catalog entry"
13068        );
13069    }
13070
13071    #[test]
13072    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
13073        for settlement in ["timeout", "inconclusive", "drop"] {
13074            let breakers = RouteBindBreakers::default();
13075            let RouteBindAdmission::Admitted {
13076                guard: mut old,
13077                probe: false,
13078            } = breakers.admit("prov")
13079            else {
13080                panic!("ordinary relay admitted")
13081            };
13082            let RouteBindAdmission::Admitted {
13083                guard: mut opener, ..
13084            } = breakers.admit("prov")
13085            else {
13086                panic!("second relay admitted")
13087            };
13088            assert!(
13089                !opener
13090                    .record_timeout(1, Duration::ZERO)
13091                    .unwrap()
13092                    .reopened_after_probe
13093            );
13094            let RouteBindAdmission::Admitted {
13095                guard: mut probe,
13096                probe: true,
13097            } = breakers.admit("prov")
13098            else {
13099                panic!("one cooldown probe admitted")
13100            };
13101            match settlement {
13102                "timeout" => assert!(
13103                    !old.record_timeout(1, Duration::ZERO)
13104                        .unwrap()
13105                        .reopened_after_probe
13106                ),
13107                "inconclusive" => old.record_inconclusive(),
13108                "drop" => drop(old),
13109                _ => unreachable!(),
13110            }
13111            assert!(
13112                matches!(
13113                    breakers.admit("prov"),
13114                    RouteBindAdmission::Refused {
13115                        probe_in_flight: true,
13116                        ..
13117                    }
13118                ),
13119                "{settlement} of a pre-open relay cannot release the real probe"
13120            );
13121            assert!(
13122                probe
13123                    .record_timeout(1, Duration::ZERO)
13124                    .unwrap()
13125                    .reopened_after_probe
13126            );
13127            assert!(matches!(
13128                breakers.admit("prov"),
13129                RouteBindAdmission::Admitted { probe: true, .. }
13130            ));
13131        }
13132        let breakers = RouteBindBreakers::default();
13133        let admit = || match breakers.admit("prov") {
13134            RouteBindAdmission::Admitted { guard, .. } => guard,
13135            _ => panic!("relay admitted"),
13136        };
13137        admit().record_timeout(1, Duration::ZERO);
13138        let mut old_probe = admit();
13139        breakers.reset_for_new_module_connection("prov");
13140        admit().record_timeout(1, Duration::ZERO);
13141        let _new_probe = admit();
13142        old_probe.record_inconclusive();
13143        assert!(matches!(
13144            breakers.admit("prov"),
13145            RouteBindAdmission::Refused {
13146                probe_in_flight: true,
13147                ..
13148            }
13149        ));
13150    }
13151
13152    #[tokio::test]
13153    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13154        for candidate in [false, true] {
13155            let registry = Arc::new(Registry::default());
13156            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13157                [("vault".to_string(), true), ("squatter".to_string(), true)],
13158                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13159            );
13160            let conn = ConnectionId::new(77);
13161            let (ctx, mut rx) = route_ctx(conn);
13162            let initial = capability_manifest("squatter", &[], &[]);
13163            if candidate {
13164                registry
13165                    .register_candidate_with_control_ops(
13166                        initial.clone(),
13167                        PROTOCOL_VERSION,
13168                        conn,
13169                        module_baseline_control_ops(),
13170                    )
13171                    .unwrap();
13172                handler
13173                    .forwarding
13174                    .register_candidate_module_connection(
13175                        conn,
13176                        "squatter".to_string(),
13177                        PROTOCOL_VERSION,
13178                        manifest_concurrency(&initial),
13179                        ctx.egress.clone(),
13180                    )
13181                    .unwrap();
13182            } else {
13183                hello_via_sink(
13184                    &handler,
13185                    &ctx,
13186                    &mut rx,
13187                    hello_frame_with_manifest(initial.clone(), 1),
13188                )
13189                .await;
13190            }
13191            let response = handler
13192                .handle_control_frame(
13193                    &ctx,
13194                    catalog_update_with_capabilities_frame(
13195                        2,
13196                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13197                            .capabilities
13198                            .unwrap(),
13199                    ),
13200                )
13201                .await
13202                .unwrap();
13203            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13204            assert_eq!(
13205                registry
13206                    .get_module_by_connection(conn)
13207                    .unwrap()
13208                    .unwrap()
13209                    .manifest,
13210                initial
13211            );
13212        }
13213    }
13214
13215    #[test]
13216    #[cfg(not(feature = "dev-desktop-approval"))]
13217    fn server_describe_default_build_advertises_no_config_capability() {
13218        let assert_default = |handler: &ControlHandler| {
13219            let request = Frame::build(
13220                FrameType::Request,
13221                control_flags(),
13222                0,
13223                0,
13224                79,
13225                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13226            )
13227            .unwrap();
13228            let responses = handler.handle_server_describe(request).unwrap();
13229            assert_eq!(responses.len(), 1);
13230            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13231            assert_eq!(response["op"], "server.describe");
13232            let capabilities = response["capabilities"]
13233                .as_array()
13234                .expect("capability array");
13235            assert!(
13236                !capabilities.is_empty(),
13237                "exercise an actual describe response, not an empty fixture"
13238            );
13239            assert!(
13240                capabilities
13241                    .iter()
13242                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13243                "a default build must not announce configuration authority: {capabilities:?}"
13244            );
13245        };
13246        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13247        #[cfg(unix)]
13248        {
13249            // A local store does not prove that project-membership validation,
13250            // active-scope usage tracking and approved-program launch selection
13251            // are connected. Defaults must not advertise that authority.
13252            let (_rig, _owner, _supervisor, handler, _spec) =
13253                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13254                );
13255            assert_default(&handler);
13256        }
13257    }
13258
13259    #[test]
13260    fn server_describe_surfaces_required_capability_verdict_fields() {
13261        let registry = Arc::new(Registry::default());
13262        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13263            [
13264                ("consumer".to_string(), true),
13265                ("provider".to_string(), false),
13266            ],
13267            BTreeMap::new(),
13268        );
13269        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13270        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13271            provides: Vec::new(),
13272            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13273                capability: "credentials-provider/v1".to_string(),
13274                need: subc_protocol::manifest::CapabilityNeed::Required,
13275            }],
13276            must_never_reach: Vec::new(),
13277        });
13278        let hello = Frame::build(
13279            FrameType::Hello,
13280            control_flags(),
13281            0,
13282            0,
13283            78,
13284            serde_json::to_vec(&ModuleHelloBody {
13285                manifest: consumer,
13286                protocol_ver: PROTOCOL_VERSION,
13287                control_ops: None,
13288                launch_nonce: None,
13289            })
13290            .expect("HELLO serializes"),
13291        )
13292        .expect("HELLO frame builds");
13293        handler
13294            .handle_control(ConnectionId::new(78), hello)
13295            .expect("consumer registers");
13296        let describe = Frame::build(
13297            FrameType::Request,
13298            control_flags(),
13299            0,
13300            0,
13301            79,
13302            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13303                .expect("request serializes"),
13304        )
13305        .expect("describe frame builds");
13306        let response = handler
13307            .handle_server_describe(describe)
13308            .expect("server.describe succeeds");
13309        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13310        let requirement = &rendered["capability_requirements"][0];
13311        assert_eq!(requirement["consumer"], "consumer");
13312        assert_eq!(requirement["verdict"], "never_provided");
13313        assert_eq!(requirement["episode_seq"], 1);
13314        assert_eq!(requirement["config_satisfiable"], false);
13315        assert_eq!(requirement["runtime_available"], false);
13316        assert!(requirement["detail"]
13317            .as_str()
13318            .expect("detail string")
13319            .contains("credentials-provider/v1"));
13320    }
13321
13322    /// Register a consumer that requires `project-identity/v1` and the provider
13323    /// of it, optionally mark daemon shutdown as begun, then deregister the
13324    /// provider as its connection closes. Returns the `capability.requirement`
13325    /// events that deregistration logged and the verdict the evaluator then
13326    /// holds for the requirement (the one `route.open` refusals read).
13327    fn deregister_required_provider(
13328        daemon_shutdown_begun: bool,
13329    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13330        const CAPABILITY: &str = "project-identity/v1";
13331        let registry = Arc::new(Registry::default());
13332        let daemon_shutdown = DaemonShutdownFlag::default();
13333        let handler = ControlHandler::new(Arc::clone(&registry))
13334            .with_capability_config(
13335                [
13336                    ("consumer".to_string(), true),
13337                    ("provider".to_string(), true),
13338                ],
13339                BTreeMap::new(),
13340            )
13341            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13342        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13343        consumer.capabilities = Some(CapabilityDeclarations {
13344            provides: Vec::new(),
13345            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13346                capability: CAPABILITY.to_string(),
13347                need: subc_protocol::manifest::CapabilityNeed::Required,
13348            }],
13349            must_never_reach: Vec::new(),
13350        });
13351        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13352        let provider_conn = ConnectionId::new(182);
13353        for (conn, manifest, corr) in [
13354            (ConnectionId::new(181), consumer, 181),
13355            (provider_conn, provider, 182),
13356        ] {
13357            let hello = handler
13358                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13359                .expect("module registers");
13360            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13361        }
13362        assert_eq!(
13363            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13364            Some(CapabilityVerdict::Provided),
13365            "the registered provider must satisfy the requirement first"
13366        );
13367        if daemon_shutdown_begun {
13368            daemon_shutdown.set_for_test();
13369        }
13370
13371        let capture = EventCapture::default();
13372        let _subscriber =
13373            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13374        handler
13375            .cleanup_connection(provider_conn)
13376            .expect("provider deregisters");
13377        let events = capture
13378            .events()
13379            .into_iter()
13380            .filter(|event| {
13381                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13382            })
13383            .collect();
13384        (
13385            events,
13386            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13387        )
13388    }
13389
13390    #[test]
13391    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13392        let (events, verdict) = deregister_required_provider(true);
13393        assert_eq!(
13394            verdict,
13395            Some(CapabilityVerdict::NeverProvided),
13396            "shutdown must not change the verdict route.open refusals read"
13397        );
13398        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13399        let event = &events[0];
13400        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13401        assert_eq!(
13402            event.fields.get("cause").map(String::as_str),
13403            Some("\"daemon_shutdown\""),
13404            "{event:?}"
13405        );
13406        assert_eq!(
13407            event.fields.get("verdict").map(String::as_str),
13408            Some("\"never_provided\""),
13409            "{event:?}"
13410        );
13411    }
13412
13413    #[test]
13414    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13415        let (events, verdict) = deregister_required_provider(false);
13416        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13417        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13418        let event = &events[0];
13419        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13420        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13421        assert_eq!(
13422            event.fields.get("verdict").map(String::as_str),
13423            Some("\"never_provided\""),
13424            "{event:?}"
13425        );
13426    }
13427
13428    #[test]
13429    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13430        let registry = Arc::new(Registry::default());
13431        let handler = ControlHandler::new(Arc::clone(&registry));
13432        let hello = handler
13433            .handle_control(
13434                ConnectionId::new(101),
13435                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13436            )
13437            .expect("legacy HELLO registers");
13438        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13439
13440        let request = Frame::build(
13441            FrameType::Request,
13442            control_flags(),
13443            0,
13444            0,
13445            102,
13446            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13447                .expect("catalog request serializes"),
13448        )
13449        .expect("catalog request frame builds");
13450        let response = handler
13451            .handle_catalog_list(request, None)
13452            .expect("catalog list succeeds");
13453        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13454        assert!(
13455            body["modules"][0].get("capabilities").is_none(),
13456            "legacy manifest must retain an absent capabilities field on catalog.list"
13457        );
13458    }
13459
13460    #[test]
13461    fn hello_ack_omits_storage_when_no_storage_config() {
13462        let registry = Arc::new(Registry::default());
13463        let handler = ControlHandler::new(Arc::clone(&registry));
13464        let responses = handler
13465            .handle_control(
13466                ConnectionId::new(1),
13467                hello_frame("aft", PROTOCOL_VERSION, 7),
13468            )
13469            .unwrap();
13470        let ack = parse_ack(&responses[0]);
13471        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13472        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13473    }
13474
13475    #[tokio::test]
13476    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13477        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13478        let registry = Arc::new(Registry::default());
13479        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13480        let responses = handler
13481            .handle_control(
13482                ConnectionId::new(1),
13483                hello_frame("aft", PROTOCOL_VERSION, 7),
13484            )
13485            .unwrap();
13486        let ack = parse_ack(&responses[0]);
13487        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13488
13489        let described = handler
13490            .handle_control_frame(
13491                &route_ctx(ConnectionId::new(2)).0,
13492                Frame::build(
13493                    FrameType::Request,
13494                    control_flags(),
13495                    0,
13496                    0,
13497                    9,
13498                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13499                )
13500                .unwrap(),
13501            )
13502            .await
13503            .unwrap();
13504        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13505            serde_json::from_slice(&described[0].body).unwrap()
13506        else {
13507            panic!("server.describe answered with another shape");
13508        };
13509        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13510    }
13511
13512    #[test]
13513    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13514        // With a central sqlite storage policy, each registering module gets its
13515        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13516        let registry = Arc::new(Registry::default());
13517        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13518            crate::daemon_config::StorageConfig::Sqlite {
13519                data_home: std::path::PathBuf::from("/data"),
13520            },
13521        ));
13522
13523        let responses = handler
13524            .handle_control(
13525                ConnectionId::new(1),
13526                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13527            )
13528            .unwrap();
13529        let ack = parse_ack(&responses[0]);
13530        assert_eq!(
13531            ack.storage,
13532            Some(serde_json::json!({
13533                "module_id": "alfonso-routing",
13534                "storage_namespace": "default",
13535                "isolation": { "kind": "module" },
13536                "backend": {
13537                    "backend": "sqlite",
13538                    "path": "/data/cortexkit/alfonso-routing/store.db"
13539                }
13540            })),
13541            "the delivered descriptor is the module's own sqlite store path"
13542        );
13543    }
13544
13545    #[test]
13546    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13547        let registry = Arc::new(Registry::default());
13548        let handler = ControlHandler::new(Arc::clone(&registry));
13549        let conn = ConnectionId::new(1);
13550        let responses = handler
13551            .handle_control(
13552                conn,
13553                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13554            )
13555            .unwrap();
13556        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13557        let registration = registry.get_module("aft").unwrap().unwrap();
13558        assert_eq!(registration.control_ops, module_baseline_control_ops());
13559
13560        let frame =
13561            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13562        assert!(handler
13563            .guard_module_control_op(&frame, "aft", "route.bind")
13564            .unwrap()
13565            .is_none());
13566        let error = handler
13567            .guard_module_control_op(&frame, "aft", "test.synthetic")
13568            .unwrap()
13569            .expect("synthetic ungranted op should be rejected");
13570        assert_eq!(error.header.ty, FrameType::Error);
13571        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13572    }
13573
13574    #[test]
13575    fn hello_control_ops_some_adds_optional_grants() {
13576        let registry = Arc::new(Registry::default());
13577        let handler = ControlHandler::new(Arc::clone(&registry));
13578        handler
13579            .handle_control(
13580                ConnectionId::new(1),
13581                hello_frame_with_control_ops(
13582                    "aft",
13583                    PROTOCOL_VERSION,
13584                    7,
13585                    Some(vec![
13586                        "future.synthetic".to_string(),
13587                        "route.bind".to_string(),
13588                    ]),
13589                ),
13590            )
13591            .unwrap();
13592        let registration = registry.get_module("aft").unwrap().unwrap();
13593        assert_eq!(
13594            registration.control_ops,
13595            vec![
13596                "route.bind".to_string(),
13597                "route.status".to_string(),
13598                "future.synthetic".to_string(),
13599            ]
13600        );
13601        let frame =
13602            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13603        assert!(handler
13604            .guard_module_control_op(&frame, "aft", "future.synthetic")
13605            .unwrap()
13606            .is_none());
13607    }
13608
13609    #[tokio::test]
13610    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13611        let registry = Arc::new(Registry::default());
13612        let forwarding = Arc::new(ForwardingTable::default());
13613        let handler =
13614            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13615        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13616        hello_via_sink(
13617            &handler,
13618            &module_ctx,
13619            &mut module_rx,
13620            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13621        )
13622        .await;
13623
13624        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13625        let responses = handler
13626            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13627            .await
13628            .unwrap();
13629        assert_eq!(responses.len(), 1);
13630        assert_eq!(responses[0].header.ty, FrameType::Error);
13631        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13632        assert!(module_rx.try_recv().is_err());
13633    }
13634
13635    #[tokio::test]
13636    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13637        let registry = Arc::new(Registry::default());
13638        let forwarding = Arc::new(ForwardingTable::default());
13639        let handler =
13640            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13641        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13642        hello_via_sink(
13643            &handler,
13644            &module_ctx,
13645            &mut module_rx,
13646            hello_frame_with_control_ops(
13647                "aft",
13648                PROTOCOL_VERSION,
13649                7,
13650                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13651            ),
13652        )
13653        .await;
13654
13655        let project_root = unique_project_root("demux");
13656        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13657        let route_handler = handler.clone();
13658        let route_task = tokio::spawn(async move {
13659            route_handler
13660                .handle_control_frame(
13661                    &route_client_ctx,
13662                    route_open_frame(100, "aft", project_root),
13663                )
13664                .await
13665                .unwrap()
13666        });
13667        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13668            .await
13669            .unwrap()
13670            .unwrap();
13671        assert!(matches!(
13672            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13673            ModuleControlRequest::RouteBind { .. }
13674        ));
13675
13676        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13677        let health_handler = handler.clone();
13678        let health_task = tokio::spawn(async move {
13679            health_handler
13680                .handle_control_frame(
13681                    &health_client_ctx,
13682                    supervisor_health_probe_frame(101, "aft"),
13683                )
13684                .await
13685                .unwrap()
13686        });
13687        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13688            .await
13689            .unwrap()
13690            .unwrap();
13691        assert_eq!(
13692            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13693            ModuleControlRequest::HealthCheck {}
13694        );
13695
13696        handler
13697            .handle_control_frame(
13698                &module_ctx,
13699                health_response(health_frame.header.corr, HealthStatus::Degraded),
13700            )
13701            .await
13702            .unwrap();
13703        let health_response = health_task.await.unwrap();
13704        assert_eq!(health_response.len(), 1);
13705        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13706            ClientControlResponse::SupervisorHealthProbe {
13707                module_id,
13708                status,
13709                detail,
13710                metrics,
13711            } => {
13712                assert_eq!(module_id, "aft");
13713                assert_eq!(status, HealthStatus::Degraded);
13714                assert_eq!(detail.as_deref(), Some("warming"));
13715                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13716            }
13717            other => panic!("unexpected health response: {other:?}"),
13718        }
13719
13720        handler
13721            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13722            .await
13723            .unwrap();
13724        let route_response = route_task.await.unwrap();
13725        assert!(route_response.is_empty());
13726        let published = route_client_rx.recv().await.unwrap();
13727        assert!(matches!(
13728            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13729            ClientControlResponse::RouteOpen { .. }
13730        ));
13731    }
13732
13733    /// Start one `route.open` on `client_connection` and return its still-running
13734    /// handler task together with the `route.bind` the module received for it.
13735    /// The handler blocks until the module answers, so it has to run as a task
13736    /// while the test drives the module side.
13737    async fn relay_route_open(
13738        handler: &ControlHandler,
13739        client_connection: ConnectionId,
13740        client_egress: &FrameSink,
13741        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13742        corr: u64,
13743        module_id: &str,
13744        project_root_label: &str,
13745    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13746        let ctx = RouteCtx {
13747            connection_id: client_connection,
13748            egress: client_egress.clone(),
13749        };
13750        let handler = handler.clone();
13751        let project_root = unique_project_root(project_root_label);
13752        let module_id = module_id.to_string();
13753        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13754        let task = tokio::spawn(async move {
13755            let _guard = tracing::dispatcher::set_default(&dispatch);
13756            handler
13757                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13758                .await
13759                .unwrap()
13760        });
13761        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13762            .await
13763            .expect("module receives the relayed route.bind")
13764            .expect("module egress is open");
13765        (task, bind.frame)
13766    }
13767
13768    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13769        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13770            ModuleControlRequest::RouteBind {
13771                route_channel,
13772                epoch,
13773                ..
13774            } => (route_channel, epoch),
13775            other => panic!("expected a route.bind request, got {other:?}"),
13776        }
13777    }
13778
13779    fn published_route(frame: &Frame) -> (u16, u32) {
13780        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13781            ClientControlResponse::RouteOpen {
13782                route_channel,
13783                route_epoch,
13784                ..
13785            } => (route_channel, route_epoch),
13786            other => panic!("expected a route.open response, got {other:?}"),
13787        }
13788    }
13789
13790    /// Reproduction of a production outage. A client had `route.open`s in
13791    /// flight to a module and was already marked closing -- its egress had refused a
13792    /// module frame, so the daemon asked its connection to end -- while its sink
13793    /// was still open. When the module acked those binds, the daemon refused to
13794    /// commit a route for a closing client, and that refusal was returned from
13795    /// the MODULE connection's frame handler, where a router error that has no
13796    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13797    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13798    /// its tools for hours -- one client's teardown took down a connection
13799    /// carrying ~170 other routes.
13800    ///
13801    /// The window is opened here by calling the production path that opens it
13802    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13803    /// state that matters is "in `closing_connections`, sink still open, relay
13804    /// still pending", and it lasts only from the close request until the
13805    /// connection loop reacts to it; a socket-level test can flood a client into
13806    /// that escalation but cannot pin the module's ack inside the window. Closing
13807    /// the socket instead takes the other path entirely -- connection teardown
13808    /// removes the pending relay under the same lock, so the ack finds nothing.
13809    #[tokio::test]
13810    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13811        let registry = Arc::new(Registry::default());
13812        let forwarding = Arc::new(ForwardingTable::default());
13813        let handler =
13814            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13815
13816        let module_connection = ConnectionId::new(30);
13817        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13818        hello_via_sink(
13819            &handler,
13820            &module_ctx,
13821            &mut module_rx,
13822            hello_frame("aft", PROTOCOL_VERSION, 7),
13823        )
13824        .await;
13825
13826        let dying_client = ConnectionId::new(31);
13827        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13828
13829        // A published route on the dying client. The escalation below only marks
13830        // a connection closing for a route it has already published.
13831        let (first_task, first_bind) = relay_route_open(
13832            &handler,
13833            dying_client,
13834            &dying_ctx.egress,
13835            &mut module_rx,
13836            100,
13837            "aft",
13838            "closing-first",
13839        )
13840        .await;
13841        handler
13842            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13843            .await
13844            .unwrap();
13845        assert!(first_task.await.unwrap().is_empty());
13846        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13847
13848        // A second route.open from the same client, relayed and awaiting its ack.
13849        let (second_task, second_bind) = relay_route_open(
13850            &handler,
13851            dying_client,
13852            &dying_ctx.egress,
13853            &mut module_rx,
13854            101,
13855            "aft",
13856            "closing-second",
13857        )
13858        .await;
13859        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13860
13861        // The window: the client is closing, its sink is still open, and its
13862        // second bind is still pending.
13863        assert!(forwarding
13864            .escalate_client_delivery_failure(
13865                dying_client,
13866                first_channel,
13867                first_epoch,
13868                CloseReason::new(
13869                    "module_to_client_delivery_failed",
13870                    "client egress refused a module frame",
13871                ),
13872                crate::forwarding::UndeliveredFrame {
13873                    module_id: None,
13874                    sink: &dying_ctx.egress,
13875                },
13876            )
13877            .unwrap());
13878        assert!(!dying_ctx.egress.is_closed());
13879
13880        // The frame that used to end the module connection.
13881        let ack = handler
13882            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13883            .await;
13884        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13885        if module_loop_error.is_some() {
13886            // What the server's connection loop does with a router error that has
13887            // no ERROR-frame translation: end the connection, which releases the
13888            // module's registration and every route on it.
13889            handler.cleanup_connection(module_connection).unwrap();
13890        }
13891        // Read the module's next frame before opening the co-tenant's route, so
13892        // the GOODBYE assertion below is about THIS ack and not about later
13893        // traffic. `None` means the module was told nothing.
13894        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13895            .await
13896            .ok()
13897            .flatten();
13898
13899        // 1. The module connection is still registered.
13900        assert!(
13901            registry
13902                .get_module_by_connection(module_connection)
13903                .unwrap()
13904                .is_some(),
13905            "one client's closing connection ended the shared module connection: \
13906             {module_loop_error:?}"
13907        );
13908        // ...and still serving: another client can open and use a route on it.
13909        let cotenant = ConnectionId::new(32);
13910        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13911        let (cotenant_task, cotenant_bind) = relay_route_open(
13912            &handler,
13913            cotenant,
13914            &cotenant_ctx.egress,
13915            &mut module_rx,
13916            102,
13917            "aft",
13918            "closing-cotenant",
13919        )
13920        .await;
13921        handler
13922            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13923            .await
13924            .unwrap();
13925        assert!(cotenant_task.await.unwrap().is_empty());
13926        let (cotenant_channel, cotenant_epoch) =
13927            published_route(&cotenant_rx.recv().await.unwrap());
13928        assert!(matches!(
13929            forwarding
13930                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13931                .unwrap(),
13932            DataRoute::Client(DataRouteState::Bound(_))
13933        ));
13934
13935        // 2. The module was told to drop the binding it created for the route
13936        //    that will never be published.
13937        let goodbye = post_ack_module_frame
13938            .expect("module receives a GOODBYE for the abandoned route channel");
13939        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13940        assert_eq!(goodbye.header.channel, abandoned_channel);
13941        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13942
13943        // 3. The dying client received nothing: no route was ever published to
13944        //    it. Its route.open is answered as unavailable, which the connection
13945        //    loop would write to a socket that is already going away.
13946        assert!(dying_rx.try_recv().is_err());
13947        let second_response = second_task.await.unwrap();
13948        assert_eq!(second_response.len(), 1);
13949        assert_eq!(
13950            parse_error(&second_response[0])["code"],
13951            "target_unavailable"
13952        );
13953    }
13954
13955    /// One `catalog.list` as a client sees it: the generation and the listed
13956    /// module ids with their readiness.
13957    async fn catalog_snapshot(
13958        handler: &ControlHandler,
13959        client_ctx: &RouteCtx,
13960        corr: u64,
13961    ) -> (u64, Vec<(String, bool)>) {
13962        let body =
13963            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13964        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13965        let reply = handler
13966            .handle_control_frame(client_ctx, request)
13967            .await
13968            .unwrap()
13969            .pop()
13970            .unwrap();
13971        let ClientControlResponse::CatalogList {
13972            generation,
13973            modules,
13974            ..
13975        } = serde_json::from_slice(&reply.body).unwrap()
13976        else {
13977            panic!("not a catalog.list reply");
13978        };
13979        (
13980            generation,
13981            modules
13982                .into_iter()
13983                .map(|entry| (entry.module_id, entry.ready))
13984                .collect(),
13985        )
13986    }
13987
13988    /// A handler whose HELLO for module "aft" on connection 40 is parked
13989    /// between reserving its registry entry and installing its forwarding
13990    /// endpoint. Returns the handler, the two-party barrier (wait once to know
13991    /// the HELLO is parked, once more to release it), the HELLO's thread, and
13992    /// the module's context and receiver.
13993    fn hello_held_before_forwarding() -> (
13994        ControlHandler,
13995        Arc<std::sync::Barrier>,
13996        std::thread::JoinHandle<Vec<Frame>>,
13997        RouteCtx,
13998        mpsc::Receiver<crate::router::OutboundFrame>,
13999    ) {
14000        let hold = Arc::new(std::sync::Barrier::new(2));
14001        let handler = ControlHandler::with_forwarding(
14002            Arc::new(Registry::default()),
14003            Arc::new(ForwardingTable::default()),
14004        )
14005        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
14006        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14007        let hello = {
14008            let handler = handler.clone();
14009            let module_ctx = module_ctx.clone();
14010            std::thread::spawn(move || {
14011                handler
14012                    .handle_hello(
14013                        module_ctx.connection_id,
14014                        Some(module_ctx.egress.clone()),
14015                        hello_frame("aft", PROTOCOL_VERSION, 7),
14016                    )
14017                    .unwrap()
14018            })
14019        };
14020        (handler, hold, hello, module_ctx, module_rx)
14021    }
14022
14023    /// If a lookup can acquire the registry while publication is parked, let
14024    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
14025    /// after the lookup has tried the lock. Both schedules avoid timing guesses
14026    /// and return the actual lookup result, including an unpublished snapshot
14027    /// when the publication lock is missing.
14028    fn lookup_during_hello_publication<T: Send + 'static>(
14029        registry: &Registry,
14030        hold: &std::sync::Barrier,
14031        lookup: impl FnOnce() -> T + Send + 'static,
14032    ) -> T {
14033        let attempted = registry.observe_next_lock_attempt();
14034        let reader = std::thread::spawn(lookup);
14035        if attempted.recv().unwrap() {
14036            let result = reader.join().unwrap();
14037            hold.wait();
14038            result
14039        } else {
14040            hold.wait();
14041            reader.join().unwrap()
14042        }
14043    }
14044
14045    #[test]
14046    fn catalog_read_after_hello_ack_waits_for_publication() {
14047        let registry = Arc::new(Registry::default());
14048        let hold = Arc::new(std::sync::Barrier::new(2));
14049        let mut handler = ControlHandler::with_forwarding(
14050            Arc::clone(&registry),
14051            Arc::new(ForwardingTable::default()),
14052        );
14053        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
14054        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14055        let hello = {
14056            let handler = handler.clone();
14057            std::thread::spawn(move || {
14058                handler
14059                    .handle_hello(
14060                        module_ctx.connection_id,
14061                        Some(module_ctx.egress),
14062                        hello_frame("aft", PROTOCOL_VERSION, 7),
14063                    )
14064                    .unwrap()
14065            })
14066        };
14067        hold.wait();
14068        assert_eq!(
14069            module_rx.try_recv().unwrap().frame.header.ty,
14070            FrameType::HelloAck
14071        );
14072        let replies = lookup_during_hello_publication(&registry, &hold, move || {
14073            // A different connection can issue catalog.list as soon as the
14074            // module has read its ACK, even while HELLO has not returned.
14075            let request = Frame::build(
14076                FrameType::Request,
14077                control_flags(),
14078                0,
14079                0,
14080                300,
14081                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
14082            )
14083            .unwrap();
14084            handler.handle_catalog_list(request, None).unwrap()
14085        });
14086        assert!(hello.join().unwrap().is_empty());
14087        let ClientControlResponse::CatalogList {
14088            generation,
14089            modules,
14090            ..
14091        } = serde_json::from_slice(&replies[0].body).unwrap()
14092        else {
14093            panic!("not a catalog.list reply");
14094        };
14095        assert_eq!(
14096            modules
14097                .iter()
14098                .map(|entry| entry.module_id.as_str())
14099                .collect::<Vec<_>>(),
14100            vec!["aft"]
14101        );
14102        assert_eq!(generation, 1);
14103    }
14104
14105    /// While a HELLO has reserved its registry entry but its forwarding
14106    /// endpoint is not installed yet, `route.open` to the module can only be
14107    /// refused. `catalog.list` must not list the module in that window: a
14108    /// client that opens a route as soon as it sees a module listed and ready
14109    /// would be refused for a module the daemon had just advertised. The
14110    /// refusal in the window stays the retryable `target_unavailable`, never
14111    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14112    /// Once the HELLO completes, the module is listed and a route to it opens.
14113    #[tokio::test]
14114    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14115        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14116        let client = ConnectionId::new(41);
14117        let (client_ctx, mut client_rx) = route_ctx(client);
14118
14119        hold.wait();
14120        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14121        assert!(handler.registry.get_module("aft").unwrap().is_some());
14122        assert!(!handler
14123            .forwarding
14124            .has_live_module_connection("aft")
14125            .unwrap());
14126        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14127        assert!(
14128            listed.is_empty(),
14129            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14130        );
14131        let refused = handler
14132            .handle_control_frame(
14133                &client_ctx,
14134                route_open_frame(301, "aft", unique_project_root("listed-window")),
14135            )
14136            .await
14137            .unwrap();
14138        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14139        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14140        let duplicate = handler
14141            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14142            .await
14143            .unwrap();
14144        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14145
14146        hold.wait();
14147        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14148        let ack = module_rx.try_recv().unwrap().frame;
14149        assert_eq!(ack.header.ty, FrameType::HelloAck);
14150        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14151        assert_eq!(listed, vec![("aft".to_string(), true)]);
14152
14153        let (open_task, bind) = relay_route_open(
14154            &handler,
14155            client,
14156            &client_ctx.egress,
14157            &mut module_rx,
14158            303,
14159            "aft",
14160            "listed-after",
14161        )
14162        .await;
14163        assert!(handler
14164            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14165            .await
14166            .unwrap()
14167            .is_empty());
14168        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14169        published_route(&client_rx.try_recv().unwrap().frame);
14170    }
14171
14172    /// A catalog watcher keys on the generation: when it changes, it re-reads
14173    /// the listing. So the generation must advance exactly when the module
14174    /// appears. If it advanced while the module was still hidden, a watcher
14175    /// would read the new generation without the module, and the module would
14176    /// later appear under that same generation with nothing telling the
14177    /// watcher to look again.
14178    #[tokio::test]
14179    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14180        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14181        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14182        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14183
14184        hold.wait();
14185        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14186        assert!(listed.is_empty());
14187        assert_eq!(
14188            during, before,
14189            "the generation moved while the module was not listed"
14190        );
14191
14192        hold.wait();
14193        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14194        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14195        assert_eq!(listed, vec![("aft".to_string(), true)]);
14196        assert_eq!(
14197            after,
14198            before + 1,
14199            "the module appeared without exactly one generation bump"
14200        );
14201    }
14202
14203    /// A HELLO whose forwarding endpoint cannot be installed (here the
14204    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14205    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14206    /// and the catalog generation where it was.
14207    #[tokio::test]
14208    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14209        let registry = Arc::new(Registry::default());
14210        let handler = ControlHandler::with_forwarding(
14211            Arc::clone(&registry),
14212            Arc::new(ForwardingTable::default()),
14213        );
14214        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14215        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14216        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14217        drop(module_rx);
14218
14219        let replies = handler
14220            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14221            .await
14222            .unwrap();
14223        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14224        assert!(registry.get_module("aft").unwrap().is_none());
14225        assert!(registry
14226            .get_module_by_connection(module_ctx.connection_id)
14227            .unwrap()
14228            .is_none());
14229        assert_eq!(
14230            catalog_snapshot(&handler, &client_ctx, 301).await,
14231            (before, Vec::new())
14232        );
14233    }
14234
14235    /// A handler whose `route.open` parks after queueing the route.bind and
14236    /// before marking it enqueued, with module "aft" registered on connection
14237    /// 40. Returns the two-party barrier that parks and releases it.
14238    async fn route_open_held_after_bind_send() -> (
14239        ControlHandler,
14240        Arc<tokio::sync::Barrier>,
14241        RouteCtx,
14242        mpsc::Receiver<crate::router::OutboundFrame>,
14243    ) {
14244        let hold = Arc::new(tokio::sync::Barrier::new(2));
14245        let handler = ControlHandler::with_forwarding(
14246            Arc::new(Registry::default()),
14247            Arc::new(ForwardingTable::default()),
14248        )
14249        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14250        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14251        hello_via_sink(
14252            &handler,
14253            &module_ctx,
14254            &mut module_rx,
14255            hello_frame("aft", PROTOCOL_VERSION, 7),
14256        )
14257        .await;
14258        (handler, hold, module_ctx, module_rx)
14259    }
14260
14261    /// A fast module acks the route.bind, and the reader commits the route,
14262    /// before `route.open` has marked the relay enqueued. The daemon used to
14263    /// read the missing relay as an abandoned bind and send the module a
14264    /// GOODBYE for the route it had just committed: the client was told its
14265    /// route was open, the module unbound the channel, and the client's first
14266    /// request was dropped on the module side as unbound.
14267    #[tokio::test]
14268    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14269        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14270        let client = ConnectionId::new(41);
14271        let (client_ctx, mut client_rx) = route_ctx(client);
14272
14273        let (open_task, bind) = relay_route_open(
14274            &handler,
14275            client,
14276            &client_ctx.egress,
14277            &mut module_rx,
14278            200,
14279            "aft",
14280            "acked-before-mark",
14281        )
14282        .await;
14283        let (module_channel, module_epoch) = route_bind_channel(&bind);
14284        // route.open is now parked between queueing the bind and marking it.
14285        hold.wait().await;
14286
14287        // The module answers inside that window, and the route commits.
14288        assert!(handler
14289            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14290            .await
14291            .unwrap()
14292            .is_empty());
14293        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14294
14295        hold.wait().await;
14296        assert!(
14297            open_task.await.unwrap().is_empty(),
14298            "route.open answers accepted"
14299        );
14300
14301        // Every frame route.open could have sent is already queued, because it
14302        // has returned; the module must have been sent nothing.
14303        match module_rx.try_recv() {
14304            Err(mpsc::error::TryRecvError::Empty) => {}
14305            Ok(outbound) => panic!(
14306                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14307                outbound.frame.header.ty,
14308                outbound.frame.header.channel,
14309                outbound.frame.header.epoch
14310            ),
14311            Err(err) => panic!("module egress closed: {err}"),
14312        }
14313
14314        // The client's first request on the route is the next thing the module
14315        // reads, on the binding it just created.
14316        let router = Router::with_control_handler(Arc::new(handler.clone()));
14317        let request = Frame::build(
14318            FrameType::Request,
14319            Flags::new(true, Priority::Interactive, false),
14320            client_channel,
14321            client_epoch,
14322            201,
14323            b"first request".to_vec(),
14324        )
14325        .unwrap();
14326        router
14327            .route_for_connection(&client_ctx, request)
14328            .await
14329            .unwrap();
14330        let delivered = module_rx.try_recv().unwrap().frame;
14331        assert_eq!(delivered.header.ty, FrameType::Request);
14332        assert_eq!(
14333            (delivered.header.channel, delivered.header.epoch),
14334            (module_channel, module_epoch)
14335        );
14336        assert_eq!(delivered.body, b"first request");
14337    }
14338
14339    /// The client goes away while `route.open` is still queueing the bind, so
14340    /// the relay is dropped with no module reply. The teardown cannot send the
14341    /// GOODBYE itself (it could reach the module ahead of the bind), so
14342    /// `route.open` must send it once the bind is queued; otherwise the module
14343    /// keeps a binding the daemon will never commit.
14344    #[tokio::test]
14345    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14346        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14347        let client = ConnectionId::new(42);
14348        let (client_ctx, _client_rx) = route_ctx(client);
14349
14350        let (open_task, bind) = relay_route_open(
14351            &handler,
14352            client,
14353            &client_ctx.egress,
14354            &mut module_rx,
14355            300,
14356            "aft",
14357            "released-before-mark",
14358        )
14359        .await;
14360        let (module_channel, module_epoch) = route_bind_channel(&bind);
14361        hold.wait().await;
14362
14363        handler.cleanup_connection(client).unwrap();
14364        assert!(
14365            module_rx.try_recv().is_err(),
14366            "client teardown must not GOODBYE a bind route.open is still queueing"
14367        );
14368
14369        hold.wait().await;
14370        let response = open_task.await.unwrap();
14371        assert_eq!(response.len(), 1);
14372        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14373
14374        let goodbye = module_rx
14375            .try_recv()
14376            .expect("module is told to drop the binding the daemon abandoned")
14377            .frame;
14378        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14379        assert_eq!(
14380            (goodbye.header.channel, goodbye.header.epoch),
14381            (module_channel, module_epoch)
14382        );
14383        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14384    }
14385
14386    /// The module acks inside the same window, but the client's egress closed
14387    /// first, so the reader refuses to commit. The ack proves the module holds
14388    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14389    /// send a second one.
14390    #[tokio::test]
14391    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14392        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14393        let client = ConnectionId::new(43);
14394        let (client_ctx, client_rx) = route_ctx(client);
14395
14396        let (open_task, bind) = relay_route_open(
14397            &handler,
14398            client,
14399            &client_ctx.egress,
14400            &mut module_rx,
14401            400,
14402            "aft",
14403            "gone-client-before-mark",
14404        )
14405        .await;
14406        let (module_channel, module_epoch) = route_bind_channel(&bind);
14407        hold.wait().await;
14408
14409        drop(client_rx);
14410        assert!(client_ctx.egress.is_closed());
14411        handler
14412            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14413            .await
14414            .unwrap();
14415
14416        hold.wait().await;
14417        let response = open_task.await.unwrap();
14418        assert_eq!(response.len(), 1);
14419        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14420
14421        let goodbye = module_rx
14422            .try_recv()
14423            .expect("module is told to drop the binding it acked")
14424            .frame;
14425        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14426        assert_eq!(
14427            (goodbye.header.channel, goodbye.header.epoch),
14428            (module_channel, module_epoch)
14429        );
14430        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14431        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14432    }
14433
14434    /// The fence at the module-loop boundary, stated as its own contract: which
14435    /// forwarding failures are allowed to end the module connection that is being
14436    /// served. A `ConnectionClosing` naming some client is about that client, and
14437    /// a module connection is shared; the same error naming the module's own
14438    /// connection is about this connection and must stay fatal, as must failures
14439    /// that are about the forwarding table itself.
14440    #[test]
14441    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14442        let handler = ControlHandler::default();
14443        let module_connection = ConnectionId::new(30);
14444        let client_connection = ConnectionId::new(31);
14445
14446        handler
14447            .refuse_to_end_module_connection_for_a_client(
14448                module_connection,
14449                77,
14450                ForwardingError::ConnectionClosing {
14451                    connection_id: client_connection,
14452                },
14453            )
14454            .expect("a closing client must never end the module connection");
14455
14456        assert!(matches!(
14457            handler.refuse_to_end_module_connection_for_a_client(
14458                module_connection,
14459                78,
14460                ForwardingError::ConnectionClosing {
14461                    connection_id: module_connection,
14462                },
14463            ),
14464            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14465                connection_id
14466            })) if connection_id == module_connection
14467        ));
14468        assert!(matches!(
14469            handler.refuse_to_end_module_connection_for_a_client(
14470                module_connection,
14471                79,
14472                ForwardingError::Poisoned,
14473            ),
14474            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14475        ));
14476        assert!(matches!(
14477            handler.refuse_to_end_module_connection_for_a_client(
14478                module_connection,
14479                80,
14480                ForwardingError::StaleModuleEndpoint,
14481            ),
14482            Err(RouterError::Forwarding(
14483                ForwardingError::StaleModuleEndpoint
14484            ))
14485        ));
14486    }
14487
14488    /// The spawn-attestation guard is what stops a connected module from claiming
14489    /// another module's identity and being stamped `Reserved` for it. Every other
14490    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14491    /// correct one is what the rest of the flow needs -- so the guard's rejection
14492    /// branch was never the subject of an assertion, only its acceptance branch.
14493    ///
14494    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14495    /// whole subc-core library suite green; only the forwarding integration tests
14496    /// notice, and they notice for unrelated reasons. This test exists so the
14497    /// refusal itself is asserted where the guard lives: it fails if the identity
14498    /// check stops refusing, which is the direction that matters, since a guard
14499    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14500    #[tokio::test]
14501    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14502        let registry = Arc::new(Registry::default());
14503        let forwarding = Arc::new(ForwardingTable::default());
14504        let supervisor = SupervisorHandle::new();
14505        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14506        let handler =
14507            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14508                .with_supervisor(supervisor);
14509
14510        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14511        hello_via_sink(
14512            &handler,
14513            &target_ctx,
14514            &mut target_rx,
14515            hello_frame("target", PROTOCOL_VERSION, 1),
14516        )
14517        .await;
14518
14519        // A real supervised module id presenting the wrong nonce. This is the
14520        // impersonation case: the attacker knows a privileged module_id, which is
14521        // public, and guesses at the nonce, which is not.
14522        let wrong_nonce = handler
14523            .handle_control_frame(
14524                &route_ctx(ConnectionId::new(91)).0,
14525                route_open_frame_with_admission_facts(
14526                    20,
14527                    "target",
14528                    unique_project_root("admission-facts"),
14529                    Some(subc_control::ConsumerIdentity {
14530                        module_id: "fed".to_string(),
14531                        launch_nonce: "not-the-real-nonce".to_string(),
14532                    }),
14533                    None,
14534                ),
14535            )
14536            .await
14537            .unwrap();
14538        assert_eq!(
14539            parse_error(&wrong_nonce[0])["code"],
14540            "bad_consumer_identity",
14541            "a mismatched launch nonce must be refused, not stamped Reserved"
14542        );
14543
14544        // A module id the supervisor never spawned at all, so no nonce exists to
14545        // compare against. An implementation that treats "no record" as "nothing
14546        // to check" fails open here while passing the case above.
14547        let never_spawned = handler
14548            .handle_control_frame(
14549                &route_ctx(ConnectionId::new(92)).0,
14550                route_open_frame_with_admission_facts(
14551                    21,
14552                    "target",
14553                    unique_project_root("admission-facts"),
14554                    Some(subc_control::ConsumerIdentity {
14555                        module_id: "never-spawned".to_string(),
14556                        launch_nonce: "any-nonce".to_string(),
14557                    }),
14558                    None,
14559                ),
14560            )
14561            .await
14562            .unwrap();
14563        assert_eq!(
14564            parse_error(&never_spawned[0])["code"],
14565            "bad_consumer_identity",
14566            "an unspawned module_id must be refused rather than accepted for lack of a record"
14567        );
14568    }
14569
14570    /// The refusal test above proves the guard says NO. Nothing proved it can say
14571    /// YES, and the difference is not academic: replacing the whole authorization
14572    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14573    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14574    /// library tests GREEN. The one that notices does so by HANGING, because it
14575    /// waits for a bind that can no longer happen.
14576    ///
14577    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14578    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14579    /// hangs too and gets blamed on the runner. So a total revocation of the
14580    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14581    /// to code.
14582    ///
14583    /// The bias is structural rather than accidental. A REFUSAL looks like a
14584    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14585    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14586    /// suite for that reason, and this one is the purest case in the daemon.
14587    ///
14588    /// This test asserts the EFFECT rather than the absence of an error: the module
14589    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14590    /// A guard that admitted nobody would produce no bind at all; one that admitted
14591    /// everybody would stamp the wrong principal, which the refusal test catches.
14592    #[tokio::test]
14593    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14594        let registry = Arc::new(Registry::default());
14595        let forwarding = Arc::new(ForwardingTable::default());
14596        let supervisor = SupervisorHandle::new();
14597        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14598        let handler =
14599            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14600                .with_supervisor(supervisor);
14601
14602        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14603        hello_via_sink(
14604            &handler,
14605            &target_ctx,
14606            &mut target_rx,
14607            hello_frame("target", PROTOCOL_VERSION, 1),
14608        )
14609        .await;
14610
14611        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14612        let route_handler = handler.clone();
14613        let route_task = tokio::spawn(async move {
14614            route_handler
14615                .handle_control_frame(
14616                    &client_ctx,
14617                    route_open_frame_with_admission_facts(
14618                        30,
14619                        "target",
14620                        unique_project_root("admission-facts"),
14621                        Some(subc_control::ConsumerIdentity {
14622                            module_id: "fed".to_string(),
14623                            launch_nonce: "fed-nonce".to_string(),
14624                        }),
14625                        None,
14626                    ),
14627                )
14628                .await
14629                .unwrap()
14630        });
14631
14632        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14633        // the very mutation it exists to catch -- a guard that admits nobody -- no
14634        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14635        // exact defect being fixed: a total revocation detected only as a stalled
14636        // suite, which reads as flakiness and invites a retry. An acceptance test
14637        // that waits for an effect must bound the wait, or a red becomes a hang.
14638        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14639            .await
14640            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14641            .expect("module control channel closed before route.bind");
14642        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14643        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14644            panic!("expected route.bind")
14645        };
14646        assert_eq!(
14647            principal,
14648            Some(Principal::Reserved {
14649                module_id: "fed".to_string()
14650            }),
14651            "a correctly attested consumer must be stamped Reserved for its own id"
14652        );
14653
14654        handler
14655            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14656            .await
14657            .unwrap();
14658        assert!(route_task.await.unwrap().is_empty());
14659        assert!(
14660            matches!(
14661                serde_json::from_slice::<ClientControlResponse>(
14662                    &client_rx.recv().await.unwrap().body
14663                )
14664                .unwrap(),
14665                ClientControlResponse::RouteOpen { .. }
14666            ),
14667            "the route must actually open, not merely avoid an error"
14668        );
14669    }
14670
14671    #[tokio::test(start_paused = true)]
14672    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14673        let registry = Arc::new(Registry::default());
14674        let forwarding = Arc::new(ForwardingTable::default());
14675        let supervisor = SupervisorHandle::new();
14676        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14677        let handler =
14678            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14679                .with_supervisor(supervisor);
14680
14681        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14682        hello_via_sink(
14683            &handler,
14684            &target_ctx,
14685            &mut target_rx,
14686            hello_frame("target", PROTOCOL_VERSION, 1),
14687        )
14688        .await;
14689
14690        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14691        let direct_handler = handler.clone();
14692        let direct_open = tokio::spawn(async move {
14693            direct_handler
14694                .handle_control_frame(
14695                    &direct_ctx,
14696                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14697                )
14698                .await
14699                .unwrap()
14700        });
14701        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14702            .await
14703            .expect("no direct route.bind within 5s")
14704            .expect("target control channel closed before direct route.bind");
14705        handler
14706            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14707            .await
14708            .unwrap();
14709        assert!(direct_open.await.unwrap().is_empty());
14710        let _ = direct_rx.recv().await.unwrap();
14711
14712        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14713        let reserved_handler = handler.clone();
14714        let reserved_open = tokio::spawn(async move {
14715            reserved_handler
14716                .handle_control_frame(
14717                    &reserved_ctx,
14718                    route_open_frame_with_admission_facts(
14719                        3,
14720                        "target",
14721                        unique_project_root("admission-facts"),
14722                        Some(ConsumerIdentity {
14723                            module_id: "fed".to_string(),
14724                            launch_nonce: "fed-nonce".to_string(),
14725                        }),
14726                        None,
14727                    ),
14728                )
14729                .await
14730                .unwrap()
14731        });
14732        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14733            .await
14734            .expect("no reserved route.bind within 5s")
14735            .expect("target control channel closed before reserved route.bind");
14736        handler
14737            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14738            .await
14739            .unwrap();
14740        assert!(reserved_open.await.unwrap().is_empty());
14741        let _ = reserved_rx.recv().await.unwrap();
14742
14743        forwarding
14744            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14745            .unwrap();
14746        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14747        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14748            module_id: Some("target".to_string()),
14749        })
14750        .unwrap();
14751        let census_frame =
14752            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14753        let response = handler
14754            .handle_control_frame(&census_ctx, census_frame)
14755            .await
14756            .unwrap()
14757            .pop()
14758            .unwrap();
14759        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14760        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14761        assert!(matches!(
14762            decoded,
14763            ClientControlResponse::SupervisorRoutes { .. }
14764        ));
14765        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14766        assert_eq!(routes.len(), 2);
14767        assert!(routes.iter().all(|route| route["draining"] == true));
14768        // The census carries WHY: the reason the drain was begun with, in the
14769        // route.closing vocabulary, on every draining route this drain marked.
14770        assert!(
14771            routes.iter().all(|route| route["drain_reason"] == "reload"),
14772            "draining routes must name the drain's reason: {routes:?}"
14773        );
14774        assert!(routes.iter().any(|route| {
14775            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14776        }));
14777        assert!(routes.iter().any(|route| {
14778            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14779        }));
14780
14781        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14782            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14783        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14784            std::fs::write(
14785                &golden_path,
14786                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14787            )
14788            .unwrap();
14789        }
14790        let expected: Value =
14791            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14792        assert_eq!(actual, expected);
14793    }
14794
14795    async fn query_live_roots(
14796        handler: &ControlHandler,
14797        module_ctx: &RouteCtx,
14798    ) -> ModuleControlResponseToModule {
14799        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14800        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14801        let response = handler
14802            .handle_control_frame(module_ctx, frame)
14803            .await
14804            .unwrap()
14805            .pop()
14806            .unwrap();
14807        serde_json::from_slice(&response.body).unwrap()
14808    }
14809
14810    #[tokio::test(start_paused = true)]
14811    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14812        let registry = Arc::new(Registry::default());
14813        let forwarding = Arc::new(ForwardingTable::default());
14814        let handler = ControlHandler::with_forwarding(registry, forwarding);
14815        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14816        hello_via_sink(
14817            &handler,
14818            &target_ctx,
14819            &mut target_rx,
14820            hello_frame("target", PROTOCOL_VERSION, 1),
14821        )
14822        .await;
14823        let root = unique_project_root("live-roots-known");
14824        let path = ProjectRootId::from_path_allowing_missing(root.path())
14825            .unwrap()
14826            .as_path()
14827            .to_path_buf();
14828        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14829        let open_handler = handler.clone();
14830        let opened = tokio::spawn(async move {
14831            open_handler
14832                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14833                .await
14834                .unwrap()
14835        });
14836        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14837            .await
14838            .unwrap()
14839            .unwrap();
14840        handler
14841            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14842            .await
14843            .unwrap();
14844        assert!(opened.await.unwrap().is_empty());
14845        let _ = client_rx.recv().await.unwrap();
14846
14847        let root = unique_project_root("live-roots-pending");
14848        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14849            .unwrap()
14850            .as_path()
14851            .to_path_buf();
14852        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14853        let open_handler = handler.clone();
14854        let pending = tokio::spawn(async move {
14855            open_handler
14856                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14857                .await
14858                .unwrap()
14859        });
14860        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14861            .await
14862            .unwrap()
14863            .unwrap();
14864        let actual = query_live_roots(&handler, &target_ctx).await;
14865        let ModuleControlResponseToModule::LiveRoots {
14866            roots,
14867            unknown_root_bindings,
14868            total_bindings,
14869        } = actual
14870        else {
14871            panic!("expected live roots")
14872        };
14873        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14874        assert_eq!(unknown_root_bindings, 0);
14875        assert_eq!(
14876            roots.len(),
14877            2,
14878            "root-known arm must retain each canonical root"
14879        );
14880        assert_eq!(
14881            total_bindings,
14882            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14883        );
14884        let counts = roots
14885            .iter()
14886            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14887            .collect::<Vec<_>>();
14888        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14889        expected.sort_by(|a, b| a.0.cmp(&b.0));
14890        assert_eq!(
14891            counts, expected,
14892            "roots must sort by path and count pending separately"
14893        );
14894        handler
14895            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14896            .await
14897            .unwrap();
14898        assert!(pending.await.unwrap().is_empty());
14899    }
14900
14901    #[tokio::test(start_paused = true)]
14902    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14903        let forwarding = Arc::new(ForwardingTable::default());
14904        let handler =
14905            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14906        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14907        hello_via_sink(
14908            &handler,
14909            &target_ctx,
14910            &mut target_rx,
14911            hello_frame("target", PROTOCOL_VERSION, 1),
14912        )
14913        .await;
14914        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14915        let pending = forwarding
14916            .begin_route_bind_relay_for_test(
14917                client_ctx.connection_id,
14918                client_ctx.egress.clone(),
14919                2,
14920                "target",
14921            )
14922            .unwrap();
14923        forwarding
14924            .complete_pending_relay(
14925                target_ctx.connection_id,
14926                pending.corr,
14927                RouteBindRelayOutcome::Accepted,
14928            )
14929            .unwrap();
14930        let actual = query_live_roots(&handler, &target_ctx).await;
14931        let ModuleControlResponseToModule::LiveRoots {
14932            roots,
14933            unknown_root_bindings,
14934            total_bindings,
14935        } = actual
14936        else {
14937            panic!("expected live roots")
14938        };
14939        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14940        assert_eq!(
14941            unknown_root_bindings, 1,
14942            "unknown-root arm must not read as no bindings"
14943        );
14944        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14945        assert_eq!(
14946            total_bindings,
14947            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14948        );
14949    }
14950
14951    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14952    /// so the ack has to be on its outbound queue before the module is
14953    /// routable. The connection loop writes a handler's replies only after the
14954    /// handler returns; this test stops in exactly that gap, runs a real
14955    /// route.open from another connection, and only then writes whatever the
14956    /// HELLO handler returned, the way the loop would. If the ack were still a
14957    /// reply, the route.bind request would reach the module first.
14958    #[tokio::test(start_paused = true)]
14959    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14960        let forwarding = Arc::new(ForwardingTable::default());
14961        let handler =
14962            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14963        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14964        let replies = handler
14965            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14966            .await
14967            .unwrap();
14968        let queued_by_hello = module_rx.len();
14969
14970        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14971        let open_handler = handler.clone();
14972        let open = tokio::spawn(async move {
14973            open_handler
14974                .handle_control_frame(
14975                    &client_ctx,
14976                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14977                )
14978                .await
14979                .unwrap()
14980        });
14981        // Let the route.open run until its route.bind is on the module's queue.
14982        let mut spins = 0;
14983        while module_rx.len() == queued_by_hello {
14984            spins += 1;
14985            assert!(spins < 10_000, "route.open never queued a route.bind");
14986            tokio::task::yield_now().await;
14987        }
14988
14989        // Now the connection loop's half: write the HELLO handler's replies.
14990        for reply in replies {
14991            module_ctx.egress.send(reply).await.unwrap();
14992        }
14993
14994        let first = module_rx.recv().await.unwrap().frame;
14995        assert_eq!(
14996            first.header.ty,
14997            FrameType::HelloAck,
14998            "the first frame a registering module reads must be its HELLO_ACK"
14999        );
15000        assert_eq!(first.header.corr, 7);
15001        let second = module_rx.recv().await.unwrap().frame;
15002        assert_eq!(second.header.ty, FrameType::Request);
15003        assert!(
15004            matches!(
15005                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
15006                ModuleControlRequest::RouteBind { .. }
15007            ),
15008            "the route.bind follows the ack"
15009        );
15010        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
15011
15012        handler
15013            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
15014            .await
15015            .unwrap();
15016        assert!(open.await.unwrap().is_empty());
15017        let _ = client_rx.recv().await.unwrap();
15018    }
15019
15020    #[tokio::test(start_paused = true)]
15021    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
15022        let handler = ControlHandler::with_forwarding(
15023            Arc::new(Registry::default()),
15024            Arc::new(ForwardingTable::default()),
15025        );
15026        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
15027        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
15028        hello_via_sink(
15029            &handler,
15030            &first_ctx,
15031            &mut first_rx,
15032            hello_frame("first", PROTOCOL_VERSION, 1),
15033        )
15034        .await;
15035        hello_via_sink(
15036            &handler,
15037            &second_ctx,
15038            &mut second_rx,
15039            hello_frame("second", PROTOCOL_VERSION, 2),
15040        )
15041        .await;
15042        let root = unique_project_root("second-only");
15043        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
15044        let cloned = handler.clone();
15045        let open = tokio::spawn(async move {
15046            cloned
15047                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
15048                .await
15049                .unwrap()
15050        });
15051        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
15052            .await
15053            .unwrap()
15054            .unwrap();
15055        let first = query_live_roots(&handler, &first_ctx).await;
15056        let second = query_live_roots(&handler, &second_ctx).await;
15057        assert!(
15058            matches!(
15059                first,
15060                ModuleControlResponseToModule::LiveRoots {
15061                    total_bindings: 0,
15062                    ..
15063                }
15064            ),
15065            "cross-module scope must not expose another module's roots"
15066        );
15067        assert!(
15068            matches!(
15069                second,
15070                ModuleControlResponseToModule::LiveRoots {
15071                    total_bindings: 1,
15072                    ..
15073                }
15074            ),
15075            "second module must see its pending route"
15076        );
15077        handler
15078            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
15079            .await
15080            .unwrap();
15081        assert!(open.await.unwrap().is_empty());
15082    }
15083
15084    #[tokio::test(start_paused = true)]
15085    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
15086        let handler = ControlHandler::with_forwarding(
15087            Arc::new(Registry::default()),
15088            Arc::new(ForwardingTable::default()),
15089        );
15090        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15091        hello_via_sink(
15092            &handler,
15093            &target_ctx,
15094            &mut target_rx,
15095            hello_frame("target", PROTOCOL_VERSION, 1),
15096        )
15097        .await;
15098        let actual = query_live_roots(&handler, &target_ctx).await;
15099        let ModuleControlResponseToModule::LiveRoots {
15100            roots,
15101            unknown_root_bindings,
15102            total_bindings,
15103        } = actual
15104        else {
15105            panic!("expected live roots")
15106        };
15107        assert!(roots.is_empty());
15108        assert_eq!(unknown_root_bindings, 0);
15109        assert_eq!(total_bindings, 0);
15110        assert_eq!(
15111            total_bindings,
15112            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15113        );
15114    }
15115
15116    /// Read the vendored fed corpus rather than hand-building a package.
15117    ///
15118    /// A hand-built object encodes what the test author believed the carrier
15119    /// emits. These vectors are what it actually emits, and one of them exists
15120    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15121    /// ignores additive unknown fields at the traversal emit terminus."
15122    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15123        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15124            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15125        let text = std::fs::read_to_string(&path)
15126            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15127        let vectors: Vec<(String, Value)> = text
15128            .lines()
15129            .filter(|line| !line.trim().is_empty())
15130            .map(|line| {
15131                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15132                let id = entry["corpus_id"]
15133                    .as_str()
15134                    .expect("every vector carries a corpus_id")
15135                    .to_string();
15136                (id, entry["package"].clone())
15137            })
15138            .collect();
15139        // Pin the count: a corpus that silently shrinks would take its coverage
15140        // with it, and a suite reading N-1 vectors reports the same clean pass
15141        // as one reading N.
15142        assert_eq!(
15143            vectors.len(),
15144            3,
15145            "vendored fed corpus changed size; re-sync from subc-federation"
15146        );
15147
15148        // Pin what makes the corpus DISCRIMINATING, not just present.
15149        //
15150        // The relay test below takes its expected value from the corpus, so the
15151        // corpus supplies the test's power to detect a lossy relay rather than
15152        // its correctness. A relay that dropped unrecognised fields would still
15153        // be caught -- but only by a package carrying fields it does not know.
15154        // Shrink every package to the handful of keys any implementation would
15155        // recognise and the test keeps passing over an input that can no longer
15156        // fail, which is the same clean green as a corpus that shrank away.
15157        //
15158        // So assert the precondition rather than duplicating the packages here:
15159        // at least one vector must carry a field beyond the small common set.
15160        // That is one claim to maintain instead of nine, and it fails loudly if
15161        // a re-sync ever flattens the corpus.
15162        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15163        let richest = vectors
15164            .iter()
15165            .filter_map(|(_, package)| package.as_object())
15166            .map(|object| {
15167                object
15168                    .keys()
15169                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15170                    .count()
15171            })
15172            .max()
15173            .unwrap_or(0);
15174        assert!(
15175            richest >= 2,
15176            "vendored corpus no longer carries a package with unmodelled fields, \
15177             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15178        );
15179
15180        vectors
15181    }
15182
15183    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15184    ///
15185    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15186    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15187    /// three-key object, so a relay that quietly dropped fields it did not
15188    /// recognise would satisfy it. These vectors carry nine keys including ones
15189    /// this crate has no type for, so a typed relay fails here and only here.
15190    #[tokio::test]
15191    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15192        for (corpus_id, package) in fed_admission_facts_vectors() {
15193            let registry = Arc::new(Registry::default());
15194            let forwarding = Arc::new(ForwardingTable::default());
15195            let supervisor = SupervisorHandle::new();
15196            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15197            let handler =
15198                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15199                    .with_supervisor(supervisor)
15200                    .with_admission_facts_config(
15201                        Some("fed".to_string()),
15202                        Some(vec!["target".to_string()]),
15203                    );
15204
15205            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15206            hello_via_sink(
15207                &handler,
15208                &target_ctx,
15209                &mut target_rx,
15210                hello_frame("target", PROTOCOL_VERSION, 1),
15211            )
15212            .await;
15213
15214            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15215            let route_handler = handler.clone();
15216            let expected = package.clone();
15217            let route_task = tokio::spawn(async move {
15218                route_handler
15219                    .handle_control_frame(
15220                        &client_ctx,
15221                        route_open_frame_with_admission_facts(
15222                            20,
15223                            "target",
15224                            unique_project_root("admission-facts"),
15225                            Some(subc_control::ConsumerIdentity {
15226                                module_id: "fed".to_string(),
15227                                launch_nonce: "fed-nonce".to_string(),
15228                            }),
15229                            Some(package),
15230                        ),
15231                    )
15232                    .await
15233                    .unwrap()
15234            });
15235
15236            let bind_frame = target_rx.recv().await.unwrap();
15237            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15238            let ModuleControlRequest::RouteBind {
15239                admission_facts, ..
15240            } = bind
15241            else {
15242                panic!("{corpus_id}: expected route.bind")
15243            };
15244            assert_eq!(
15245                admission_facts,
15246                Some(expected),
15247                "{corpus_id}: relay must not add, drop or reshape any field"
15248            );
15249
15250            handler
15251                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15252                .await
15253                .unwrap();
15254            route_task.await.unwrap();
15255        }
15256    }
15257
15258    #[tokio::test]
15259    async fn route_bind_never_relays_the_openers_build_class() {
15260        let registry = Arc::new(Registry::default());
15261        let forwarding = Arc::new(ForwardingTable::default());
15262        let handler =
15263            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15264        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15265        hello_via_sink(
15266            &handler,
15267            &target_ctx,
15268            &mut target_rx,
15269            hello_frame("target", PROTOCOL_VERSION, 1),
15270        )
15271        .await;
15272
15273        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15274        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15275        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15276            busy_refusals: None,
15277            target: RouteTarget::ToolProvider {
15278                module_id: "target".to_string(),
15279            },
15280            identity,
15281            consumer_identity: None,
15282            consumer_capabilities: None,
15283            role_versions: None,
15284            admission_facts: None,
15285            scope: None,
15286        })
15287        .unwrap();
15288        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15289
15290        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15291        let route_handler = handler.clone();
15292        let route_task = tokio::spawn(async move {
15293            route_handler
15294                .handle_control_frame(&client_ctx, open)
15295                .await
15296                .unwrap()
15297        });
15298        let bind_frame = target_rx.recv().await.unwrap();
15299        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15300        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15301            panic!("expected route.bind")
15302        };
15303        assert_eq!(
15304            identity.build_class, None,
15305            "route.bind carried the build class"
15306        );
15307        assert!(
15308            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15309            "the route.bind bytes still name build_class"
15310        );
15311        handler
15312            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15313            .await
15314            .unwrap();
15315        route_task.await.unwrap();
15316    }
15317
15318    #[tokio::test]
15319    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15320        let registry = Arc::new(Registry::default());
15321        let forwarding = Arc::new(ForwardingTable::default());
15322        let supervisor = SupervisorHandle::new();
15323        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15324        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15325        let handler =
15326            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15327                .with_supervisor(supervisor)
15328                .with_admission_facts_config(
15329                    Some("fed".to_string()),
15330                    Some(vec!["target".to_string()]),
15331                );
15332
15333        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15334        hello_via_sink(
15335            &handler,
15336            &target_ctx,
15337            &mut target_rx,
15338            hello_frame("target", PROTOCOL_VERSION, 1),
15339        )
15340        .await;
15341        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15342        hello_via_sink(
15343            &handler,
15344            &other_ctx,
15345            &mut other_rx,
15346            hello_frame("other", PROTOCOL_VERSION, 2),
15347        )
15348        .await;
15349
15350        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15351        let expected_facts = facts.clone();
15352        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15353        let route_handler = handler.clone();
15354        let route_task = tokio::spawn(async move {
15355            route_handler
15356                .handle_control_frame(
15357                    &client_ctx,
15358                    route_open_frame_with_admission_facts(
15359                        10,
15360                        "target",
15361                        unique_project_root("admission-facts"),
15362                        Some(subc_control::ConsumerIdentity {
15363                            module_id: "fed".to_string(),
15364                            launch_nonce: "fed-nonce".to_string(),
15365                        }),
15366                        Some(facts.clone()),
15367                    ),
15368                )
15369                .await
15370                .unwrap()
15371        });
15372        let bind_frame = target_rx.recv().await.unwrap();
15373        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15374        let ModuleControlRequest::RouteBind {
15375            admission_facts, ..
15376        } = bind
15377        else {
15378            panic!("expected route.bind")
15379        };
15380        assert_eq!(admission_facts, Some(expected_facts));
15381        handler
15382            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15383            .await
15384            .unwrap();
15385        assert!(route_task.await.unwrap().is_empty());
15386        assert!(matches!(
15387            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15388                .unwrap(),
15389            ClientControlResponse::RouteOpen { .. }
15390        ));
15391
15392        let direct = handler
15393            .handle_control_frame(
15394                &route_ctx(ConnectionId::new(73)).0,
15395                route_open_frame_with_admission_facts(
15396                    11,
15397                    "target",
15398                    unique_project_root("admission-facts"),
15399                    None,
15400                    Some(json!({"x": 1})),
15401                ),
15402            )
15403            .await
15404            .unwrap();
15405        assert_eq!(
15406            parse_error(&direct[0])["code"],
15407            "admission_facts_not_permitted"
15408        );
15409
15410        let different_reserved = handler
15411            .handle_control_frame(
15412                &route_ctx(ConnectionId::new(77)).0,
15413                route_open_frame_with_admission_facts(
15414                    15,
15415                    "target",
15416                    unique_project_root("admission-facts"),
15417                    Some(subc_control::ConsumerIdentity {
15418                        module_id: "other".to_string(),
15419                        launch_nonce: "other-nonce".to_string(),
15420                    }),
15421                    Some(json!({"x": 1})),
15422                ),
15423            )
15424            .await
15425            .unwrap();
15426        assert_eq!(
15427            parse_error(&different_reserved[0])["code"],
15428            "admission_facts_not_permitted"
15429        );
15430
15431        let other_target = handler
15432            .handle_control_frame(
15433                &route_ctx(ConnectionId::new(74)).0,
15434                route_open_frame_with_admission_facts(
15435                    12,
15436                    "other",
15437                    unique_project_root("admission-facts"),
15438                    Some(subc_control::ConsumerIdentity {
15439                        module_id: "fed".to_string(),
15440                        launch_nonce: "fed-nonce".to_string(),
15441                    }),
15442                    Some(json!({"x": 1})),
15443                ),
15444            )
15445            .await
15446            .unwrap();
15447        assert_eq!(
15448            parse_error(&other_target[0])["code"],
15449            "admission_facts_target_not_allowed"
15450        );
15451
15452        let nonexistent = handler
15453            .handle_control_frame(
15454                &route_ctx(ConnectionId::new(75)).0,
15455                route_open_frame_with_admission_facts(
15456                    13,
15457                    "missing",
15458                    unique_project_root("admission-facts"),
15459                    None,
15460                    Some(json!({"x": 1})),
15461                ),
15462            )
15463            .await
15464            .unwrap();
15465        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15466
15467        let described = handler
15468            .handle_control_frame(
15469                &route_ctx(ConnectionId::new(76)).0,
15470                Frame::build(
15471                    FrameType::Request,
15472                    control_flags(),
15473                    0,
15474                    0,
15475                    14,
15476                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15477                )
15478                .unwrap(),
15479            )
15480            .await
15481            .unwrap();
15482        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15483            serde_json::from_slice(&described[0].body).unwrap()
15484        else {
15485            panic!("expected server.describe response")
15486        };
15487        assert!(capabilities
15488            .iter()
15489            .any(|cap| cap == "admission_facts_relay_v1"));
15490    }
15491
15492    #[tokio::test]
15493    async fn admission_facts_without_configured_carrier_are_rejected() {
15494        let registry = Arc::new(Registry::default());
15495        let forwarding = Arc::new(ForwardingTable::default());
15496        let handler = ControlHandler::with_forwarding(registry, forwarding);
15497        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15498        hello_via_sink(
15499            &handler,
15500            &target_ctx,
15501            &mut target_rx,
15502            hello_frame("target", PROTOCOL_VERSION, 1),
15503        )
15504        .await;
15505
15506        let responses = handler
15507            .handle_control_frame(
15508                &route_ctx(ConnectionId::new(79)).0,
15509                route_open_frame_with_admission_facts(
15510                    16,
15511                    "target",
15512                    unique_project_root("admission-facts"),
15513                    None,
15514                    Some(json!({"x": 1})),
15515                ),
15516            )
15517            .await
15518            .unwrap();
15519        assert_eq!(
15520            parse_error(&responses[0])["code"],
15521            "admission_facts_not_permitted"
15522        );
15523    }
15524
15525    #[tokio::test]
15526    async fn route_open_relays_consumer_capabilities_verbatim() {
15527        let registry = Arc::new(Registry::default());
15528        let forwarding = Arc::new(ForwardingTable::default());
15529        let handler =
15530            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15531        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15532        hello_via_sink(
15533            &handler,
15534            &module_ctx,
15535            &mut module_rx,
15536            hello_frame("aft", PROTOCOL_VERSION, 7),
15537        )
15538        .await;
15539
15540        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15541        let expected_for_request = expected.clone();
15542        let project_root = unique_project_root("consumer-capabilities-present");
15543        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15544        let route_handler = handler.clone();
15545        let route_task = tokio::spawn(async move {
15546            route_handler
15547                .handle_control_frame(
15548                    &client_ctx,
15549                    route_open_frame_with_consumer_capabilities(
15550                        401,
15551                        "aft",
15552                        project_root,
15553                        Some(expected_for_request),
15554                    ),
15555                )
15556                .await
15557                .unwrap()
15558        });
15559        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15560            .await
15561            .unwrap()
15562            .unwrap();
15563        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15564        let ModuleControlRequest::RouteBind {
15565            consumer_capabilities,
15566            ..
15567        } = bind
15568        else {
15569            panic!("expected route.bind request, got {bind:?}");
15570        };
15571        assert_eq!(consumer_capabilities, Some(expected.clone()));
15572
15573        handler
15574            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15575            .await
15576            .unwrap();
15577        let route_response = route_task.await.unwrap();
15578        assert!(route_response.is_empty());
15579        let published = client_rx.recv().await.unwrap();
15580        assert!(matches!(
15581            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15582            ClientControlResponse::RouteOpen { .. }
15583        ));
15584    }
15585
15586    #[tokio::test]
15587    async fn route_open_without_consumer_capabilities_relays_none() {
15588        let registry = Arc::new(Registry::default());
15589        let forwarding = Arc::new(ForwardingTable::default());
15590        let handler =
15591            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15592        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15593        hello_via_sink(
15594            &handler,
15595            &module_ctx,
15596            &mut module_rx,
15597            hello_frame("aft", PROTOCOL_VERSION, 7),
15598        )
15599        .await;
15600
15601        let project_root = unique_project_root("consumer-capabilities-absent");
15602        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15603        let route_handler = handler.clone();
15604        let route_task = tokio::spawn(async move {
15605            route_handler
15606                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15607                .await
15608                .unwrap()
15609        });
15610        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15611            .await
15612            .unwrap()
15613            .unwrap();
15614        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15615        let ModuleControlRequest::RouteBind {
15616            consumer_capabilities,
15617            ..
15618        } = bind
15619        else {
15620            panic!("expected route.bind request, got {bind:?}");
15621        };
15622        assert_eq!(consumer_capabilities, None);
15623
15624        handler
15625            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15626            .await
15627            .unwrap();
15628        let route_response = route_task.await.unwrap();
15629        assert!(route_response.is_empty());
15630        let published = client_rx.recv().await.unwrap();
15631        assert!(matches!(
15632            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15633            ClientControlResponse::RouteOpen { .. }
15634        ));
15635    }
15636
15637    /// Opens a route to a freshly registered `aft` with `sent` as the
15638    /// route.open's role_versions, acks the bind, and returns the role_versions
15639    /// the module's bind carried.
15640    async fn bind_role_versions_for(
15641        sent: Option<BTreeMap<String, String>>,
15642        connection: u64,
15643    ) -> Option<BTreeMap<String, String>> {
15644        let registry = Arc::new(Registry::default());
15645        let forwarding = Arc::new(ForwardingTable::default());
15646        let handler =
15647            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15648        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15649        hello_via_sink(
15650            &handler,
15651            &module_ctx,
15652            &mut module_rx,
15653            hello_frame("aft", PROTOCOL_VERSION, 7),
15654        )
15655        .await;
15656        let project_root = unique_project_root("role-versions");
15657        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15658        let route_handler = handler.clone();
15659        let route_task = tokio::spawn(async move {
15660            route_handler
15661                .handle_control_frame(
15662                    &client_ctx,
15663                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15664                )
15665                .await
15666                .unwrap()
15667        });
15668        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15669            .await
15670            .expect("a well-formed route.open reaches the module as a bind")
15671            .unwrap();
15672        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15673        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15674            panic!("expected route.bind request, got {bind:?}");
15675        };
15676        handler
15677            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15678            .await
15679            .unwrap();
15680        assert!(route_task.await.unwrap().is_empty());
15681        let published = client_rx.recv().await.unwrap();
15682        assert!(matches!(
15683            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15684            ClientControlResponse::RouteOpen { .. }
15685        ));
15686        role_versions
15687    }
15688
15689    #[tokio::test]
15690    async fn route_open_relays_role_versions_verbatim() {
15691        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15692        assert_eq!(
15693            bind_role_versions_for(Some(sent.clone()), 141).await,
15694            Some(sent)
15695        );
15696    }
15697
15698    /// An empty map declares nothing, so the provider sees no field rather
15699    /// than an empty object it would have to treat as a second "none".
15700    #[tokio::test]
15701    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15702        assert_eq!(bind_role_versions_for(None, 143).await, None);
15703        assert_eq!(
15704            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15705            None
15706        );
15707    }
15708
15709    #[tokio::test]
15710    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15711        let registry = Arc::new(Registry::default());
15712        let forwarding = Arc::new(ForwardingTable::default());
15713        let handler =
15714            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15715        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15716        hello_via_sink(
15717            &handler,
15718            &module_ctx,
15719            &mut module_rx,
15720            hello_frame("aft", PROTOCOL_VERSION, 7),
15721        )
15722        .await;
15723
15724        let nine: BTreeMap<String, String> = (0..9)
15725            .map(|index| (format!("role-{index}"), "v1".to_string()))
15726            .collect();
15727        for (label, malformed) in [
15728            (
15729                "invalid role name",
15730                role_versions(&[("Tool_Provider", "v1")]),
15731            ),
15732            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15733            ("nine entries", nine),
15734        ] {
15735            // A refused open answers at once; one that reached the module
15736            // would wait for its bind ack and trip this timeout.
15737            let responses = tokio::time::timeout(
15738                Duration::from_secs(1),
15739                handler.handle_control_frame(
15740                    &route_ctx(ConnectionId::new(148)).0,
15741                    route_open_frame_with_role_versions(
15742                        404,
15743                        "aft",
15744                        unique_project_root("role-versions-malformed"),
15745                        Some(malformed),
15746                    ),
15747                ),
15748            )
15749            .await
15750            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15751            .unwrap();
15752            assert_eq!(responses.len(), 1, "{label}");
15753            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15754            let error = parse_error(&responses[0]);
15755            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15756            assert_eq!(
15757                error["detail"]["field"], "role_versions",
15758                "{label}: {error}"
15759            );
15760            assert!(
15761                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15762                "{label}: a malformed declaration is terminal"
15763            );
15764            assert!(
15765                module_rx.try_recv().is_err(),
15766                "{label}: the module must never see a bind"
15767            );
15768        }
15769    }
15770
15771    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15772    /// consumer can tell this daemon forwards the field from one that would
15773    /// drop it.
15774    #[tokio::test]
15775    async fn route_role_versions_capability_is_advertised() {
15776        let handler = ControlHandler::new(Arc::new(Registry::default()));
15777        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15778        let ack = hello_via_sink(
15779            &handler,
15780            &ctx,
15781            &mut rx,
15782            hello_frame("m", PROTOCOL_VERSION, 1),
15783        )
15784        .await;
15785        let ack = parse_ack(&ack);
15786        assert!(
15787            ack.subc_capabilities
15788                .iter()
15789                .any(|c| c == "route-role-versions/v1"),
15790            "{:?}",
15791            ack.subc_capabilities
15792        );
15793
15794        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15795        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15796        let reply = handler
15797            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15798            .await
15799            .unwrap()
15800            .pop()
15801            .unwrap();
15802        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15803            serde_json::from_slice(&reply.body).unwrap()
15804        else {
15805            panic!("not a server.describe reply");
15806        };
15807        assert!(
15808            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15809            "{capabilities:?}"
15810        );
15811    }
15812
15813    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15814    /// catalog entry without `events` (the module declares none) from a daemon
15815    /// that never reports declared events.
15816    #[tokio::test]
15817    async fn catalog_events_capability_is_advertised() {
15818        let handler = ControlHandler::new(Arc::new(Registry::default()));
15819        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15820        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15821        let reply = handler
15822            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
15823            .await
15824            .unwrap()
15825            .pop()
15826            .unwrap();
15827        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15828            serde_json::from_slice(&reply.body).unwrap()
15829        else {
15830            panic!("not a server.describe reply");
15831        };
15832        assert!(
15833            capabilities
15834                .iter()
15835                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
15836            "{capabilities:?}"
15837        );
15838    }
15839
15840    #[tokio::test]
15841    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15842        let handler = ControlHandler::new(Arc::new(Registry::default()));
15843        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15844        let ack = hello_via_sink(
15845            &handler,
15846            &module,
15847            &mut module_rx,
15848            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15849        )
15850        .await;
15851        let ack = parse_ack(&ack);
15852        assert!(
15853            ack.subc_capabilities
15854                .iter()
15855                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15856            "{:?}",
15857            ack.subc_capabilities
15858        );
15859        assert!(ack
15860            .subc_capabilities
15861            .iter()
15862            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15863
15864        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15865        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15866        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15867        let reply = handler
15868            .handle_control_frame(&client, frame)
15869            .await
15870            .unwrap()
15871            .pop()
15872            .unwrap();
15873        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15874            serde_json::from_slice(&reply.body).unwrap()
15875        else {
15876            panic!("not a server.describe reply");
15877        };
15878        assert!(
15879            capabilities
15880                .iter()
15881                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15882            "{capabilities:?}"
15883        );
15884        assert!(capabilities
15885            .iter()
15886            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15887    }
15888
15889    #[tokio::test]
15890    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15891        let handler = ControlHandler::new(Arc::new(Registry::default()));
15892        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15893        let ack = hello_via_sink(
15894            &handler,
15895            &module,
15896            &mut rx,
15897            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15898        )
15899        .await;
15900        assert!(parse_ack(&ack)
15901            .subc_capabilities
15902            .iter()
15903            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15904        assert!(parse_ack(&ack)
15905            .subc_capabilities
15906            .iter()
15907            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15908        let (client, _rx) = route_ctx(ConnectionId::new(157));
15909        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15910        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15911        let reply = handler
15912            .handle_control_frame(&client, frame)
15913            .await
15914            .unwrap()
15915            .pop()
15916            .unwrap();
15917        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15918            serde_json::from_slice(&reply.body).unwrap()
15919        else {
15920            panic!("server.describe reply")
15921        };
15922        assert!(capabilities
15923            .iter()
15924            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15925        assert!(capabilities
15926            .iter()
15927            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15928    }
15929
15930    #[tokio::test]
15931    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15932        let handler = ControlHandler::new(Arc::new(Registry::default()));
15933        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15934        let ack = hello_via_sink(
15935            &handler,
15936            &module,
15937            &mut rx,
15938            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15939        )
15940        .await;
15941        assert!(parse_ack(&ack)
15942            .subc_capabilities
15943            .iter()
15944            .any(|cap| cap == "scope-workdir/v1"));
15945        let (client, _rx) = route_ctx(ConnectionId::new(159));
15946        let frame = Frame::build(
15947            FrameType::Request,
15948            control_flags(),
15949            0,
15950            0,
15951            5,
15952            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15953        )
15954        .unwrap();
15955        let reply = handler
15956            .handle_control_frame(&client, frame)
15957            .await
15958            .unwrap()
15959            .remove(0);
15960        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15961            serde_json::from_slice(&reply.body).unwrap()
15962        else {
15963            panic!("server.describe reply")
15964        };
15965        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15966    }
15967
15968    #[tokio::test]
15969    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15970        let handler = ControlHandler::new(Arc::new(Registry::default()));
15971        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15972        let ack = hello_via_sink(
15973            &handler,
15974            &module,
15975            &mut rx,
15976            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15977        )
15978        .await;
15979        assert!(parse_ack(&ack)
15980            .subc_capabilities
15981            .iter()
15982            .any(|cap| cap == "worker-runs/v1"));
15983        let (client, _rx) = route_ctx(ConnectionId::new(161));
15984        let frame = Frame::build(
15985            FrameType::Request,
15986            control_flags(),
15987            0,
15988            0,
15989            5,
15990            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15991        )
15992        .unwrap();
15993        let reply = handler
15994            .handle_control_frame(&client, frame)
15995            .await
15996            .unwrap()
15997            .remove(0);
15998        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15999            serde_json::from_slice(&reply.body).unwrap()
16000        else {
16001            panic!("server.describe reply")
16002        };
16003        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
16004    }
16005
16006    #[tokio::test]
16007    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
16008        let handler = ControlHandler::new(Arc::new(Registry::default()));
16009        let (module, mut rx) = route_ctx(ConnectionId::new(154));
16010        let ack = hello_via_sink(
16011            &handler,
16012            &module,
16013            &mut rx,
16014            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
16015        )
16016        .await;
16017        assert!(parse_ack(&ack)
16018            .subc_capabilities
16019            .iter()
16020            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16021        let (client, _rx) = route_ctx(ConnectionId::new(155));
16022        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16023        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16024        let reply = handler
16025            .handle_control_frame(&client, frame)
16026            .await
16027            .unwrap()
16028            .pop()
16029            .unwrap();
16030        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16031            serde_json::from_slice(&reply.body).unwrap()
16032        else {
16033            panic!("not a server.describe reply")
16034        };
16035        assert!(capabilities
16036            .iter()
16037            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16038    }
16039
16040    #[tokio::test]
16041    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
16042        let registry = Arc::new(Registry::default());
16043        let forwarding = Arc::new(ForwardingTable::default());
16044        let handler =
16045            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
16046                .with_health_probe_timeout(Duration::from_secs(5));
16047        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
16048        hello_via_sink(
16049            &handler,
16050            &module_ctx,
16051            &mut module_rx,
16052            non_routable_hello_frame_with_control_ops(
16053                "mcp",
16054                300,
16055                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
16056            ),
16057        )
16058        .await;
16059        assert!(registry
16060            .get_module("mcp")
16061            .unwrap()
16062            .unwrap()
16063            .manifest
16064            .provides
16065            .is_empty());
16066
16067        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
16068        let route_response = handler
16069            .handle_control_frame(
16070                &route_client_ctx,
16071                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
16072            )
16073            .await
16074            .unwrap();
16075        assert_eq!(route_response[0].header.ty, FrameType::Error);
16076        assert_eq!(
16077            parse_error(&route_response[0])["code"],
16078            "target_unavailable"
16079        );
16080        assert!(parse_error(&route_response[0])["message"]
16081            .as_str()
16082            .unwrap()
16083            .contains("does not provide the requested target"));
16084        assert!(module_rx.try_recv().is_err());
16085
16086        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16087        let health_handler = handler.clone();
16088        let health_task = tokio::spawn(async move {
16089            health_handler
16090                .handle_control_frame(
16091                    &health_client_ctx,
16092                    supervisor_health_probe_frame(302, "mcp"),
16093                )
16094                .await
16095                .unwrap()
16096        });
16097        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16098            .await
16099            .unwrap()
16100            .unwrap();
16101        assert_eq!(
16102            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16103            ModuleControlRequest::HealthCheck {}
16104        );
16105        handler
16106            .handle_control_frame(
16107                &module_ctx,
16108                health_response(health_frame.header.corr, HealthStatus::Ok),
16109            )
16110            .await
16111            .unwrap();
16112        let health_response = health_task.await.unwrap();
16113        assert_eq!(health_response[0].header.ty, FrameType::Response);
16114        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16115            ClientControlResponse::SupervisorHealthProbe {
16116                module_id, status, ..
16117            } => {
16118                assert_eq!(module_id, "mcp");
16119                assert_eq!(status, HealthStatus::Ok);
16120            }
16121            other => panic!("unexpected health response: {other:?}"),
16122        }
16123
16124        // Exercise the forwarding cleanup path directly while leaving the registry
16125        // advertisement in place. If cleanup leaves a stale control sink behind,
16126        // the next probe will enqueue onto it and wait for the long probe timeout
16127        // instead of returning an immediate no-connection error.
16128        forwarding
16129            .cleanup_connection(module_ctx.connection_id)
16130            .unwrap();
16131        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16132        let cleanup_response = tokio::time::timeout(
16133            Duration::from_millis(200),
16134            handler.handle_control_frame(
16135                &cleanup_probe_ctx,
16136                supervisor_health_probe_frame(303, "mcp"),
16137            ),
16138        )
16139        .await
16140        .expect("probe should fail immediately when the control lane is gone")
16141        .unwrap();
16142        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16143        assert_eq!(
16144            parse_error(&cleanup_response[0])["code"],
16145            "target_unavailable"
16146        );
16147        assert!(parse_error(&cleanup_response[0])["message"]
16148            .as_str()
16149            .unwrap()
16150            .contains("no module connection"));
16151
16152        handler
16153            .cleanup_connection(module_ctx.connection_id)
16154            .unwrap();
16155    }
16156
16157    #[tokio::test]
16158    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16159        let registry = Arc::new(Registry::default());
16160        let supervisor_handle = SupervisorHandle::new();
16161        let supervisor =
16162            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16163                .with_handle(supervisor_handle.clone())
16164                .with_connection_file_path(
16165                    std::env::temp_dir()
16166                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16167                );
16168        let module = supervisor
16169            .supervise_configured(
16170                ModuleSpec {
16171                    script: None,
16172                    carry_containment: false,
16173                    module_id: "warming".to_string(),
16174                    program: fake_aft_stub_path(),
16175                    args: Vec::new(),
16176                    env: Vec::new(),
16177                    reserved: false,
16178                    reserved_prefixes: Vec::new(),
16179                    protocol: ModuleProtocol::Subc,
16180                    overlap: Default::default(),
16181                },
16182                true,
16183            )
16184            .unwrap();
16185        assert_eq!(module.state().unwrap(), ModuleState::Running);
16186
16187        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16188        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16189        let response = handler
16190            .handle_control_frame(
16191                &ctx,
16192                route_open_frame(304, "warming", unique_project_root("warming")),
16193            )
16194            .await
16195            .unwrap();
16196        module.stop().await.unwrap();
16197
16198        assert_eq!(response[0].header.ty, FrameType::Error);
16199        let error = parse_error(&response[0]);
16200        assert_eq!(error["code"], "module_warming");
16201        assert!(error["message"]
16202            .as_str()
16203            .unwrap()
16204            .contains("state=running, enabled=true, live=false"));
16205    }
16206
16207    #[test]
16208    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16209        let handler = ControlHandler::new(Arc::new(Registry::default()));
16210        let capture = EventCapture::default();
16211        let _subscriber =
16212            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16213        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16214        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16215        let pending = (0..limit).collect::<Vec<_>>();
16216        let response = handler
16217            .route_open_capacity_refusal(
16218                &ctx,
16219                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16220                "busy",
16221                pending.len(),
16222                limit,
16223            )
16224            .unwrap();
16225        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16226        let event = capture
16227            .events()
16228            .into_iter()
16229            .find(|event| {
16230                event.target == "control"
16231                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16232            })
16233            .expect("connection admission refusal event");
16234        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16235        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16236        // Refused before `handle_route_open` parses the request, so the caller
16237        // fields are read from the frame itself.
16238        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16239        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16240    }
16241
16242    #[test]
16243    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16244        let handler = ControlHandler::new(Arc::new(Registry::default()));
16245        let capture = EventCapture::default();
16246        let _subscriber =
16247            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16248        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16249        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16250        let guards = (0..limit)
16251            .map(|_| {
16252                handler
16253                    .route_bind_concurrency
16254                    .try_admit("busy", limit)
16255                    .unwrap()
16256            })
16257            .collect::<Vec<_>>();
16258        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16259            Err(in_flight) => in_flight,
16260            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16261        };
16262        let response = handler
16263            .route_open_target_capacity_refusal(
16264                &ctx,
16265                &RouteOpenCaller::unknown(),
16266                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16267                "busy",
16268                in_flight,
16269            )
16270            .unwrap();
16271        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16272        let event = capture
16273            .events()
16274            .into_iter()
16275            .find(|event| {
16276                event.target == "control"
16277                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16278            })
16279            .expect("target admission refusal event");
16280        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16281        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16282        drop(guards);
16283    }
16284
16285    #[cfg(unix)]
16286    #[tokio::test(start_paused = true)]
16287    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16288        let registry = Arc::new(Registry::default());
16289        let handle = SupervisorHandle::new();
16290        let supervisor =
16291            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16292                .with_handle(handle.clone());
16293        let module = supervisor
16294            .spawn(crate::ModuleSpec {
16295                script: None,
16296                carry_containment: false,
16297                module_id: "retry-list".into(),
16298                program: PathBuf::from("/bin/sh"),
16299                args: vec!["-c".into(), "exit 17".into()],
16300                env: vec![],
16301                reserved: false,
16302                reserved_prefixes: vec![],
16303                protocol: ModuleProtocol::None,
16304                overlap: Default::default(),
16305            })
16306            .unwrap();
16307        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16308        while module.state().unwrap() != crate::ModuleState::Failed {
16309            assert!(
16310                std::time::Instant::now() < deadline,
16311                "waiting for budget failure"
16312            );
16313            tokio::task::yield_now().await;
16314        }
16315        let handler = ControlHandler::new(registry).with_supervisor(handle);
16316        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16317        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16318        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16319        assert_eq!(body["modules"][0]["state"], "failed");
16320        let retry = body["modules"][0]["next_retry_at_ms"]
16321            .as_u64()
16322            .expect("scheduled retry on the wire");
16323        let now = std::time::SystemTime::now()
16324            .duration_since(std::time::UNIX_EPOCH)
16325            .unwrap()
16326            .as_millis() as u64;
16327        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16328        module.set_enabled(false).await.unwrap();
16329        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16330        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16331        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16332        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16333    }
16334
16335    #[tokio::test]
16336    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16337        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16338        let supervisor =
16339            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16340        let module = supervisor
16341            .spawn(crate::ModuleSpec {
16342                script: None,
16343                carry_containment: false,
16344                module_id: "pid-read-budget".into(),
16345                program: std::env::current_exe().unwrap(),
16346                args: vec![
16347                    "--exact".into(),
16348                    "control::tests::pid_resource_read_fixture".into(),
16349                ],
16350                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16351                    .into_iter()
16352                    .map(|key| (key.into(), dir.display().to_string()))
16353                    .chain(std::iter::once((
16354                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16355                        "1".into(),
16356                    )))
16357                    .collect(),
16358                reserved: false,
16359                reserved_prefixes: Vec::new(),
16360                protocol: ModuleProtocol::None,
16361                overlap: Default::default(),
16362            })
16363            .unwrap();
16364        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16365        while !matches!(
16366            module.child_resource_usage(),
16367            subc_control::ChildResourceUsage::Measured(_)
16368        ) {
16369            assert!(
16370                tokio::time::Instant::now() < ready_deadline,
16371                "fixture process was not measurable"
16372            );
16373            tokio::time::sleep(Duration::from_millis(10)).await;
16374        }
16375        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16376        let reading = {
16377            let _guard = crate::subtree_resources::fault_read_guard().await;
16378            crate::subtree_resources::read_process(module.clone()).await
16379        };
16380        stop_resource_fixture(&module, &dir).await;
16381        assert!(
16382            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16383            "{reading:?}"
16384        );
16385    }
16386
16387    #[test]
16388    fn pid_resource_read_fixture() {
16389        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16390            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16391            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16392            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16393                std::thread::sleep(Duration::from_millis(5));
16394            }
16395            std::fs::write(dir.join("module-stopped"), "").unwrap();
16396        }
16397    }
16398
16399    async fn stop_resource_fixture(
16400        module: &crate::supervise::SupervisedModule,
16401        dir: &std::path::Path,
16402    ) {
16403        let stopping = module.stop();
16404        tokio::pin!(stopping);
16405        tokio::select! {
16406            result = &mut stopping => result.unwrap(),
16407            () = async {
16408                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16409                    tokio::time::sleep(Duration::from_millis(5)).await;
16410                }
16411                std::fs::write(dir.join("stop-module"), "").unwrap();
16412            } => stopping.await.unwrap(),
16413        }
16414        #[cfg(windows)]
16415        assert!(
16416            dir.join("module-stopped").exists(),
16417            "the resource fixture must exit cooperatively, not wait for the drain kill"
16418        );
16419        assert_eq!(
16420            module.state().unwrap(),
16421            crate::supervise::ModuleState::Stopped
16422        );
16423    }
16424
16425    #[tokio::test]
16426    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16427        let registry = Arc::new(Registry::default());
16428        let handle = SupervisorHandle::new();
16429        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16430            .with_handle(handle.clone());
16431        supervisor
16432            .supervise_configured(
16433                crate::ModuleSpec {
16434                    script: None,
16435                    module_id: "disabled-resource-reading".into(),
16436                    program: std::env::current_exe().unwrap(),
16437                    args: Vec::new(),
16438                    env: Vec::new(),
16439                    reserved: false,
16440                    reserved_prefixes: Vec::new(),
16441                    protocol: ModuleProtocol::None,
16442                    overlap: Default::default(),
16443                    carry_containment: false,
16444                },
16445                false,
16446            )
16447            .unwrap();
16448        let handler = ControlHandler::new(registry).with_supervisor(handle);
16449        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16450        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16451        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16452        assert!(body["modules"][0].get("tree").is_none());
16453        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16454    }
16455
16456    #[tokio::test]
16457    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16458        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16459        let registry = Arc::new(Registry::default());
16460        let handle = SupervisorHandle::new();
16461        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16462            .with_handle(handle.clone());
16463        let module = supervisor
16464            .spawn(crate::ModuleSpec {
16465                script: None,
16466                carry_containment: false,
16467                module_id: "list-process-priority".into(),
16468                program: std::env::current_exe().unwrap(),
16469                args: vec![
16470                    "--exact".into(),
16471                    "control::tests::pid_resource_read_fixture".into(),
16472                ],
16473                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16474                    .into_iter()
16475                    .map(|key| (key.into(), dir.display().to_string()))
16476                    .chain(std::iter::once((
16477                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16478                        "1".into(),
16479                    )))
16480                    .collect(),
16481                reserved: false,
16482                reserved_prefixes: Vec::new(),
16483                protocol: ModuleProtocol::None,
16484                overlap: Default::default(),
16485            })
16486            .unwrap();
16487        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16488        loop {
16489            let image = module.running_image_agreement().await;
16490            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16491                break;
16492            }
16493            assert!(
16494                tokio::time::Instant::now() < ready_deadline,
16495                "the fixture process never became observable: {image:?}"
16496            );
16497            tokio::time::sleep(Duration::from_millis(10)).await;
16498        }
16499        let guard = crate::subtree_resources::fault_read_guard().await;
16500        let (target, release, _) = crate::subtree_resources::held();
16501        module.set_subtree_target_for_test(target);
16502        let handler = ControlHandler::new(registry).with_supervisor(handle);
16503        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16504        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16505        drop(release);
16506        drop(guard);
16507        stop_resource_fixture(&module, &dir).await;
16508        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16509        assert_eq!(
16510            body["modules"][0]["resources"]["status"], "measured",
16511            "the optional tree timeout must not discard the process reading: {body}"
16512        );
16513        assert!(body["modules"][0].get("tree").is_none());
16514        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16515        assert_eq!(
16516            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16517            "the tree timeout must not hide a completed image observation"
16518        );
16519    }
16520
16521    #[cfg(any(target_os = "linux", target_os = "macos"))]
16522    #[tokio::test]
16523    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16524        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16525            .with_daemon_provenance(
16526                std::process::id(),
16527                0,
16528                Some(std::env::current_exe().unwrap()),
16529                None,
16530                None,
16531            );
16532        let (probe, release, began) = ExecutableIdentityProbe::held();
16533        handler.daemon_provenance.probe = probe;
16534        let observe = |handler: ControlHandler, corr| {
16535            tokio::spawn(async move {
16536                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16537                let frame =
16538                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16539                        .unwrap();
16540                handler
16541                    .handle_supervisor_provenance(&ctx, frame, None)
16542                    .await
16543                    .unwrap()
16544            })
16545        };
16546        let explicit = observe(handler.clone(), 114);
16547        began.await.unwrap();
16548        let concurrent = observe(handler.clone(), 115);
16549        // Keep explicit provenance waiting on its first image observation beyond
16550        // the list deadline; release it only after the concurrent list replies.
16551        tokio::time::sleep(Duration::from_millis(300)).await;
16552        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16553        let list = tokio::time::timeout(
16554            Duration::from_secs(1),
16555            handler.handle_supervisor_list(frame),
16556        )
16557        .await;
16558        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16559        drop(release);
16560        let replies = explicit.await.unwrap();
16561        let concurrent_replies = concurrent.await.unwrap();
16562        assert!(
16563            explicit_was_pending,
16564            "explicit provenance must await the full observation"
16565        );
16566        let list = list
16567            .expect("a concurrent explicit probe must not stall list")
16568            .unwrap();
16569        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16570        assert_eq!(list_body["op"], "supervisor.list");
16571        for replies in [replies, concurrent_replies] {
16572            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16573            assert_eq!(
16574                body["daemon"]["daemon_observed"]["running_image"]["status"],
16575                "match"
16576            );
16577        }
16578    }
16579
16580    #[tokio::test]
16581    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16582        let registry = Arc::new(Registry::default());
16583        let handle = SupervisorHandle::new();
16584        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16585            .with_handle(handle.clone());
16586        let module = supervisor
16587            .supervise_configured(
16588                crate::ModuleSpec {
16589                    script: None,
16590                    carry_containment: false,
16591                    module_id: "memory-read".into(),
16592                    program: PathBuf::from("disabled-module"),
16593                    args: Vec::new(),
16594                    env: Vec::new(),
16595                    reserved: false,
16596                    reserved_prefixes: Vec::new(),
16597                    protocol: ModuleProtocol::Subc,
16598                    overlap: Default::default(),
16599                },
16600                true,
16601            )
16602            .unwrap();
16603        let _guard = crate::subtree_resources::fault_read_guard().await;
16604        let (target, release, began) = crate::subtree_resources::held();
16605        // Optional list work may be skipped when its deadline is already spent.
16606        // Establish the stalled fixture before asking the list to observe it.
16607        let stalled_target = target.clone();
16608        let stalled = tokio::task::spawn_blocking(move || {
16609            stalled_target.tree(&subc_os::ProcessTable::default())
16610        });
16611        began.await.unwrap();
16612        module.set_subtree_target_for_test(target);
16613        let handler = ControlHandler::new(registry).with_supervisor(handle);
16614        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16615        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16616        let replies = handler
16617            .handle_client_control_request(
16618                &ctx,
16619                frame,
16620                ClientControlRequest::SupervisorList {},
16621                &mut None,
16622            )
16623            .await
16624            .unwrap();
16625        assert!(
16626            replies.is_empty(),
16627            "list reply must be detached from the connection reader"
16628        );
16629        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16630        let replies = handler
16631            .handle_client_control_request(
16632                &ctx,
16633                frame,
16634                ClientControlRequest::SupervisorSpawnSnapshot {},
16635                &mut None,
16636            )
16637            .await
16638            .unwrap();
16639        assert_eq!(
16640            replies.len(),
16641            1,
16642            "another request must complete while the subtree read stalls"
16643        );
16644        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16645            .await
16646            .unwrap()
16647            .unwrap();
16648        release.send(()).unwrap();
16649        drop(release);
16650        stalled.await.unwrap();
16651        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16652        assert!(
16653            body["modules"][0].get("tree").is_none(),
16654            "an unknown tree reading must be omitted after the bounded read expires"
16655        );
16656        // Lists export completed work rather than measuring synchronously.
16657        // Complete a refresh after the fixture is released before asserting
16658        // that a later list contains its measured tree.
16659        handler
16660            .resource_tracker
16661            .read(handler.supervisor.list(), false, "released_tree_fixture")
16662            .await;
16663        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16664        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16665        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16666        assert_eq!(
16667            body["modules"][0]["tree"]["source"], "process_tree",
16668            "the next request must export the completed refresh"
16669        );
16670        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16671    }
16672
16673    #[tokio::test]
16674    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16675        use subc_control::{
16676            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16677            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16678            TreeReading, TreeSource,
16679        };
16680        let registry = Arc::new(Registry::default());
16681        let handle = SupervisorHandle::new();
16682        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16683            .with_handle(handle.clone());
16684        supervisor
16685            .supervise_configured(
16686                crate::ModuleSpec {
16687                    script: None,
16688                    carry_containment: false,
16689                    module_id: "budget-worker".into(),
16690                    program: PathBuf::from("disabled-module"),
16691                    args: Vec::new(),
16692                    env: Vec::new(),
16693                    reserved: false,
16694                    reserved_prefixes: Vec::new(),
16695                    protocol: ModuleProtocol::Subc,
16696                    overlap: Default::default(),
16697                },
16698                true,
16699            )
16700            .unwrap();
16701        let handler = ControlHandler::new(registry).with_supervisor(handle);
16702        let now = u64::try_from(
16703            std::time::SystemTime::now()
16704                .duration_since(std::time::UNIX_EPOCH)
16705                .unwrap()
16706                .as_millis(),
16707        )
16708        .unwrap();
16709        let measured = now - 1_000;
16710        let hour = CpuLastHour::new(100, 60_000);
16711        let daemon = DaemonResources::new(7, 1, "test")
16712            .with_measured_at_ms(Some(measured))
16713            .with_resources(Some(ChildResourceUsage::Measured(
16714                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16715            )))
16716            .with_cpu_last_hour(Some(hour.clone()));
16717        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16718            .with_measured_at_ms(Some(measured))
16719            .with_cpu_last_hour(Some(hour.clone()));
16720        let tree = TreeReading::new(
16721            150,
16722            50,
16723            ChildMemoryKind::ResidentSet,
16724            1,
16725            TreeSource::ProcessTree,
16726        )
16727        .with_measured_at_ms(Some(measured));
16728        handler.resource_tracker.seed_committed_for_test(
16729            &handler.supervisor.list(),
16730            crate::resource_totals::Readings {
16731                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16732                daemon: Some(daemon),
16733                agent_commands: Some(vec![agents]),
16734                ..Default::default()
16735            },
16736            now,
16737        );
16738        list_diagnostics::scope(async {
16739            tokio::time::sleep(Duration::from_millis(110)).await;
16740            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16741            let request =
16742                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16743            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16744            let ClientControlResponse::SupervisorList {
16745                modules,
16746                daemon,
16747                agent_commands,
16748                ..
16749            } = serde_json::from_slice(&replies[0].body).unwrap()
16750            else {
16751                panic!("expected a list response")
16752            };
16753            assert!(matches!(
16754                modules[0].resources,
16755                Some(ChildResourceUsage::Unavailable {
16756                    reason: ChildResourceUnavailableReason::Unreadable
16757                })
16758            ));
16759            assert_eq!(
16760                (
16761                    modules[0].tree.as_ref().unwrap().cpu_ms,
16762                    modules[0].tree.as_ref().unwrap().measured_at_ms
16763                ),
16764                (150, Some(measured))
16765            );
16766            let daemon = daemon.unwrap();
16767            let agents = agent_commands.unwrap();
16768            assert_eq!(daemon.measured_at_ms, Some(measured));
16769            assert_eq!(
16770                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16771                (1, 50, Some(measured))
16772            );
16773            for hour in [
16774                modules[0].cpu_last_hour.as_ref(),
16775                daemon.cpu_last_hour.as_ref(),
16776                agents[0].cpu_last_hour.as_ref(),
16777            ] {
16778                let hour = hour.unwrap();
16779                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16780            }
16781        })
16782        .await;
16783    }
16784
16785    #[tokio::test]
16786    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16787        let registry = Arc::new(Registry::default());
16788        let handle = SupervisorHandle::new();
16789        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16790            .with_handle(handle.clone());
16791        supervisor
16792            .supervise_configured(
16793                crate::ModuleSpec {
16794                    script: None,
16795                    carry_containment: false,
16796                    module_id: "drift".into(),
16797                    program: PathBuf::from("disabled-module"),
16798                    args: Vec::new(),
16799                    env: Vec::new(),
16800                    reserved: false,
16801                    reserved_prefixes: Vec::new(),
16802                    protocol: ModuleProtocol::Subc,
16803                    overlap: Default::default(),
16804                },
16805                false,
16806            )
16807            .unwrap();
16808        let handler = ControlHandler::new(registry).with_supervisor(handle);
16809        for configured in [None, Some(false), Some(true)] {
16810            handler.capability_evaluator.configure(
16811                configured.map(|enabled| ("drift".to_string(), enabled)),
16812                BTreeMap::new(),
16813            );
16814            let frame =
16815                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16816            let replies = handler
16817                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16818                .await
16819                .unwrap();
16820            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16821            assert!(body.get("configured_enabled").is_none());
16822            assert_eq!(body["op"], "supervisor.ack");
16823            let frame =
16824                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16825            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16826            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16827            assert_eq!(
16828                body["modules"][0].get("configured_enabled"),
16829                configured.map(Value::Bool).as_ref()
16830            );
16831            assert!(body["modules"][0].get("tree").is_none());
16832            assert!(body["modules"][0].get("subtree").is_none());
16833        }
16834    }
16835
16836    #[tokio::test(flavor = "current_thread")]
16837    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16838        let handler = ControlHandler::new(Arc::new(Registry::default()));
16839        let capture = EventCapture::default();
16840        let _subscriber =
16841            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16842        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16843        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16844
16845        let _ = handler
16846            .handle_client_control_request(
16847                &ctx,
16848                frame,
16849                ClientControlRequest::SupervisorSetEnabled {
16850                    module_id: "broca".to_string(),
16851                    enabled: false,
16852                },
16853                &mut None,
16854            )
16855            .await
16856            .unwrap();
16857
16858        let events = capture
16859            .events()
16860            .into_iter()
16861            .filter(|event| {
16862                event.target == "control"
16863                    && event.fields.get("message").map(String::as_str)
16864                        == Some("supervisor request received")
16865            })
16866            .collect::<Vec<_>>();
16867        assert_eq!(events.len(), 1, "one supervisor request log line");
16868        let event = &events[0];
16869        assert_eq!(event.level, tracing::Level::INFO);
16870        assert_eq!(
16871            event.fields.get("op"),
16872            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16873        );
16874        assert_eq!(
16875            event.fields.get("module_id"),
16876            Some(&"\"broca\"".to_string())
16877        );
16878        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16879        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16880        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16881    }
16882
16883    #[tokio::test(flavor = "current_thread")]
16884    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16885        let registry = Arc::new(Registry::default());
16886        let module_connection = ConnectionId::new(303);
16887        registry
16888            .register_with_control_ops(
16889                manifest("aft", PROTOCOL_VERSION),
16890                PROTOCOL_VERSION,
16891                module_connection,
16892                module_baseline_control_ops(),
16893            )
16894            .unwrap();
16895        let handler = ControlHandler::new(registry);
16896        let capture = EventCapture::default();
16897        let _subscriber =
16898            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16899        let (ctx, _rx) = route_ctx(module_connection);
16900        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16901
16902        let _ = handler
16903            .handle_client_control_request(
16904                &ctx,
16905                frame,
16906                ClientControlRequest::SupervisorSetEnabled {
16907                    module_id: "broca".to_string(),
16908                    enabled: false,
16909                },
16910                &mut None,
16911            )
16912            .await
16913            .unwrap();
16914
16915        let callers = capture
16916            .events()
16917            .into_iter()
16918            .filter(|event| {
16919                event.fields.get("message").map(String::as_str)
16920                    == Some("supervisor request received")
16921            })
16922            .map(|event| event.fields.get("caller").cloned())
16923            .collect::<Vec<_>>();
16924        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16925    }
16926
16927    #[tokio::test(flavor = "current_thread")]
16928    async fn supervisor_list_does_not_log_request_received() {
16929        let handler = ControlHandler::new(Arc::new(Registry::default()));
16930        let capture = EventCapture::default();
16931        let _subscriber =
16932            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16933        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16934        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16935
16936        handler
16937            .handle_client_control_request(
16938                &ctx,
16939                frame,
16940                ClientControlRequest::SupervisorList {},
16941                &mut None,
16942            )
16943            .await
16944            .unwrap();
16945
16946        assert!(capture.events().into_iter().all(|event| {
16947            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16948        }));
16949    }
16950
16951    #[tokio::test(flavor = "current_thread")]
16952    async fn supervisor_rescan_preview_does_not_log_request_received() {
16953        let handler = ControlHandler::new(Arc::new(Registry::default()));
16954        let capture = EventCapture::default();
16955        let _subscriber =
16956            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16957        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16958        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16959
16960        handler
16961            .handle_client_control_request(
16962                &ctx,
16963                frame,
16964                ClientControlRequest::SupervisorRescan { preview: true },
16965                &mut None,
16966            )
16967            .await
16968            .unwrap();
16969
16970        assert!(capture.events().into_iter().all(|event| {
16971            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16972        }));
16973    }
16974
16975    struct ApproveOperator;
16976    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16977        fn prompt(
16978            &self,
16979            _: &str,
16980            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16981        ) -> crate::operator_confirm::ProviderResult {
16982            crate::operator_confirm::ProviderResult::Approved
16983        }
16984    }
16985
16986    #[tokio::test]
16987    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
16988        assert_eq!(
16989            ControlHandler::default().privileged_operator_prompt,
16990            PrivilegedOperatorPrompt::Log
16991        );
16992        for (initial, changed, running) in [
16993            ("log", "enforce", PrivilegedOperatorPrompt::Log),
16994            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
16995        ] {
16996            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
16997            let path = dir.join("subc.jsonc");
16998            std::fs::write(
16999                &path,
17000                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
17001            )
17002            .unwrap();
17003            let config = crate::daemon_config::load(&path).unwrap().unwrap();
17004            let registry = Arc::new(Registry::default());
17005            let handle = SupervisorHandle::new();
17006            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
17007                .with_handle(handle.clone());
17008            let handler = ControlHandler::new(registry)
17009                .with_supervisor(handle)
17010                .with_privileged_operator_prompt(config.privileged_operator_prompt)
17011                .with_supervisor_rescan(supervisor, &path, config.port);
17012            handler.forwarding.operator_confirms().configure(
17013                Arc::new(ApproveOperator),
17014                crate::operator_confirm::OperatorLimits::default(),
17015            );
17016            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
17017
17018            for (disk_mode, needs_restart) in [
17019                (Some(initial), false),
17020                (Some(changed), true),
17021                (Some(changed), true),
17022                (None, running == PrivilegedOperatorPrompt::Enforce),
17023                (Some(initial), false),
17024            ] {
17025                let mut doc = json!({"version":1});
17026                if let Some(mode) = disk_mode {
17027                    doc["privileged_operator_prompt"] = json!(mode);
17028                }
17029                std::fs::write(&path, doc.to_string()).unwrap();
17030                for preview in [true, false] {
17031                    let request = ClientControlRequest::SupervisorRescan { preview };
17032                    let frame = Frame::build(
17033                        FrameType::Request,
17034                        control_flags(),
17035                        0,
17036                        0,
17037                        1,
17038                        serde_json::to_vec(&request).unwrap(),
17039                    )
17040                    .unwrap();
17041                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17042                    assert_eq!(frames.len(), 1);
17043                    let ClientControlResponse::SupervisorRescan { result } =
17044                        serde_json::from_slice(&frames[0].body).unwrap()
17045                    else {
17046                        panic!("expected a rescan response");
17047                    };
17048                    let expected = if needs_restart {
17049                        vec!["privileged_operator_prompt"]
17050                    } else {
17051                        Vec::new()
17052                    };
17053                    assert_eq!(result.restart_required, expected);
17054                    assert_eq!(handler.privileged_operator_prompt, running);
17055                    assert_eq!(
17056                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
17057                        running
17058                    );
17059                }
17060            }
17061        }
17062    }
17063
17064    #[tokio::test]
17065    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
17066        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
17067        let path = dir.join("subc.jsonc");
17068        let registry = Arc::new(Registry::default());
17069        let handle = SupervisorHandle::new();
17070        let supervisor =
17071            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
17072        let handler = ControlHandler::new(registry)
17073            .with_supervisor(handle)
17074            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
17075            .with_supervisor_rescan(supervisor, &path, None);
17076        handler.forwarding.operator_confirms().configure(
17077            Arc::new(ApproveOperator),
17078            crate::operator_confirm::OperatorLimits::default(),
17079        );
17080        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17081        for preview in [true, false] {
17082            std::fs::write(
17083                &path,
17084                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17085            )
17086            .unwrap();
17087            let request = ClientControlRequest::SupervisorRescan { preview };
17088            let frame = Frame::build(
17089                FrameType::Request,
17090                control_flags(),
17091                0,
17092                0,
17093                1,
17094                serde_json::to_vec(&request).unwrap(),
17095            )
17096            .unwrap();
17097            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17098            assert_eq!(frames.len(), 1);
17099            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17100            assert_eq!(
17101                handler.privileged_operator_prompt,
17102                PrivilegedOperatorPrompt::Enforce
17103            );
17104        }
17105    }
17106
17107    /// One wire code has several senders, so the refusal line names the check
17108    /// that refused. This drives the shared refusal path for ordinary refusals
17109    /// with an unregistered
17110    /// target and requires the branch label on the event.
17111    #[tokio::test]
17112    async fn route_open_refusal_names_the_check_that_refused() {
17113        let handler = ControlHandler::new(Arc::new(Registry::default()));
17114        let capture = EventCapture::default();
17115        let _subscriber =
17116            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17117        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17118        let response = handler
17119            .handle_control_frame(
17120                &ctx,
17121                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17122            )
17123            .await
17124            .unwrap();
17125
17126        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17127        let event = capture
17128            .events()
17129            .into_iter()
17130            .find(|event| {
17131                event.target == "control"
17132                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17133            })
17134            .expect("route.open refusal event");
17135        assert_eq!(
17136            event.fields.get("reason"),
17137            Some(&"\"not_registered\"".to_string())
17138        );
17139    }
17140
17141    #[tokio::test]
17142    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17143        let registry = Arc::new(Registry::default());
17144        let supervisor_handle = SupervisorHandle::new();
17145        let supervisor =
17146            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17147                .with_handle(supervisor_handle.clone())
17148                .with_connection_file_path(std::env::temp_dir().join(format!(
17149                    "subc-route-open-refusal-info-{}",
17150                    std::process::id()
17151                )));
17152        let module = supervisor
17153            .supervise_configured(
17154                ModuleSpec {
17155                    script: None,
17156                    carry_containment: false,
17157                    module_id: "warming".to_string(),
17158                    program: fake_aft_stub_path(),
17159                    args: Vec::new(),
17160                    env: Vec::new(),
17161                    reserved: false,
17162                    reserved_prefixes: Vec::new(),
17163                    protocol: ModuleProtocol::Subc,
17164                    overlap: Default::default(),
17165                },
17166                true,
17167            )
17168            .unwrap();
17169        assert_eq!(module.state().unwrap(), ModuleState::Running);
17170
17171        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17172        assert!(handler
17173            .counters()
17174            .snapshot()
17175            .get("route_open_refused_by_code")
17176            .is_none());
17177        let capture = EventCapture::default();
17178        let _subscriber =
17179            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17180        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17181        let response = handler
17182            .handle_control_frame(
17183                &ctx,
17184                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17185            )
17186            .await
17187            .unwrap();
17188        module.stop().await.unwrap();
17189
17190        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17191        let event = capture
17192            .events()
17193            .into_iter()
17194            .find(|event| {
17195                event.target == "control"
17196                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17197            })
17198            .expect("route.open refusal event");
17199        assert_eq!(
17200            event.fields.get("module_id"),
17201            Some(&"\"warming\"".to_string())
17202        );
17203        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17204        assert_eq!(
17205            event.fields.get("reason"),
17206            Some(&"\"supervised_not_registered\"".to_string())
17207        );
17208        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17209        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17210        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17211        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17212        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17213        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17214        assert_eq!(
17215            handler.counters().snapshot()["route_open_refused_by_code"],
17216            json!({ "module_warming": 1 })
17217        );
17218    }
17219
17220    const OUTAGE_START: &str = "route.open refusing module: not serving";
17221    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17222
17223    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17224        capture
17225            .events()
17226            .into_iter()
17227            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17228            .collect()
17229    }
17230
17231    fn supervise_stub(
17232        registry: &Arc<Registry>,
17233        module_id: &str,
17234        enabled: bool,
17235    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17236        let supervisor_handle = SupervisorHandle::new();
17237        let supervisor =
17238            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17239                .with_handle(supervisor_handle.clone())
17240                .with_connection_file_path(std::env::temp_dir().join(format!(
17241                    "subc-route-outage-{module_id}-{}",
17242                    std::process::id()
17243                )));
17244        let module = supervisor
17245            .supervise_configured(
17246                ModuleSpec {
17247                    script: None,
17248                    carry_containment: false,
17249                    module_id: module_id.to_string(),
17250                    program: fake_aft_stub_path(),
17251                    args: Vec::new(),
17252                    env: Vec::new(),
17253                    reserved: false,
17254                    reserved_prefixes: Vec::new(),
17255                    protocol: ModuleProtocol::Subc,
17256                    overlap: Default::default(),
17257                },
17258                enabled,
17259            )
17260            .unwrap();
17261        (supervisor_handle, module)
17262    }
17263
17264    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17265        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17266            module_id: module_id.to_string(),
17267            drain_timeout_ms: Some(50),
17268        })
17269        .unwrap();
17270        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17271    }
17272
17273    /// Two handlers built over one forwarding table must share one outage
17274    /// tracker; separate trackers would each log their own opening line for
17275    /// the same outage.
17276    #[test]
17277    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17278        let registry = Arc::new(Registry::default());
17279        let forwarding = Arc::new(ForwardingTable::default());
17280        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17281        let second = ControlHandler::with_forwarding(registry, forwarding);
17282        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17283    }
17284
17285    /// A client can name any module id it likes. Refusing an unknown one,
17286    /// however often, must not create outage state or outage lines, or the
17287    /// tracker would be a memory sink any client could fill.
17288    #[tokio::test(flavor = "current_thread")]
17289    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17290        let handler = ControlHandler::new(Arc::new(Registry::default()));
17291        let capture = EventCapture::default();
17292        let _subscriber =
17293            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17294        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17295        for corr in 0..8 {
17296            let response = handler
17297                .handle_control_frame(
17298                    &ctx,
17299                    route_open_frame(
17300                        380 + corr,
17301                        &format!("nobody-{corr}"),
17302                        unique_project_root("outage-unknown"),
17303                    ),
17304                )
17305                .await
17306                .unwrap();
17307            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17308        }
17309
17310        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17311        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17312        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17313    }
17314
17315    /// Drives the refusal path end to end: a supervised module that served
17316    /// before and stopped being registered with no instruction to stop is a
17317    /// WARN, and the same module refused after an operator `supervisor.restart`
17318    /// is an INFO.
17319    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17320    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17321        let registry = Arc::new(Registry::default());
17322        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17323        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17324        let capture = EventCapture::default();
17325        let _subscriber =
17326            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17327        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17328        // The stub never registers, so pretend it served once: otherwise every
17329        // refusal would fall in its startup window.
17330        handler.route_outages.record_accepted("outage-restart");
17331
17332        let response = handler
17333            .handle_control_frame(
17334                &ctx,
17335                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17336            )
17337            .await
17338            .unwrap();
17339        assert_eq!(response[0].header.ty, FrameType::Error);
17340        let starts = outage_lines(&capture, OUTAGE_START);
17341        assert_eq!(starts.len(), 1, "{starts:?}");
17342        assert_eq!(starts[0].level, tracing::Level::WARN);
17343        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17344        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17345        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17346        handler.route_outages.record_accepted("outage-restart");
17347        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17348
17349        // The missing connection file makes the stub exit immediately. Restart
17350        // is deliberately deferred while that exit is being recorded; Failed
17351        // means the zero restart budget and terminal record have been published.
17352        tokio::time::timeout(Duration::from_secs(10), async {
17353            while module.state().unwrap() != crate::ModuleState::Failed {
17354                tokio::task::yield_now().await;
17355            }
17356        })
17357        .await
17358        .expect("stub exit must be recorded before the operator restart");
17359
17360        let restart = handler
17361            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17362            .await
17363            .unwrap();
17364        assert_eq!(
17365            restart[0].header.ty,
17366            FrameType::Response,
17367            "{:?}",
17368            parse_error(&restart[0])
17369        );
17370        handler
17371            .handle_control_frame(
17372                &ctx,
17373                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17374            )
17375            .await
17376            .unwrap();
17377        module.stop().await.unwrap();
17378
17379        let starts = outage_lines(&capture, OUTAGE_START);
17380        assert_eq!(starts.len(), 2, "{starts:?}");
17381        assert_eq!(starts[1].level, tracing::Level::INFO);
17382        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17383    }
17384
17385    /// A restart refused before it touched the module (here: the module is
17386    /// disabled) must clear its operator mark, so the next real outage is
17387    /// still reported as a warning.
17388    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17389    async fn failed_operator_restart_leaves_no_operator_mark() {
17390        let registry = Arc::new(Registry::default());
17391        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17392        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17393        let capture = EventCapture::default();
17394        let _subscriber =
17395            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17396        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17397        handler.route_outages.record_accepted("outage-disabled");
17398
17399        let restart = handler
17400            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17401            .await
17402            .unwrap();
17403        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17404        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17405
17406        handler
17407            .handle_control_frame(
17408                &ctx,
17409                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17410            )
17411            .await
17412            .unwrap();
17413        let starts = outage_lines(&capture, OUTAGE_START);
17414        assert_eq!(starts.len(), 1, "{starts:?}");
17415        assert_eq!(starts[0].level, tracing::Level::WARN);
17416    }
17417
17418    #[tokio::test(flavor = "current_thread")]
17419    async fn route_open_unknown_module_escapes_target_module_id() {
17420        let handler = ControlHandler::new(Arc::new(Registry::default()));
17421        let capture = EventCapture::default();
17422        let _subscriber =
17423            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17424        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17425        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17426        let response = handler
17427            .handle_control_frame(
17428                &ctx,
17429                route_open_frame(
17430                    395,
17431                    hostile_module_id,
17432                    unique_project_root("hostile-target-module-id"),
17433                ),
17434            )
17435            .await
17436            .unwrap();
17437
17438        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17439        let event = capture
17440            .events()
17441            .into_iter()
17442            .find(|event| {
17443                event.target == "control"
17444                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17445            })
17446            .expect("route.open unknown-module refusal event");
17447        let logged = event.fields.get("module_id").expect("module_id field");
17448        assert!(!logged.bytes().any(|byte| byte < 0x20));
17449        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17450    }
17451
17452    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17453    /// the daemon-origin bit on the frame the client receives.
17454    #[tokio::test(flavor = "current_thread")]
17455    async fn route_open_refusal_carries_daemon_origin() {
17456        let handler = ControlHandler::new(Arc::new(Registry::default()));
17457        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17458        let response = handler
17459            .handle_control_frame(
17460                &ctx,
17461                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17462            )
17463            .await
17464            .unwrap();
17465
17466        assert_eq!(response.len(), 1);
17467        assert_eq!(response[0].header.ty, FrameType::Error);
17468        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17469        assert!(
17470            response[0].header.flags.is_daemon_origin(),
17471            "route.open refusal must carry daemon origin: {:?}",
17472            response[0].header.flags
17473        );
17474    }
17475
17476    /// The drain `module_reloading` refusal is daemon-synthesized for an
17477    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17478    /// frame the client receives.
17479    #[tokio::test(flavor = "current_thread")]
17480    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17481        let registry = Arc::new(Registry::default());
17482        let forwarding = Arc::new(ForwardingTable::default());
17483        let handler =
17484            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17485        let module_connection = ConnectionId::new(95);
17486        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17487        hello_via_sink(
17488            &handler,
17489            &module_ctx,
17490            &mut module_rx,
17491            hello_frame("aft", PROTOCOL_VERSION, 395),
17492        )
17493        .await;
17494        forwarding
17495            .begin_module_drain("aft", RouteCloseReason::Restart)
17496            .unwrap()
17497            .expect("the module endpoint drains");
17498
17499        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17500        let response = handler
17501            .handle_control_frame(
17502                &client_ctx,
17503                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17504            )
17505            .await
17506            .unwrap();
17507
17508        assert_eq!(response.len(), 1);
17509        assert_eq!(response[0].header.ty, FrameType::Error);
17510        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17511        assert!(
17512            response[0].header.flags.is_daemon_origin(),
17513            "drain module_reloading must carry daemon origin: {:?}",
17514            response[0].header.flags
17515        );
17516    }
17517
17518    /// A module that refuses a bind with a daemon code still cannot mint a
17519    /// daemon refusal: the relayed `module_reloading` body reaches the client
17520    /// with the daemon-origin bit clear.
17521    #[tokio::test(flavor = "current_thread")]
17522    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17523        let registry = Arc::new(Registry::default());
17524        let forwarding = Arc::new(ForwardingTable::default());
17525        let handler =
17526            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17527        let module_connection = ConnectionId::new(95);
17528        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17529        hello_via_sink(
17530            &handler,
17531            &module_ctx,
17532            &mut module_rx,
17533            hello_frame("aft", PROTOCOL_VERSION, 395),
17534        )
17535        .await;
17536
17537        let client_connection = ConnectionId::new(96);
17538        let (client_ctx, _client_rx) = route_ctx(client_connection);
17539        let (route_task, bind) = relay_route_open(
17540            &handler,
17541            client_connection,
17542            &client_ctx.egress,
17543            &mut module_rx,
17544            396,
17545            "aft",
17546            "spoofed-reloading",
17547        )
17548        .await;
17549        // The module sets the origin bit on its own rejection too: neither
17550        // the bit nor the daemon code may survive the relay as daemon-owned.
17551        let rejection = Frame::build(
17552            FrameType::Error,
17553            crate::router::daemon_error_flags(),
17554            0,
17555            0,
17556            bind.header.corr,
17557            serde_json::to_vec(&ErrorBody::new(
17558                "module_reloading",
17559                "module refused route.bind",
17560            ))
17561            .unwrap(),
17562        )
17563        .unwrap();
17564        handler
17565            .handle_control_frame(&module_ctx, rejection)
17566            .await
17567            .unwrap();
17568
17569        let response = route_task.await.unwrap();
17570        assert_eq!(response.len(), 1);
17571        assert_eq!(response[0].header.ty, FrameType::Error);
17572        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17573        assert!(
17574            !response[0].header.flags.is_daemon_origin(),
17575            "a module's own rejection must not carry daemon origin: {:?}",
17576            response[0].header.flags
17577        );
17578    }
17579
17580    #[tokio::test(flavor = "current_thread")]
17581    async fn route_open_module_rejection_uses_daemon_counter_key() {
17582        let registry = Arc::new(Registry::default());
17583        let forwarding = Arc::new(ForwardingTable::default());
17584        let handler =
17585            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17586        let module_connection = ConnectionId::new(95);
17587        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17588        hello_via_sink(
17589            &handler,
17590            &module_ctx,
17591            &mut module_rx,
17592            hello_frame("aft", PROTOCOL_VERSION, 395),
17593        )
17594        .await;
17595
17596        let client_connection = ConnectionId::new(96);
17597        let (client_ctx, _client_rx) = route_ctx(client_connection);
17598        let capture = EventCapture::default();
17599        // tracing-core decides once per callsite whether its events are enabled,
17600        // and caches the answer. If a parallel test with no subscriber reaches
17601        // this callsite first, the cached answer is "disabled" and this test's
17602        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17603        // ask every live subscriber instead, while only this test's default
17604        // receives the events.
17605        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17606        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17607        let _subscriber =
17608            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17609        let (route_task, bind) = relay_route_open(
17610            &handler,
17611            client_connection,
17612            &client_ctx.egress,
17613            &mut module_rx,
17614            396,
17615            "aft",
17616            "hostile-module-code",
17617        )
17618        .await;
17619        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17620        let rejection = Frame::build(
17621            FrameType::Error,
17622            control_flags(),
17623            0,
17624            0,
17625            bind.header.corr,
17626            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17627        )
17628        .unwrap();
17629        handler
17630            .handle_control_frame(&module_ctx, rejection)
17631            .await
17632            .unwrap();
17633
17634        let response = route_task.await.unwrap();
17635        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17636        let counters = handler.counters().snapshot();
17637        assert_eq!(
17638            counters["route_open_refused_by_code"],
17639            json!({ "module_rejected": 1 })
17640        );
17641        assert!(counters["route_open_refused_by_code"]
17642            .get(hostile_code)
17643            .is_none());
17644
17645        let event = capture
17646            .events()
17647            .into_iter()
17648            .find(|event| {
17649                event.target == "control"
17650                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17651            })
17652            .expect("route.open module-rejection refusal event");
17653        let logged = event.fields.get("module_code").expect("module_code field");
17654        assert!(!logged.bytes().any(|byte| byte < 0x20));
17655        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17656    }
17657
17658    #[tokio::test]
17659    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17660        let registry = Arc::new(Registry::default());
17661        let supervisor_handle = SupervisorHandle::new();
17662        let missing_program = std::env::temp_dir().join(format!(
17663            "subc-route-open-missing-program-{}",
17664            std::process::id()
17665        ));
17666        let supervisor =
17667            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17668                .with_handle(supervisor_handle.clone());
17669        let module = supervisor
17670            .supervise_configured(
17671                ModuleSpec {
17672                    script: None,
17673                    carry_containment: false,
17674                    module_id: "failed".to_string(),
17675                    program: missing_program,
17676                    args: Vec::new(),
17677                    env: Vec::new(),
17678                    reserved: false,
17679                    reserved_prefixes: Vec::new(),
17680                    protocol: ModuleProtocol::Subc,
17681                    overlap: Default::default(),
17682                },
17683                true,
17684            )
17685            .unwrap();
17686        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17687
17688        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17689        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17690        let response = handler
17691            .handle_control_frame(
17692                &ctx,
17693                route_open_frame(305, "failed", unique_project_root("failed")),
17694            )
17695            .await
17696            .unwrap();
17697
17698        assert_eq!(response[0].header.ty, FrameType::Error);
17699        let error = parse_error(&response[0]);
17700        assert_eq!(error["code"], "target_unavailable");
17701        assert!(error["message"]
17702            .as_str()
17703            .unwrap()
17704            .contains("state=failed, enabled=true, live=false"));
17705    }
17706
17707    #[tokio::test]
17708    async fn route_open_role_mismatch_remains_target_unavailable() {
17709        let registry = Arc::new(Registry::default());
17710        let handler = ControlHandler::new(Arc::clone(&registry));
17711        handler
17712            .handle_control(
17713                ConnectionId::new(41),
17714                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17715            )
17716            .unwrap();
17717
17718        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17719        let response = handler
17720            .handle_control_frame(
17721                &ctx,
17722                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17723            )
17724            .await
17725            .unwrap();
17726
17727        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17728        assert!(parse_error(&response[0])["message"]
17729            .as_str()
17730            .unwrap()
17731            .contains("does not provide the requested target"));
17732    }
17733
17734    #[tokio::test]
17735    async fn route_open_inactive_registration_remains_target_unavailable() {
17736        let registry = Arc::new(Registry::default());
17737        let handler = ControlHandler::new(Arc::clone(&registry));
17738        handler
17739            .handle_control(
17740                ConnectionId::new(43),
17741                hello_frame("inactive", PROTOCOL_VERSION, 308),
17742            )
17743            .unwrap();
17744        assert!(registry
17745            .set_module_state_for_test("inactive", ChannelState::Closed)
17746            .unwrap());
17747
17748        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17749        let response = handler
17750            .handle_control_frame(
17751                &ctx,
17752                route_open_frame(309, "inactive", unique_project_root("inactive")),
17753            )
17754            .await
17755            .unwrap();
17756
17757        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17758        assert!(parse_error(&response[0])["message"]
17759            .as_str()
17760            .unwrap()
17761            .contains("is not active"));
17762    }
17763
17764    #[tokio::test]
17765    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17766        let registry = Arc::new(Registry::default());
17767        let forwarding = Arc::new(ForwardingTable::default());
17768        let supervisor_handle = SupervisorHandle::new();
17769        let supervisor =
17770            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17771                .with_forwarding(Arc::clone(&forwarding))
17772                .with_handle(supervisor_handle.clone());
17773        let module = supervisor
17774            .supervise_configured(
17775                crate::ModuleSpec {
17776                    script: None,
17777                    carry_containment: false,
17778                    module_id: "late-health-response".to_string(),
17779                    program: PathBuf::from("disabled-module"),
17780                    args: Vec::new(),
17781                    env: Vec::new(),
17782                    reserved: false,
17783                    reserved_prefixes: Vec::new(),
17784                    protocol: ModuleProtocol::Subc,
17785                    overlap: Default::default(),
17786                },
17787                false,
17788            )
17789            .unwrap();
17790        let handler =
17791            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17792                .with_supervisor(supervisor_handle);
17793        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17794        handler
17795            .handle_control_frame(
17796                &module_ctx,
17797                hello_frame_with_control_ops(
17798                    "late-health-response",
17799                    PROTOCOL_VERSION,
17800                    7,
17801                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17802                ),
17803            )
17804            .await
17805            .unwrap();
17806        let probe_started_at = Instant::now() - Duration::from_millis(80);
17807        let pending = forwarding
17808            .begin_health_probe_rpc_for(
17809                "late-health-response",
17810                MODULE_CONTROL_OP_HEALTH_CHECK,
17811                probe_started_at,
17812                Instant::now() - Duration::from_millis(1),
17813            )
17814            .unwrap();
17815        assert!(forwarding
17816            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17817            .unwrap());
17818
17819        let responses = handler
17820            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17821            .await
17822            .unwrap();
17823
17824        assert!(responses.is_empty());
17825        let health = module.status().unwrap().health;
17826        assert_eq!(health.late_answer_count, 1);
17827        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17828    }
17829
17830    #[tokio::test]
17831    async fn health_probe_timeout_and_module_death_are_typed() {
17832        let registry = Arc::new(Registry::default());
17833        let forwarding = Arc::new(ForwardingTable::default());
17834        let handler =
17835            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17836                .with_health_probe_timeout(Duration::from_millis(50));
17837        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17838        hello_via_sink(
17839            &handler,
17840            &module_ctx,
17841            &mut module_rx,
17842            hello_frame_with_control_ops(
17843                "aft",
17844                PROTOCOL_VERSION,
17845                7,
17846                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17847            ),
17848        )
17849        .await;
17850
17851        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17852        let responses = handler
17853            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17854            .await
17855            .unwrap();
17856        assert_eq!(responses[0].header.ty, FrameType::Error);
17857        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17858        let _ = module_rx.try_recv();
17859
17860        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17861        let health_handler = handler.clone();
17862        let death_task = tokio::spawn(async move {
17863            health_handler
17864                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17865                .await
17866                .unwrap()
17867        });
17868        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17869            .await
17870            .unwrap()
17871            .unwrap();
17872        handler
17873            .cleanup_connection(module_ctx.connection_id)
17874            .unwrap();
17875        let responses = death_task.await.unwrap();
17876        assert_eq!(responses[0].header.ty, FrameType::Error);
17877        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17878    }
17879
17880    #[test]
17881    fn hello_requires_exact_protocol_version() {
17882        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17883            let registry = Arc::new(Registry::default());
17884            let handler = ControlHandler::new(Arc::clone(&registry));
17885            let responses = handler
17886                .handle_control(
17887                    ConnectionId::new(connection),
17888                    hello_frame("aft", offered, 9),
17889                )
17890                .unwrap();
17891
17892            assert_eq!(responses.len(), 1);
17893            assert_eq!(responses[0].header.ty, FrameType::Error);
17894            let error = parse_error(&responses[0]);
17895            assert_eq!(error["code"], "version_unsupported");
17896            assert!(registry.get_module("aft").unwrap().is_none());
17897            assert_eq!(registry.active_registration_count().unwrap(), 0);
17898        }
17899    }
17900
17901    #[test]
17902    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17903        let registry = Arc::new(Registry::default());
17904        let forwarding = Arc::new(ForwardingTable::default());
17905        let handler =
17906            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17907        let module_connection = ConnectionId::new(301);
17908        let registration = registry
17909            .register_with_control_ops(
17910                manifest("aft-push", PROTOCOL_VERSION),
17911                PROTOCOL_VERSION,
17912                module_connection,
17913                module_baseline_control_ops(),
17914            )
17915            .unwrap();
17916        let (module_tx, _module_rx) = mpsc::channel(8);
17917        let endpoint = forwarding
17918            .register_module_connection(
17919                module_connection,
17920                "aft-push".to_string(),
17921                PROTOCOL_VERSION,
17922                manifest_concurrency(&registration.manifest),
17923                FrameSink::new(module_tx),
17924            )
17925            .unwrap();
17926
17927        // A push op this version does not know is ignored (forward-compat), not errored.
17928        let unknown = Frame::build(
17929            FrameType::Push,
17930            control_flags(),
17931            0,
17932            0,
17933            5,
17934            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17935        )
17936        .unwrap();
17937        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17938        assert!(
17939            out.is_empty(),
17940            "unknown push op must be ignored, got {out:?}"
17941        );
17942
17943        // A malformed body for a KNOWN op is a real error worth surfacing.
17944        let malformed = Frame::build(
17945            FrameType::Push,
17946            control_flags(),
17947            0,
17948            0,
17949            6,
17950            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17951        )
17952        .unwrap();
17953        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17954        assert_eq!(out.len(), 1);
17955        assert_eq!(out[0].header.ty, FrameType::Error);
17956        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17957    }
17958
17959    #[test]
17960    fn hello_rejected_when_connection_already_owns_client_routes() {
17961        let registry = Arc::new(Registry::default());
17962        let forwarding = Arc::new(ForwardingTable::default());
17963        let handler =
17964            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17965        // Commits a client route on connection 202 (bound to a module on conn 101).
17966        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17967        let client_connection = ConnectionId::new(202);
17968
17969        // That same connection now tries to register as a module: rejected, so one
17970        // connection never holds both client-route and module-endpoint state.
17971        let responses = handler
17972            .handle_control(
17973                client_connection,
17974                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17975            )
17976            .unwrap();
17977        assert_eq!(responses[0].header.ty, FrameType::Error);
17978        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17979        assert!(registry.get_module("aft-second").unwrap().is_none());
17980    }
17981
17982    #[tokio::test]
17983    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17984        let registry = Arc::new(Registry::default());
17985        let forwarding = Arc::new(ForwardingTable::default());
17986        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
17987        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
17988        hello_via_sink(
17989            &handler,
17990            &module_ctx,
17991            &mut module_rx,
17992            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
17993        )
17994        .await;
17995        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
17996        let pending = forwarding
17997            .begin_route_bind_relay_for_test(
17998                client_ctx.connection_id,
17999                client_ctx.egress.clone(),
18000                2,
18001                "alpha",
18002            )
18003            .unwrap();
18004        forwarding
18005            .complete_pending_relay(
18006                module_ctx.connection_id,
18007                pending.corr,
18008                RouteBindRelayOutcome::Accepted,
18009            )
18010            .unwrap();
18011        client_rx.try_recv().unwrap();
18012        for module_id in ["beta", "alpha"] {
18013            let replies = handler
18014                .handle_control_frame(
18015                    &module_ctx,
18016                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
18017                )
18018                .await
18019                .unwrap();
18020            assert_eq!(replies.len(), 1, "second HELLO must be refused");
18021            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
18022        }
18023        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
18024        assert!(registry.get_module("beta").unwrap().is_none());
18025        assert!(matches!(
18026            forwarding
18027                .lookup_data_route(
18028                    client_ctx.connection_id,
18029                    pending.client_channel,
18030                    pending.client_epoch,
18031                )
18032                .unwrap(),
18033            DataRoute::Client(DataRouteState::Bound(_))
18034        ));
18035        assert!(handler
18036            .hello_launch_nonces
18037            .lock()
18038            .unwrap()
18039            .presented(module_ctx.connection_id, Some("alpha-nonce")));
18040        assert!(module_rx.try_recv().is_err());
18041    }
18042
18043    #[test]
18044    fn reserved_module_hello_requires_matching_launch_nonce() {
18045        let registry = Arc::new(Registry::default());
18046        let supervisor = SupervisorHandle::new();
18047        // The supervisor recorded the nonce it injected when it spawned the reserved
18048        // module; the HELLO verifier checks against the same shared handle.
18049        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
18050        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18051
18052        // A HELLO with NO nonce is rejected.
18053        let no_nonce = handler
18054            .handle_control(
18055                ConnectionId::new(1),
18056                hello_frame("vault", PROTOCOL_VERSION, 1),
18057            )
18058            .unwrap();
18059        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
18060        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
18061        assert!(registry.get_module("vault").unwrap().is_none());
18062
18063        // A HELLO with the WRONG nonce is rejected.
18064        let wrong = handler
18065            .handle_control(
18066                ConnectionId::new(2),
18067                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
18068            )
18069            .unwrap();
18070        assert_eq!(wrong[0].header.ty, FrameType::Error);
18071        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
18072        assert!(registry.get_module("vault").unwrap().is_none());
18073
18074        // A HELLO with the CORRECT nonce registers.
18075        let ok = handler
18076            .handle_control(
18077                ConnectionId::new(3),
18078                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
18079            )
18080            .unwrap();
18081        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18082        assert!(registry.get_module("vault").unwrap().is_some());
18083    }
18084
18085    #[test]
18086    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18087        let registry = Arc::new(Registry::default());
18088        let supervisor = SupervisorHandle::new();
18089        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18090        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18091        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18092
18093        let squat = handler
18094            .handle_control(
18095                ConnectionId::new(1),
18096                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18097            )
18098            .unwrap();
18099        assert_eq!(squat[0].header.ty, FrameType::Error);
18100        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18101        assert!(parse_error(&squat[0])["message"]
18102            .as_str()
18103            .unwrap()
18104            .contains("fed:"));
18105
18106        let accepted_peer = handler
18107            .handle_control(
18108                ConnectionId::new(2),
18109                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18110            )
18111            .unwrap();
18112        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18113
18114        let accepted_short = handler
18115            .handle_control(
18116                ConnectionId::new(3),
18117                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18118            )
18119            .unwrap();
18120        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18121
18122        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18123            let response = handler
18124                .handle_control(
18125                    ConnectionId::new(conn),
18126                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18127                )
18128                .unwrap();
18129            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18130        }
18131    }
18132
18133    #[test]
18134    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18135        let registry = Arc::new(Registry::default());
18136        let supervisor = SupervisorHandle::new();
18137        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18138        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18139        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18140        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18141
18142        let owner_nonce = handler
18143            .handle_control(
18144                ConnectionId::new(1),
18145                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18146            )
18147            .unwrap();
18148        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18149        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18150        assert!(registry.get_module("fed:special").unwrap().is_none());
18151
18152        let exact_nonce = handler
18153            .handle_control(
18154                ConnectionId::new(2),
18155                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18156            )
18157            .unwrap();
18158        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18159        assert!(registry.get_module("fed:special").unwrap().is_some());
18160    }
18161
18162    #[test]
18163    fn non_reserved_module_ignores_launch_nonce() {
18164        let registry = Arc::new(Registry::default());
18165        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18166        // registration succeeds whether a spawned process echoes a nonce or not.
18167        let handler = ControlHandler::new(Arc::clone(&registry));
18168        let no_nonce = handler
18169            .handle_control(
18170                ConnectionId::new(1),
18171                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18172            )
18173            .unwrap();
18174        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18175        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18176
18177        let echoed_nonce = handler
18178            .handle_control(
18179                ConnectionId::new(2),
18180                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18181            )
18182            .unwrap();
18183        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18184        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18185    }
18186
18187    #[test]
18188    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18189        let handler = ControlHandler::default();
18190        let conn = ConnectionId::new(1);
18191        let malformed = Frame::build(
18192            FrameType::Hello,
18193            control_flags(),
18194            0,
18195            0,
18196            3,
18197            b"{not json".to_vec(),
18198        )
18199        .unwrap();
18200
18201        let error = handler.handle_control(conn, malformed).unwrap();
18202        assert_eq!(error[0].header.ty, FrameType::Error);
18203        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18204
18205        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18206        let pong = handler.handle_control(conn, ping).unwrap();
18207        assert_eq!(pong[0].header.ty, FrameType::Pong);
18208        assert_eq!(pong[0].header.corr, 4);
18209    }
18210
18211    #[test]
18212    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18213        let registry = Arc::new(Registry::default());
18214        let handler = ControlHandler::new(Arc::clone(&registry));
18215
18216        handler
18217            .handle_control(
18218                ConnectionId::new(1),
18219                hello_frame("aft", PROTOCOL_VERSION, 1),
18220            )
18221            .unwrap();
18222        let duplicate = handler
18223            .handle_control(
18224                ConnectionId::new(2),
18225                hello_frame("aft", PROTOCOL_VERSION, 2),
18226            )
18227            .unwrap();
18228
18229        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18230        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18231        let registration = registry.get_module("aft").unwrap().unwrap();
18232        assert_eq!(registration.connection_id, ConnectionId::new(1));
18233    }
18234
18235    #[test]
18236    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18237        let registry = Arc::new(Registry::default());
18238        let forwarding = Arc::new(ForwardingTable::default());
18239        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18240        let handler =
18241            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18242                .with_process_liveness(process_liveness);
18243        let (ctx, route_channel, route_epoch) =
18244            bind_liveness_route(&registry, &forwarding, "aft-dead");
18245        let responses = handler
18246            .handle_route_poll(
18247                &ctx,
18248                route_poll_frame(41, PollKind::Liveness, route_channel),
18249                route_channel,
18250                route_epoch,
18251                PollKind::Liveness,
18252            )
18253            .unwrap();
18254
18255        assert_eq!(responses.len(), 1);
18256        assert_eq!(responses[0].header.ty, FrameType::Response);
18257        assert_route_poll_liveness(&responses[0], false);
18258    }
18259
18260    #[test]
18261    fn liveness_poll_without_process_source_uses_bound_route() {
18262        let registry = Arc::new(Registry::default());
18263        let forwarding = Arc::new(ForwardingTable::default());
18264        let handler =
18265            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18266        let (ctx, route_channel, route_epoch) =
18267            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18268        let responses = handler
18269            .handle_route_poll(
18270                &ctx,
18271                route_poll_frame(42, PollKind::Liveness, route_channel),
18272                route_channel,
18273                route_epoch,
18274                PollKind::Liveness,
18275            )
18276            .unwrap();
18277
18278        assert_route_poll_liveness(&responses[0], true);
18279    }
18280
18281    #[test]
18282    fn liveness_poll_untracked_process_source_uses_bound_route() {
18283        let registry = Arc::new(Registry::default());
18284        let forwarding = Arc::new(ForwardingTable::default());
18285        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18286        let handler =
18287            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18288                .with_process_liveness(process_liveness);
18289        let (ctx, route_channel, route_epoch) =
18290            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18291        let responses = handler
18292            .handle_route_poll(
18293                &ctx,
18294                route_poll_frame(43, PollKind::Liveness, route_channel),
18295                route_channel,
18296                route_epoch,
18297                PollKind::Liveness,
18298            )
18299            .unwrap();
18300
18301        assert_route_poll_liveness(&responses[0], true);
18302    }
18303
18304    #[tokio::test]
18305    async fn unknown_op_returns_unknown_control_op() {
18306        let handler = ControlHandler::default();
18307        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18308        let request = Frame::build(
18309            FrameType::Request,
18310            control_flags(),
18311            0,
18312            0,
18313            55,
18314            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18315        )
18316        .unwrap();
18317
18318        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18319
18320        assert_eq!(response.len(), 1);
18321        assert_eq!(response[0].header.ty, FrameType::Error);
18322        assert_eq!(response[0].header.corr, 55);
18323        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18324    }
18325
18326    #[tokio::test]
18327    async fn supervisor_provenance_rejects_unknown_exact_module() {
18328        let handler = ControlHandler::default();
18329        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18330        let request = Frame::build(
18331            FrameType::Request,
18332            control_flags(),
18333            0,
18334            0,
18335            57,
18336            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18337        )
18338        .unwrap();
18339
18340        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18341
18342        assert_eq!(response.len(), 1);
18343        assert_eq!(response[0].header.ty, FrameType::Error);
18344        assert_eq!(response[0].header.corr, 57);
18345        let error = parse_error(&response[0]);
18346        assert_eq!(error["code"], "unknown_module");
18347        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18348    }
18349
18350    #[test]
18351    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18352        let expected = subc_control::RunningImageAgreement::Unavailable {
18353            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18354        };
18355        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18356        assert_eq!(handler.provenance_probe_override, Some(expected));
18357    }
18358
18359    #[test]
18360    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18361        let verdict = reload_verdict(
18362            std::path::Path::new("/bin/new"),
18363            Some(std::path::Path::new("/bin/old")),
18364            subc_control::RunningImageAgreement::Unavailable {
18365                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18366            },
18367        );
18368        assert!(matches!(
18369            verdict.path,
18370            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18371                if configured == std::path::Path::new("/bin/new")
18372                    && spawned_from == std::path::Path::new("/bin/old")
18373        ));
18374    }
18375
18376    #[test]
18377    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18378        use subc_control::{
18379            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18380        };
18381        let configured = crate::supervise::ModuleSpec {
18382            script: None,
18383            carry_containment: false,
18384            module_id: "legacy".into(),
18385            program: "/module".into(),
18386            args: Vec::new(),
18387            env: Vec::new(),
18388            reserved: false,
18389            reserved_prefixes: Vec::new(),
18390            protocol: subc_control::ModuleProtocol::Subc,
18391            overlap: Default::default(),
18392        };
18393        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18394        assert_eq!(
18395            launch_spec_agreement(&configured, false, Some(&digest)),
18396            Agreement::Unavailable {
18397                reason: Reason::NotRunning
18398            }
18399        );
18400        assert_eq!(
18401            launch_spec_agreement(&configured, true, None),
18402            Agreement::Unavailable {
18403                reason: Reason::SpawnedSpecUnavailable
18404            }
18405        );
18406        assert_eq!(
18407            launch_spec_agreement(&configured, true, Some(&digest)),
18408            Agreement::Match
18409        );
18410    }
18411
18412    #[cfg(windows)]
18413    #[test]
18414    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18415        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18416        let configured = dir.join("module.exe");
18417        std::fs::write(&configured, b"executable path fixture").unwrap();
18418        let spawned = std::fs::canonicalize(&configured).unwrap();
18419        assert_ne!(
18420            configured, spawned,
18421            "fixture must exercise different path spellings"
18422        );
18423        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18424        let lower_case = configured.to_string_lossy().to_lowercase();
18425        for spelling in [
18426            &configured,
18427            Path::new(&forward_slashes),
18428            Path::new(&lower_case),
18429        ] {
18430            let verdict = reload_verdict(
18431                spelling,
18432                Some(&spawned),
18433                subc_control::RunningImageAgreement::Unavailable {
18434                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18435                },
18436            );
18437            assert_eq!(
18438                verdict.path,
18439                ReloadPathAgreement::Match,
18440                "configured {spelling:?}, spawned {spawned:?}"
18441            );
18442        }
18443    }
18444
18445    #[cfg(windows)]
18446    #[test]
18447    fn windows_reload_path_keeps_different_existing_program_pending() {
18448        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18449        let old = dir.join("old.exe");
18450        let new = dir.join("new.exe");
18451        std::fs::write(&old, b"same executable content").unwrap();
18452        std::fs::copy(&old, &new).unwrap();
18453        let spawned = std::fs::canonicalize(&old).unwrap();
18454        let image = subc_control::RunningImageAgreement::Unavailable {
18455            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18456        };
18457        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18458        assert!(
18459            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18460            if configured == new && spawned_from == spawned)
18461        );
18462        let missing = dir.join("missing.exe");
18463        assert!(matches!(
18464            reload_verdict(&missing, Some(&spawned), image).path,
18465            ReloadPathAgreement::Mismatch { .. }
18466        ));
18467    }
18468
18469    #[test]
18470    fn reload_verdict_detects_replaced_image_at_same_path() {
18471        let image = subc_control::RunningImageAgreement::Mismatch {
18472            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18473                digest: "old".into(),
18474            },
18475            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18476                digest: "new".into(),
18477            },
18478        };
18479        let verdict = reload_verdict(
18480            std::path::Path::new("/bin/same"),
18481            Some(std::path::Path::new("/bin/same")),
18482            image.clone(),
18483        );
18484        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18485        assert_eq!(verdict.image, image);
18486    }
18487
18488    #[test]
18489    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18490        let image = subc_control::RunningImageAgreement::Unavailable {
18491            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18492        };
18493        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18494        assert_eq!(
18495            verdict.path,
18496            subc_control::ReloadPathAgreement::Unavailable {
18497                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18498            }
18499        );
18500        assert_eq!(verdict.image, image);
18501
18502        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18503            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18504        };
18505        let verdict = reload_verdict(
18506            std::path::Path::new("/bin/same"),
18507            Some(std::path::Path::new("/bin/same")),
18508            unconfirmed.clone(),
18509        );
18510        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18511        assert_eq!(verdict.image, unconfirmed);
18512    }
18513
18514    #[test]
18515    fn reload_verdict_preserves_each_image_unavailability_reason() {
18516        use subc_control::RunningImageUnavailableReason as Reason;
18517
18518        for reason in [
18519            Reason::NotRunning,
18520            Reason::UnsupportedPlatform,
18521            Reason::RunningExecutableUnreadable,
18522            Reason::SpawnedPathUnreadable,
18523            Reason::HashFailed,
18524            Reason::ProcessIdentityUnconfirmed,
18525            Reason::Unknown("future_probe_reason".to_string()),
18526        ] {
18527            let image = subc_control::RunningImageAgreement::Unavailable {
18528                reason: reason.clone(),
18529            };
18530            let verdict = reload_verdict(
18531                std::path::Path::new("/bin/same"),
18532                Some(std::path::Path::new("/bin/same")),
18533                image.clone(),
18534            );
18535            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18536            assert_eq!(verdict.image, image, "{reason:?}");
18537        }
18538    }
18539
18540    #[tokio::test]
18541    async fn malformed_control_bodies_return_invalid_control_body() {
18542        let handler = ControlHandler::default();
18543        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18544
18545        for (corr, body) in [
18546            (56, br#"{"route_channel":1}"#.as_slice()),
18547            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18548            (
18549                58,
18550                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18551            ),
18552        ] {
18553            let request = Frame::build(
18554                FrameType::Request,
18555                control_flags(),
18556                0,
18557                0,
18558                corr,
18559                body.to_vec(),
18560            )
18561            .unwrap();
18562            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18563
18564            assert_eq!(response.len(), 1);
18565            assert_eq!(response[0].header.ty, FrameType::Error);
18566            assert_eq!(response[0].header.corr, corr);
18567            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18568        }
18569    }
18570
18571    #[tokio::test]
18572    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18573        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18574        let registry = Arc::new(Registry::default());
18575        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18576        let router = Router::with_control_handler(Arc::clone(&control));
18577        let connection = router.begin_connection();
18578        let (ctx, mut rx) = route_ctx(connection.id());
18579
18580        router
18581            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18582            .await
18583            .unwrap();
18584        let response = rx.recv().await.unwrap();
18585        let ack = parse_ack(&response);
18586        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18587        let channel = 1;
18588
18589        let goodbye =
18590            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18591        router.route_for_connection(&ctx, goodbye).await.unwrap();
18592        assert!(rx.try_recv().is_err());
18593        assert!(registry.get_module("aft").unwrap().is_none());
18594
18595        router
18596            .route_for_connection(&ctx, channel_request(channel, 13))
18597            .await
18598            .unwrap();
18599        let error_frame = rx.recv().await.unwrap();
18600        assert_eq!(error_frame.header.ty, FrameType::Error);
18601        assert_eq!(error_frame.header.channel, channel);
18602        let captured = crate::router::test_log::captured_logs(&logs);
18603        assert_eq!(
18604            captured
18605                .lines()
18606                .filter(|line| {
18607                    line.contains("module_id=aft")
18608                        && line.contains("reason=explicit_goodbye")
18609                        && line.contains("module registration ended")
18610                })
18611                .count(),
18612            1,
18613            "unexpected GOODBYE registry log: {captured}"
18614        );
18615    }
18616
18617    #[tokio::test]
18618    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18619        let registry = Arc::new(Registry::default());
18620        let handler = ControlHandler::new(registry).with_capability_config(
18621            [("prov".to_string(), true), ("cons".to_string(), true)],
18622            BTreeMap::new(),
18623        );
18624        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18625        register_capability_manifest(
18626            &handler,
18627            &provider_ctx,
18628            &mut provider_rx,
18629            capability_manifest("prov", &["thing/v1"], &[]),
18630            1,
18631        )
18632        .await;
18633        let mut consumer = capability_manifest("cons", &[], &[]);
18634        consumer.capabilities.as_mut().unwrap().requires.push(
18635            subc_protocol::manifest::CapabilityRequirement {
18636                capability: "thing/v1".to_string(),
18637                need: subc_protocol::manifest::CapabilityNeed::Required,
18638            },
18639        );
18640        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18641        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18642        assert_eq!(
18643            handler.capability_evaluator.verdict("cons", "thing/v1"),
18644            Some(CapabilityVerdict::Provided)
18645        );
18646        let (mut client_rx, _) = open_route_for_capability_test(
18647            &handler,
18648            &provider_ctx,
18649            &mut provider_rx,
18650            703,
18651            3,
18652            "prov",
18653            None,
18654        )
18655        .await;
18656        let goodbye =
18657            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18658        handler
18659            .handle_control_frame(&provider_ctx, goodbye)
18660            .await
18661            .unwrap();
18662        assert_eq!(
18663            handler.capability_evaluator.verdict("cons", "thing/v1"),
18664            Some(CapabilityVerdict::NeverProvided)
18665        );
18666        let closed = client_rx
18667            .try_recv()
18668            .expect("GOODBYE pushes route.closed before route GOODBYE");
18669        assert!(
18670            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18671            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18672        );
18673        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18674        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18675    }
18676
18677    struct RouteClosedFixture {
18678        handler: ControlHandler,
18679        #[cfg(unix)]
18680        supervisor: Supervisor,
18681        module_ctx: RouteCtx,
18682        #[cfg(unix)]
18683        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18684        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18685        route: Arc<crate::forwarding::RouteBinding>,
18686    }
18687
18688    async fn route_closed_fixture() -> RouteClosedFixture {
18689        let registry = Arc::new(Registry::default());
18690        let handler = ControlHandler::new(Arc::clone(&registry));
18691        #[cfg(unix)]
18692        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18693            .with_forwarding(Arc::clone(&handler.forwarding));
18694        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18695        register_capability_manifest(
18696            &handler,
18697            &module_ctx,
18698            &mut module_rx,
18699            capability_manifest("prov", &[], &[]),
18700            1,
18701        )
18702        .await;
18703        let (client_rx, bind) = open_route_for_capability_test(
18704            &handler,
18705            &module_ctx,
18706            &mut module_rx,
18707            702,
18708            2,
18709            "prov",
18710            None,
18711        )
18712        .await;
18713        let ModuleControlRequest::RouteBind {
18714            route_channel: channel,
18715            epoch: route_epoch,
18716            ..
18717        } = bind
18718        else {
18719            panic!("expected route.bind");
18720        };
18721        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18722            handler
18723                .forwarding
18724                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18725                .unwrap()
18726        else {
18727            panic!("the acknowledged route must be bound");
18728        };
18729        RouteClosedFixture {
18730            handler,
18731            #[cfg(unix)]
18732            supervisor,
18733            module_ctx,
18734            #[cfg(unix)]
18735            module_rx,
18736            client_rx,
18737            route,
18738        }
18739    }
18740
18741    impl RouteClosedFixture {
18742        #[cfg(unix)]
18743        async fn cut(&mut self) {
18744            let notices = async {
18745                let mut draining = self.module_rx.recv().await.unwrap();
18746                assert!(matches!(
18747                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18748                        &draining.body
18749                    )
18750                    .unwrap(),
18751                    subc_protocol::session::ModuleControlCommand::Draining {
18752                        reason: RouteCloseReason::Disable,
18753                        ..
18754                    }
18755                ));
18756                draining.flushed.take().unwrap().send(()).unwrap();
18757                let mut closing = self.client_rx.recv().await.unwrap();
18758                assert!(matches!(
18759                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18760                    ClientControlPush::RouteClosing {
18761                        reason: RouteCloseReason::Restart,
18762                        ..
18763                    }
18764                ));
18765                closing.flushed.take().unwrap().send(()).unwrap();
18766            };
18767            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18768            result.unwrap();
18769        }
18770
18771        fn disconnect(&mut self) -> ClientControlPush {
18772            self.handler
18773                .cleanup_connection(self.module_ctx.connection_id)
18774                .unwrap();
18775            let closed = self.client_rx.try_recv().unwrap();
18776            assert_eq!(closed.header.ty, FrameType::Push);
18777            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18778            assert!(matches!(
18779                &push,
18780                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18781                    if channels == &[self.route.client_channel]
18782            ));
18783            assert_eq!(
18784                self.client_rx.try_recv().unwrap().header.ty,
18785                FrameType::Goodbye
18786            );
18787            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18788            push
18789        }
18790    }
18791
18792    #[cfg(unix)]
18793    #[tokio::test(start_paused = true)]
18794    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18795        let mut fixture = route_closed_fixture().await;
18796        fixture.cut().await;
18797        assert!(matches!(
18798            fixture.disconnect(),
18799            ClientControlPush::RouteClosed {
18800                reason: RouteCloseReason::Restart,
18801                drained: true,
18802                ..
18803            }
18804        ));
18805    }
18806
18807    #[cfg(unix)]
18808    #[tokio::test(start_paused = true)]
18809    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18810        let mut fixture = route_closed_fixture().await;
18811        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18812        let started = tokio::time::Instant::now();
18813        fixture.cut().await;
18814        assert!(started.elapsed() >= Duration::from_secs(2));
18815        assert_eq!(fixture.route.flow.in_flight(), 1);
18816        assert!(matches!(
18817            fixture.disconnect(),
18818            ClientControlPush::RouteClosed {
18819                reason: RouteCloseReason::Restart,
18820                drained: false,
18821                ..
18822            }
18823        ));
18824    }
18825
18826    #[tokio::test]
18827    async fn module_connection_crash_reports_crash_and_not_drained() {
18828        let mut fixture = route_closed_fixture().await;
18829        // The server calls cleanup_connection on module EOF. Without a planned
18830        // daemon shutdown, that disconnect must remain a crash with no prior
18831        // route.closing notice, even when the route has no in-flight calls.
18832        assert!(matches!(
18833            fixture.disconnect(),
18834            ClientControlPush::RouteClosed {
18835                reason: RouteCloseReason::Crash,
18836                drained: false,
18837                ..
18838            }
18839        ));
18840    }
18841
18842    #[tokio::test]
18843    async fn dropping_router_connection_releases_registration() {
18844        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18845        let registry = Arc::new(Registry::default());
18846        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18847        let router = Router::with_control_handler(Arc::clone(&control));
18848        let connection = router.begin_connection();
18849        let connection_id = connection.id();
18850        let (ctx, mut rx) = route_ctx(connection_id);
18851
18852        router
18853            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18854            .await
18855            .unwrap();
18856        let response = rx.recv().await.unwrap();
18857        let ack = parse_ack(&response);
18858        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18859        assert!(registry.get_module("aft").unwrap().is_some());
18860
18861        drop(connection);
18862
18863        assert!(registry.get_module("aft").unwrap().is_none());
18864        assert_eq!(registry.active_registration_count().unwrap(), 0);
18865
18866        control
18867            .cleanup_connection(ConnectionId::new(u64::MAX))
18868            .unwrap();
18869        let captured = crate::router::test_log::captured_logs(&logs);
18870        println!("captured registry lifecycle logs:\n{captured}");
18871        let events: Vec<_> = captured
18872            .lines()
18873            .filter(|line| {
18874                line.contains("module registered module_id=aft ")
18875                    || line.contains("module registration ended")
18876            })
18877            .collect();
18878        assert_eq!(
18879            events.len(),
18880            2,
18881            "unexpected registry lifecycle logs: {captured}"
18882        );
18883        assert!(events[0].contains("module registered module_id=aft "));
18884        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18885        assert!(events[1].contains(&format!(
18886            "module_id=aft connection_id={}",
18887            connection_id.get()
18888        )));
18889        assert!(events[1].contains("reason=connection_closed"));
18890        assert!(events[1].contains("module registration ended"));
18891        assert_eq!(
18892            captured
18893                .lines()
18894                .filter(|line| line.contains("module registered module_id=aft "))
18895                .count(),
18896            1,
18897            "legacy registration admission line must appear once: {captured}"
18898        );
18899    }
18900
18901    #[tokio::test]
18902    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18903        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18904        let registry = Arc::new(Registry::default());
18905        let control = ControlHandler::new(Arc::clone(&registry));
18906        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18907        hello_via_sink(
18908            &control,
18909            &ctx,
18910            &mut rx,
18911            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18912        )
18913        .await;
18914
18915        let captured = crate::router::test_log::captured_logs(&logs);
18916        let admissions: Vec<_> = captured
18917            .lines()
18918            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18919            .collect();
18920        assert_eq!(
18921            admissions.len(),
18922            1,
18923            "legacy admission line must remain exactly once: {captured}"
18924        );
18925        assert!(admissions[0].contains("routable_provider=true"));
18926        assert!(admissions[0].contains("connection_id=777"));
18927    }
18928
18929    fn capability_manifest(
18930        module_id: &str,
18931        provides: &[&str],
18932        must_never_reach: &[&str],
18933    ) -> ModuleManifest {
18934        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18935        manifest.capabilities = Some(CapabilityDeclarations {
18936            provides: provides
18937                .iter()
18938                .map(|capability| (*capability).to_string())
18939                .collect(),
18940            requires: Vec::new(),
18941            must_never_reach: must_never_reach
18942                .iter()
18943                .map(|capability| (*capability).to_string())
18944                .collect(),
18945        });
18946        manifest
18947    }
18948
18949    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18950        Frame::build(
18951            FrameType::Hello,
18952            control_flags(),
18953            0,
18954            0,
18955            corr,
18956            serde_json::to_vec(&ModuleHelloBody {
18957                protocol_ver: manifest.protocol_ver,
18958                manifest,
18959                control_ops: None,
18960                launch_nonce: None,
18961            })
18962            .expect("capability test HELLO serializes"),
18963        )
18964        .expect("capability test HELLO frame builds")
18965    }
18966
18967    fn catalog_update_with_capabilities_frame(
18968        corr: u64,
18969        capabilities: CapabilityDeclarations,
18970    ) -> Frame {
18971        Frame::build(
18972            FrameType::Request,
18973            control_flags(),
18974            0,
18975            0,
18976            corr,
18977            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18978                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18979                capabilities: Some(capabilities),
18980                ready: None,
18981            })
18982            .expect("capability catalog.update serializes"),
18983        )
18984        .expect("capability catalog.update frame builds")
18985    }
18986
18987    async fn register_capability_manifest(
18988        handler: &ControlHandler,
18989        ctx: &RouteCtx,
18990        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18991        manifest: ModuleManifest,
18992        corr: u64,
18993    ) {
18994        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
18995    }
18996
18997    async fn open_route_for_capability_test(
18998        handler: &ControlHandler,
18999        target_ctx: &RouteCtx,
19000        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
19001        client_connection_id: u64,
19002        corr: u64,
19003        target_module_id: &str,
19004        consumer_identity: Option<ConsumerIdentity>,
19005    ) -> (
19006        mpsc::Receiver<crate::router::OutboundFrame>,
19007        ModuleControlRequest,
19008    ) {
19009        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
19010        let route_handler = handler.clone();
19011        let target_module_id = target_module_id.to_string();
19012        let route_task = tokio::spawn(async move {
19013            route_handler
19014                .handle_control_frame(
19015                    &client_ctx,
19016                    route_open_frame_with_admission_facts(
19017                        corr,
19018                        &target_module_id,
19019                        unique_project_root("admission-facts"),
19020                        consumer_identity,
19021                        None,
19022                    ),
19023                )
19024                .await
19025                .expect("capability test route.open succeeds")
19026        });
19027        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
19028            .await
19029            .expect("capability test route.open must reach route.bind")
19030            .expect("target control receiver stays open");
19031        let bind_request: ModuleControlRequest =
19032            serde_json::from_slice(&bind.body).expect("route.bind decodes");
19033        handler
19034            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
19035            .await
19036            .expect("capability test route.bind ACK succeeds");
19037        assert!(route_task.await.expect("route.open task joins").is_empty());
19038        let opened = client_rx
19039            .recv()
19040            .await
19041            .expect("successful route.open publishes a response");
19042        assert!(matches!(
19043            serde_json::from_slice::<ClientControlResponse>(&opened.body),
19044            Ok(ClientControlResponse::RouteOpen { .. })
19045        ));
19046        (client_rx, bind_request)
19047    }
19048
19049    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
19050        assert_eq!(frame.header.ty, FrameType::Push);
19051        assert_eq!(frame.header.channel, 0);
19052        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
19053            .expect("route.closed control push decodes");
19054        let ClientControlPush::RouteClosed { channels, .. } = &push else {
19055            panic!("expected route.closed");
19056        };
19057        assert_eq!(channels.len(), 1, "exactly one violating route closed");
19058        let closed_channel = channels[0];
19059        let channels = channels.clone();
19060        assert_eq!(
19061            push,
19062            ClientControlPush::RouteClosed {
19063                module_id: target_module_id.to_string(),
19064                channels,
19065                reason: RouteCloseReason::CapabilityDenied,
19066                drained: false,
19067                abandoned: 0,
19068                excluded_subscriptions: 0,
19069                terminal: Some(false),
19070            }
19071        );
19072        closed_channel
19073    }
19074
19075    #[tokio::test]
19076    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
19077        let registry = Arc::new(Registry::default());
19078        let forwarding = Arc::new(ForwardingTable::default());
19079        let supervisor = SupervisorHandle::new();
19080        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19081        let handler =
19082            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19083                .with_supervisor(supervisor);
19084        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19085        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19086        register_capability_manifest(
19087            &handler,
19088            &target_ctx,
19089            &mut target_rx,
19090            capability_manifest("target", &["credentials-provider/v1"], &[]),
19091            1,
19092        )
19093        .await;
19094        register_capability_manifest(
19095            &handler,
19096            &opener_ctx,
19097            &mut opener_rx,
19098            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19099            2,
19100        )
19101        .await;
19102
19103        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19104        let replies = handler
19105            .handle_control_frame(
19106                &client_ctx,
19107                route_open_frame_with_admission_facts(
19108                    3,
19109                    "target",
19110                    unique_project_root("admission-facts"),
19111                    Some(ConsumerIdentity {
19112                        module_id: "opener".to_string(),
19113                        launch_nonce: "opener-nonce".to_string(),
19114                    }),
19115                    None,
19116                ),
19117            )
19118            .await
19119            .expect("denied route.open returns a typed frame");
19120        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19121        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19122        assert!(
19123            target_rx.try_recv().is_err(),
19124            "forbidden route.open must not relay route.bind"
19125        );
19126    }
19127
19128    #[tokio::test]
19129    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19130        let registry = Arc::new(Registry::default());
19131        let forwarding = Arc::new(ForwardingTable::default());
19132        let supervisor = SupervisorHandle::new();
19133        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19134        let handler =
19135            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19136                .with_supervisor(supervisor);
19137        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19138        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19139        register_capability_manifest(
19140            &handler,
19141            &target_ctx,
19142            &mut target_rx,
19143            capability_manifest("target", &["credentials-provider/v1"], &[]),
19144            1,
19145        )
19146        .await;
19147        register_capability_manifest(
19148            &handler,
19149            &old_opener_ctx,
19150            &mut old_opener_rx,
19151            capability_manifest("opener", &[], &[]),
19152            2,
19153        )
19154        .await;
19155        let (mut client_rx, _) = open_route_for_capability_test(
19156            &handler,
19157            &target_ctx,
19158            &mut target_rx,
19159            712,
19160            3,
19161            "target",
19162            Some(ConsumerIdentity {
19163                module_id: "opener".to_string(),
19164                launch_nonce: "opener-nonce".to_string(),
19165            }),
19166        )
19167        .await;
19168        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19169
19170        handler
19171            .cleanup_connection(old_opener_ctx.connection_id)
19172            .expect("old opener registration cleans up");
19173        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19174        register_capability_manifest(
19175            &handler,
19176            &new_opener_ctx,
19177            &mut new_opener_rx,
19178            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19179            4,
19180        )
19181        .await;
19182
19183        let closed_channel = assert_capability_denied_push(
19184            client_rx
19185                .try_recv()
19186                .expect("HELLO deny addition must emit route.closed")
19187                .frame,
19188            "target",
19189        );
19190        let goodbye = client_rx
19191            .try_recv()
19192            .expect("HELLO deny addition must send the client a route GOODBYE")
19193            .frame;
19194        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19195        assert_eq!(goodbye.header.channel, closed_channel);
19196        assert_ne!(goodbye.header.channel, 0);
19197        assert_ne!(goodbye.header.epoch, 0);
19198        assert!(client_rx.try_recv().is_err());
19199        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19200        assert!(matches!(
19201            target_rx.try_recv(),
19202            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19203        ));
19204    }
19205
19206    #[tokio::test]
19207    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19208        let registry = Arc::new(Registry::default());
19209        let forwarding = Arc::new(ForwardingTable::default());
19210        let supervisor = SupervisorHandle::new();
19211        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19212        let handler =
19213            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19214                .with_supervisor(supervisor);
19215        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19216        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19217        register_capability_manifest(
19218            &handler,
19219            &target_ctx,
19220            &mut target_rx,
19221            capability_manifest("target", &[], &[]),
19222            1,
19223        )
19224        .await;
19225        register_capability_manifest(
19226            &handler,
19227            &opener_ctx,
19228            &mut opener_rx,
19229            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19230            2,
19231        )
19232        .await;
19233        let (mut client_rx, _) = open_route_for_capability_test(
19234            &handler,
19235            &target_ctx,
19236            &mut target_rx,
19237            722,
19238            3,
19239            "target",
19240            Some(ConsumerIdentity {
19241                module_id: "opener".to_string(),
19242                launch_nonce: "opener-nonce".to_string(),
19243            }),
19244        )
19245        .await;
19246        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19247
19248        let replies = handler
19249            .handle_control_frame(
19250                &target_ctx,
19251                catalog_update_with_capabilities_frame(
19252                    4,
19253                    CapabilityDeclarations {
19254                        provides: vec!["credentials-provider/v1".to_string()],
19255                        requires: Vec::new(),
19256                        must_never_reach: Vec::new(),
19257                    },
19258                ),
19259            )
19260            .await
19261            .expect("claim catalog.update succeeds");
19262        assert!(matches!(
19263            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19264            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19265        ));
19266        let closed_channel = assert_capability_denied_push(
19267            client_rx
19268                .try_recv()
19269                .expect("claim addition must emit route.closed")
19270                .frame,
19271            "target",
19272        );
19273        let goodbye = client_rx
19274            .try_recv()
19275            .expect("claim addition must send the client a route GOODBYE")
19276            .frame;
19277        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19278        assert_eq!(goodbye.header.channel, closed_channel);
19279        assert_ne!(goodbye.header.channel, 0);
19280        assert_ne!(goodbye.header.epoch, 0);
19281        assert!(client_rx.try_recv().is_err());
19282        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19283        assert!(matches!(
19284            target_rx.try_recv(),
19285            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19286        ));
19287    }
19288
19289    #[tokio::test]
19290    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19291        let registry = Arc::new(Registry::default());
19292        let forwarding = Arc::new(ForwardingTable::default());
19293        let supervisor = SupervisorHandle::new();
19294        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19295        let handler =
19296            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19297                .with_supervisor(supervisor);
19298        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19299        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19300        register_capability_manifest(
19301            &handler,
19302            &target_ctx,
19303            &mut target_rx,
19304            capability_manifest("target", &["credentials-provider/v1"], &[]),
19305            1,
19306        )
19307        .await;
19308        register_capability_manifest(
19309            &handler,
19310            &opener_ctx,
19311            &mut opener_rx,
19312            capability_manifest("opener", &[], &[]),
19313            2,
19314        )
19315        .await;
19316        let (mut client_rx, _) = open_route_for_capability_test(
19317            &handler,
19318            &target_ctx,
19319            &mut target_rx,
19320            732,
19321            3,
19322            "target",
19323            Some(ConsumerIdentity {
19324                module_id: "opener".to_string(),
19325                launch_nonce: "opener-nonce".to_string(),
19326            }),
19327        )
19328        .await;
19329        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19330
19331        handler
19332            .handle_control_frame(
19333                &target_ctx,
19334                catalog_update_with_capabilities_frame(
19335                    4,
19336                    CapabilityDeclarations {
19337                        provides: Vec::new(),
19338                        requires: Vec::new(),
19339                        must_never_reach: Vec::new(),
19340                    },
19341                ),
19342            )
19343            .await
19344            .expect("claim removal catalog.update succeeds");
19345        assert_eq!(
19346            forwarding.active_binding_count().unwrap(),
19347            1,
19348            "removing an attested target claim must leave the route census unchanged"
19349        );
19350        assert!(
19351            client_rx.try_recv().is_err(),
19352            "claim removal must not emit route.closed or a client route GOODBYE"
19353        );
19354        assert!(
19355            target_rx.try_recv().is_err(),
19356            "claim removal must not send the target a route GOODBYE"
19357        );
19358    }
19359
19360    /// A direct client may open a route to a denied capability provider; this
19361    /// policy applies only to attested supervised module origins, not to direct clients.
19362    #[tokio::test]
19363    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19364        let registry = Arc::new(Registry::default());
19365        let forwarding = Arc::new(ForwardingTable::default());
19366        let supervisor = SupervisorHandle::new();
19367        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19368        let handler =
19369            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19370                .with_supervisor(supervisor);
19371        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19372        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19373        register_capability_manifest(
19374            &handler,
19375            &target_ctx,
19376            &mut target_rx,
19377            capability_manifest("target", &["credentials-provider/v1"], &[]),
19378            1,
19379        )
19380        .await;
19381        register_capability_manifest(
19382            &handler,
19383            &opener_ctx,
19384            &mut opener_rx,
19385            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19386            2,
19387        )
19388        .await;
19389
19390        let (_client_rx, bind) = open_route_for_capability_test(
19391            &handler,
19392            &target_ctx,
19393            &mut target_rx,
19394            742,
19395            3,
19396            "target",
19397            None,
19398        )
19399        .await;
19400        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19401            panic!("direct scope-honesty route must bind");
19402        };
19403        assert_eq!(principal, Some(Principal::Direct));
19404        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19405    }
19406
19407    /// A module that denies a capability receives no self-route exemption when it
19408    /// also attestedly provides that capability.
19409    #[tokio::test]
19410    async fn must_never_reach_self_route_is_capability_forbidden() {
19411        let registry = Arc::new(Registry::default());
19412        let forwarding = Arc::new(ForwardingTable::default());
19413        let supervisor = SupervisorHandle::new();
19414        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19415        let handler =
19416            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19417                .with_supervisor(supervisor);
19418        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19419        register_capability_manifest(
19420            &handler,
19421            &self_ctx,
19422            &mut self_rx,
19423            capability_manifest(
19424                "self-provider",
19425                &["credentials-provider/v1"],
19426                &["credentials-provider/v1"],
19427            ),
19428            1,
19429        )
19430        .await;
19431
19432        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19433        let replies = handler
19434            .handle_control_frame(
19435                &client_ctx,
19436                route_open_frame_with_admission_facts(
19437                    2,
19438                    "self-provider",
19439                    unique_project_root("admission-facts"),
19440                    Some(ConsumerIdentity {
19441                        module_id: "self-provider".to_string(),
19442                        launch_nonce: "self-nonce".to_string(),
19443                    }),
19444                    None,
19445                ),
19446            )
19447            .await
19448            .expect("self-route refusal returns a typed frame");
19449        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19450        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19451        assert!(
19452            self_rx.try_recv().is_err(),
19453            "self denial must not relay route.bind"
19454        );
19455    }
19456
19457    #[test]
19458    fn unsupported_channel_zero_frame_returns_error() {
19459        let handler = ControlHandler::default();
19460        let request = Frame::build(
19461            FrameType::Request,
19462            control_flags(),
19463            0,
19464            0,
19465            21,
19466            b"opaque".to_vec(),
19467        )
19468        .unwrap();
19469
19470        let response = handler
19471            .handle_control(ConnectionId::new(1), request)
19472            .unwrap();
19473
19474        assert_eq!(response[0].header.ty, FrameType::Error);
19475        assert_eq!(
19476            parse_error(&response[0])["code"],
19477            "unsupported_control_frame"
19478        );
19479    }
19480
19481    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19482    /// a swap is not wired yet, so the candidate is registered here directly
19483    /// into the registry and forwarding candidate slots, the way the swap's
19484    /// HELLO admission will.
19485    mod swap {
19486        use super::*;
19487
19488        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19489        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19490
19491        struct Swap {
19492            registry: Arc<Registry>,
19493            forwarding: Arc<ForwardingTable>,
19494            handler: ControlHandler,
19495            incumbent_ctx: RouteCtx,
19496            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19497            candidate_ctx: RouteCtx,
19498            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19499        }
19500
19501        async fn swap_with_incumbent() -> Swap {
19502            let registry = Arc::new(Registry::default());
19503            let forwarding = Arc::new(ForwardingTable::default());
19504            let handler =
19505                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19506            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19507            hello_via_sink(
19508                &handler,
19509                &incumbent_ctx,
19510                &mut incumbent_rx,
19511                hello_frame("aft", PROTOCOL_VERSION, 7),
19512            )
19513            .await;
19514            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19515            Swap {
19516                registry,
19517                forwarding,
19518                handler,
19519                incumbent_ctx,
19520                incumbent_rx,
19521                candidate_ctx,
19522                candidate_rx,
19523            }
19524        }
19525
19526        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19527            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19528            candidate_manifest.ready = ready;
19529            let registration = swap
19530                .registry
19531                .register_candidate_with_control_ops(
19532                    candidate_manifest,
19533                    PROTOCOL_VERSION,
19534                    CANDIDATE,
19535                    module_baseline_control_ops(),
19536                )
19537                .unwrap();
19538            swap.forwarding
19539                .register_candidate_module_connection(
19540                    CANDIDATE,
19541                    "aft".to_string(),
19542                    PROTOCOL_VERSION,
19543                    manifest_concurrency(&registration.manifest),
19544                    swap.candidate_ctx.egress.clone(),
19545                )
19546                .unwrap();
19547        }
19548
19549        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19550            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19551            swap.registry.promote_candidate("aft").unwrap().unwrap();
19552            cutover.incumbent.unwrap()
19553        }
19554
19555        /// A swap candidate's HELLO reserves its candidate registry entry
19556        /// before installing its candidate forwarding endpoint. The swap
19557        /// supervisor promotes a ready candidate as soon as it reads it as
19558        /// registered, and promotion cuts forwarding over to the candidate
19559        /// endpoint, so the lookup the supervisor reads
19560        /// (`Registry::published_registration`) must not return the candidate
19561        /// until that endpoint exists. Otherwise the cutover finds no candidate
19562        /// endpoint and the swap fails as if the candidate had disconnected.
19563        #[tokio::test]
19564        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19565            let mut swap = swap_with_incumbent().await;
19566            let hold = Arc::new(std::sync::Barrier::new(2));
19567            let handler = swap
19568                .handler
19569                .clone()
19570                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19571            handler
19572                .supervisor
19573                .open_swap("aft", "candidate-nonce".to_string());
19574            let hello = {
19575                let handler = handler.clone();
19576                let candidate_ctx = swap.candidate_ctx.clone();
19577                std::thread::spawn(move || {
19578                    handler
19579                        .handle_hello(
19580                            candidate_ctx.connection_id,
19581                            Some(candidate_ctx.egress.clone()),
19582                            hello_frame_with_nonce(
19583                                "aft",
19584                                PROTOCOL_VERSION,
19585                                8,
19586                                Some("candidate-nonce"),
19587                            ),
19588                        )
19589                        .unwrap()
19590                })
19591            };
19592
19593            hold.wait();
19594            // Parked: the candidate slot is claimed but not published, and
19595            // forwarding has no candidate endpoint.
19596            assert!(swap
19597                .registry
19598                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19599                .unwrap()
19600                .is_some());
19601            assert!(swap
19602                .registry
19603                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19604                .unwrap()
19605                .is_none());
19606            assert!(swap
19607                .forwarding
19608                .module_endpoint_for_connection(CANDIDATE)
19609                .unwrap()
19610                .is_none());
19611
19612            hold.wait();
19613            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19614            assert_eq!(
19615                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19616                FrameType::HelloAck
19617            );
19618            let published = swap
19619                .registry
19620                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19621                .unwrap()
19622                .expect("candidate is published once its HELLO completes");
19623            assert_eq!(published.connection_id, CANDIDATE);
19624            assert!(swap
19625                .forwarding
19626                .module_endpoint_for_connection(CANDIDATE)
19627                .unwrap()
19628                .is_some());
19629        }
19630
19631        #[tokio::test]
19632        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19633            let mut swap = swap_with_incumbent().await;
19634            let hold = Arc::new(std::sync::Barrier::new(2));
19635            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19636            swap.handler
19637                .supervisor
19638                .open_swap("aft", "candidate-nonce".to_string());
19639            let hello = {
19640                let handler = swap.handler.clone();
19641                let candidate_ctx = swap.candidate_ctx.clone();
19642                std::thread::spawn(move || {
19643                    handler
19644                        .handle_hello(
19645                            CANDIDATE,
19646                            Some(candidate_ctx.egress),
19647                            hello_frame_with_nonce(
19648                                "aft",
19649                                PROTOCOL_VERSION,
19650                                8,
19651                                Some("candidate-nonce"),
19652                            ),
19653                        )
19654                        .unwrap()
19655                })
19656            };
19657            hold.wait();
19658            assert_eq!(
19659                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19660                FrameType::HelloAck
19661            );
19662            let reader_registry = Arc::clone(&swap.registry);
19663            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19664                reader_registry
19665                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19666                    .unwrap()
19667            });
19668            assert!(hello.join().unwrap().is_empty());
19669            assert_eq!(
19670                published
19671                    .expect("ACK makes candidate publication visible")
19672                    .connection_id,
19673                CANDIDATE
19674            );
19675            assert_eq!(
19676                swap.registry.generation().unwrap(),
19677                1,
19678                "candidate is not a second catalog entry"
19679            );
19680        }
19681
19682        #[tokio::test]
19683        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19684            let mut swap = swap_with_incumbent().await;
19685            let hold = Arc::new(std::sync::Barrier::new(2));
19686            let handler = swap
19687                .handler
19688                .clone()
19689                .with_hello_registry_to_forwarding_hold(hold.clone());
19690            handler
19691                .supervisor
19692                .open_swap("aft", "candidate-nonce".into());
19693            let hello = {
19694                let handler = handler.clone();
19695                let ctx = swap.candidate_ctx.clone();
19696                std::thread::spawn(move || {
19697                    handler
19698                        .handle_hello(
19699                            CANDIDATE,
19700                            Some(ctx.egress),
19701                            hello_frame_with_nonce(
19702                                "aft",
19703                                PROTOCOL_VERSION,
19704                                8,
19705                                Some("candidate-nonce"),
19706                            ),
19707                        )
19708                        .unwrap()
19709                })
19710            };
19711            hold.wait();
19712            assert_eq!(
19713                swap.registry
19714                    .deregister_connection(CANDIDATE)
19715                    .unwrap()
19716                    .len(),
19717                1
19718            );
19719            hold.wait();
19720            assert!(hello.join().unwrap().is_empty());
19721            assert_eq!(
19722                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19723                FrameType::HelloAck
19724            );
19725            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19726            assert_eq!(
19727                handler
19728                    .supervisor
19729                    .swap_hello_admission("aft", Some("candidate-nonce")),
19730                SwapHelloAdmission::Candidate,
19731                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19732            );
19733            handler.supervisor.close_swap("aft");
19734        }
19735
19736        fn keyed_total(counters: &Value, key: &str) -> u64 {
19737            counters[key]
19738                .as_object()
19739                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19740                .unwrap_or(0)
19741        }
19742
19743        #[tokio::test]
19744        async fn replacement_logs_old_end_and_new_admission_once() {
19745            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19746            let mut swap = swap_with_incumbent().await;
19747            swap.handler
19748                .supervisor
19749                .open_swap("aft", "candidate-nonce".to_string());
19750            hello_via_sink(
19751                &swap.handler,
19752                &swap.candidate_ctx,
19753                &mut swap.candidate_rx,
19754                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19755            )
19756            .await;
19757            cutover(&swap);
19758            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19759
19760            let captured = crate::router::test_log::captured_logs(&logs);
19761            println!("captured replacement registry logs:\n{captured}");
19762            let new_admissions: Vec<_> = captured
19763                .lines()
19764                .filter(|line| {
19765                    line.contains("connection_id=40")
19766                        && line.contains("swap candidate registered; not routable until cutover")
19767                })
19768                .collect();
19769            assert_eq!(
19770                new_admissions.len(),
19771                1,
19772                "unexpected admission logs: {captured}"
19773            );
19774            assert!(new_admissions[0].contains("module_id=aft"));
19775            assert!(new_admissions[0].contains("connection_id=40"));
19776            assert!(
19777                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19778            );
19779            assert!(new_admissions[0].contains("ready=true"));
19780
19781            let old_admissions: Vec<_> = captured
19782                .lines()
19783                .filter(|line| {
19784                    line.contains("module registered module_id=aft ")
19785                        && line.contains("connection_id=30")
19786                })
19787                .collect();
19788            assert_eq!(
19789                old_admissions.len(),
19790                1,
19791                "unexpected incumbent admission: {captured}"
19792            );
19793
19794            let old_ends: Vec<_> = captured
19795                .lines()
19796                .filter(|line| {
19797                    line.contains("connection_id=30") && line.contains("module registration ended")
19798                })
19799                .collect();
19800            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19801            assert!(old_ends[0].contains("module_id=aft"));
19802            assert!(old_ends[0].contains("connection_id=30"));
19803            assert!(old_ends[0].contains("reason=replaced"));
19804            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19805            assert_eq!(
19806                captured
19807                    .lines()
19808                    .filter(|line| line.contains("module registration promoted"))
19809                    .count(),
19810                1,
19811                "unexpected promotion logs: {captured}"
19812            );
19813        }
19814
19815        /// An ack from the incumbent for a bind it was sent before cutover,
19816        /// arriving before the incumbent is drained. The incumbent is the live
19817        /// connection carrying every other client's routes, so the ack must
19818        /// not end it: the waiting client is told to retry, the reservation is
19819        /// given back, and the incumbent is told to drop just that binding.
19820        #[tokio::test]
19821        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19822            let mut swap = swap_with_incumbent().await;
19823            let handler = swap.handler.clone();
19824
19825            // A co-tenant route, bound on the incumbent before the swap.
19826            let cotenant = ConnectionId::new(31);
19827            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19828            let (cotenant_task, cotenant_bind) = relay_route_open(
19829                &handler,
19830                cotenant,
19831                &cotenant_ctx.egress,
19832                &mut swap.incumbent_rx,
19833                100,
19834                "aft",
19835                "swap-cotenant",
19836            )
19837            .await;
19838            handler
19839                .handle_control_frame(
19840                    &swap.incumbent_ctx,
19841                    route_bind_ack(cotenant_bind.header.corr),
19842                )
19843                .await
19844                .unwrap();
19845            assert!(cotenant_task.await.unwrap().is_empty());
19846            let (cotenant_channel, cotenant_epoch) =
19847                published_route(&cotenant_rx.recv().await.unwrap());
19848
19849            // A second route.open, relayed to the incumbent and not yet acked.
19850            let caller = ConnectionId::new(32);
19851            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19852            let (caller_task, caller_bind) = relay_route_open(
19853                &handler,
19854                caller,
19855                &caller_ctx.egress,
19856                &mut swap.incumbent_rx,
19857                101,
19858                "aft",
19859                "swap-caller",
19860            )
19861            .await;
19862            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19863
19864            register_candidate(&swap, None);
19865            cutover(&swap);
19866
19867            // The incumbent acks after promotion and before any drain.
19868            let ack = handler
19869                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19870                .await;
19871            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19872            if module_loop_error.is_some() {
19873                // What the connection loop does with an untranslated router
19874                // error: end the connection, releasing every route on it.
19875                handler.cleanup_connection(INCUMBENT).unwrap();
19876            }
19877
19878            // 1. The incumbent's other routes survive.
19879            assert!(
19880                cotenant_rx.try_recv().is_err(),
19881                "the co-tenant route on the incumbent was torn down by one late ack: \
19882                 {module_loop_error:?}"
19883            );
19884            assert!(matches!(
19885                swap.forwarding
19886                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19887                    .unwrap(),
19888                DataRoute::Client(DataRouteState::Bound(_))
19889            ));
19890            assert_eq!(module_loop_error, None);
19891            assert!(swap
19892                .registry
19893                .get_module_by_connection(INCUMBENT)
19894                .unwrap()
19895                .is_some());
19896
19897            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19898            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19899                .await
19900                .expect("the incumbent is told to drop the abandoned binding")
19901                .unwrap()
19902                .frame;
19903            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19904            assert_eq!(goodbye.header.channel, abandoned_channel);
19905            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19906            assert!(swap.incumbent_rx.try_recv().is_err());
19907
19908            // 3. The waiting client gets a retryable refusal and no route.
19909            let response = caller_task.await.unwrap();
19910            assert_eq!(response.len(), 1);
19911            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19912            assert!(caller_rx.try_recv().is_err());
19913
19914            // 4. The reservation pair is given back, and the pending bind
19915            //    settled exactly once: one accepted open (the co-tenant) and one
19916            //    refused open (the caller), nothing counted twice.
19917            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19918            let counters = handler.counters().snapshot();
19919            assert_eq!(
19920                keyed_total(&counters, "route_open_accepted_by_principal"),
19921                1
19922            );
19923            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19924            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19925        }
19926
19927        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19928        /// id would resolve to the promoted candidate and every new route.open
19929        /// would be refused as reloading, leaving neither process routable.
19930        #[tokio::test]
19931        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19932            let mut swap = swap_with_incumbent().await;
19933            register_candidate(&swap, None);
19934            let incumbent = cutover(&swap);
19935            swap.forwarding
19936                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19937                .unwrap()
19938                .expect("the incumbent is still registered");
19939
19940            let client = ConnectionId::new(33);
19941            let (client_ctx, mut client_rx) = route_ctx(client);
19942            let route_handler = swap.handler.clone();
19943            let open_ctx = RouteCtx {
19944                connection_id: client,
19945                egress: client_ctx.egress.clone(),
19946            };
19947            let mut route_task = tokio::spawn(async move {
19948                route_handler
19949                    .handle_control_frame(
19950                        &open_ctx,
19951                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19952                    )
19953                    .await
19954                    .unwrap()
19955            });
19956            let bind = tokio::select! {
19957                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19958                response = &mut route_task => {
19959                    let response = response.unwrap();
19960                    panic!(
19961                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19962                        parse_error(&response[0])["code"]
19963                    );
19964                }
19965            };
19966            swap.handler
19967                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19968                .await
19969                .unwrap();
19970            assert!(route_task.await.unwrap().is_empty());
19971            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19972            match swap
19973                .forwarding
19974                .lookup_data_route(client, channel, epoch)
19975                .unwrap()
19976            {
19977                DataRoute::Client(DataRouteState::Bound(route)) => {
19978                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19979                }
19980                other => panic!("expected a bound route on the candidate, got {other:?}"),
19981            }
19982            assert!(swap.incumbent_rx.try_recv().is_err());
19983        }
19984
19985        /// A candidate declares itself ready with `catalog.update` on its own
19986        /// connection. If the connection-keyed registry lookups searched only the
19987        /// active slot, this would answer `not_registered` and the candidate
19988        /// would never become ready.
19989        #[tokio::test]
19990        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
19991            let swap = swap_with_incumbent().await;
19992            register_candidate(&swap, Some(false));
19993            let update = Frame::build(
19994                FrameType::Request,
19995                control_flags(),
19996                0,
19997                0,
19998                55,
19999                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
20000                    provides: manifest("aft", PROTOCOL_VERSION).provides,
20001                    capabilities: None,
20002                    ready: Some(true),
20003                })
20004                .unwrap(),
20005            )
20006            .unwrap();
20007
20008            let replies = swap
20009                .handler
20010                .handle_control_frame(&swap.candidate_ctx, update)
20011                .await
20012                .unwrap();
20013
20014            assert_eq!(replies.len(), 1);
20015            assert_eq!(
20016                replies[0].header.ty,
20017                FrameType::Response,
20018                "candidate catalog.update was refused: {:?}",
20019                serde_json::from_slice::<Value>(&replies[0].body).ok()
20020            );
20021            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
20022            assert_eq!(
20023                swap.registry
20024                    .get_module("aft")
20025                    .unwrap()
20026                    .unwrap()
20027                    .connection_id,
20028                INCUMBENT
20029            );
20030        }
20031    }
20032
20033    /// The HELLO gate while the supervisor has a swap open: only the nonce it
20034    /// minted for the candidate admits a second process, into the candidate
20035    /// slot, and that check runs ahead of the reserved-module gate.
20036    mod swap_admission {
20037        use super::*;
20038
20039        const INCUMBENT_NONCE: &str = "incumbent-nonce";
20040        const CANDIDATE_NONCE: &str = "candidate-nonce";
20041
20042        fn handler_with_incumbent(
20043            module_id: &str,
20044            reserved: bool,
20045        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
20046            let registry = Arc::new(Registry::default());
20047            let supervisor = SupervisorHandle::new();
20048            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
20049            if reserved {
20050                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
20051            }
20052            let handler =
20053                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
20054            let incumbent = handler
20055                .handle_control(
20056                    ConnectionId::new(1),
20057                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
20058                )
20059                .unwrap();
20060            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
20061            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
20062            (registry, supervisor, handler)
20063        }
20064
20065        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
20066        /// admits every nonce, so while a swap is open the swap gate is the only
20067        /// thing between a key-holder and the candidate slot. A nonce the
20068        /// supervisor did not mint, or none at all, is refused, and neither the
20069        /// incumbent's registration nor the candidate slot moves.
20070        #[test]
20071        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
20072            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
20073
20074            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
20075                let replies = handler
20076                    .handle_control(
20077                        ConnectionId::new(connection),
20078                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
20079                    )
20080                    .unwrap();
20081                assert_eq!(replies[0].header.ty, FrameType::Error);
20082                assert_eq!(
20083                    parse_error(&replies[0])["code"],
20084                    "swap_token_invalid",
20085                    "nonce {nonce:?}"
20086                );
20087            }
20088            assert!(registry.get_candidate("aft").unwrap().is_none());
20089            assert_eq!(
20090                registry.get_module("aft").unwrap().unwrap().connection_id,
20091                ConnectionId::new(1)
20092            );
20093
20094            // Control: the minted token is admitted, into the candidate slot,
20095            // and only once.
20096            let admitted = handler
20097                .handle_control(
20098                    ConnectionId::new(4),
20099                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20100                )
20101                .unwrap();
20102            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20103            assert_eq!(
20104                registry
20105                    .get_candidate("aft")
20106                    .unwrap()
20107                    .unwrap()
20108                    .connection_id,
20109                ConnectionId::new(4)
20110            );
20111            assert_eq!(
20112                registry.get_module("aft").unwrap().unwrap().connection_id,
20113                ConnectionId::new(1),
20114                "the candidate must not take the active slot"
20115            );
20116            let replayed = handler
20117                .handle_control(
20118                    ConnectionId::new(5),
20119                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20120                )
20121                .unwrap();
20122            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20123
20124            // The case only this gate covers: the incumbent has died mid-swap,
20125            // so its duplicate refusal is gone too, and without the gate a
20126            // key-holder would take the id's ACTIVE slot.
20127            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20128            let squatter = handler
20129                .handle_control(
20130                    ConnectionId::new(6),
20131                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20132                )
20133                .unwrap();
20134            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20135            assert!(
20136                registry.get_module("aft").unwrap().is_none(),
20137                "a squatter took the active slot of an id being swapped"
20138            );
20139        }
20140
20141        /// Design mutation arm (iii). A reserved module's candidate presents a
20142        /// nonce the reserved gate has never seen (that gate holds the
20143        /// incumbent's), so the swap gate must run first or the candidate is
20144        /// refused `reserved_module` and a reserved module can never be swapped.
20145        #[test]
20146        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20147            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20148
20149            let replies = handler
20150                .handle_control(
20151                    ConnectionId::new(2),
20152                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20153                )
20154                .unwrap();
20155
20156            assert_eq!(
20157                replies[0].header.ty,
20158                FrameType::HelloAck,
20159                "reserved candidate refused: {:?}",
20160                serde_json::from_slice::<Value>(&replies[0].body).ok()
20161            );
20162            assert_eq!(
20163                registry
20164                    .get_candidate("vault")
20165                    .unwrap()
20166                    .unwrap()
20167                    .connection_id,
20168                ConnectionId::new(2)
20169            );
20170        }
20171
20172        /// With no swap open the gate is inert: the incumbent's reserved gate
20173        /// and duplicate refusal behave exactly as before.
20174        #[test]
20175        fn without_an_open_swap_the_ordinary_gates_decide() {
20176            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20177            supervisor.close_swap("vault");
20178
20179            let candidate = handler
20180                .handle_control(
20181                    ConnectionId::new(2),
20182                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20183                )
20184                .unwrap();
20185            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20186            let duplicate = handler
20187                .handle_control(
20188                    ConnectionId::new(3),
20189                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20190                )
20191                .unwrap();
20192            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20193            assert!(registry.get_candidate("vault").unwrap().is_none());
20194        }
20195    }
20196
20197    /// `scope.sync` and `scope.describe` through the real control handler: who
20198    /// may sync is decided by the registration and launch nonce of the module
20199    /// connection, never by the request body.
20200    mod scopes {
20201        mod close_reasons {
20202            include!("route_close_reason_tests.rs");
20203        }
20204        mod idle_tests {
20205            use super::*;
20206            include!("scope_idle_tests.rs");
20207        }
20208        mod route_open_timings {
20209            use super::*;
20210            include!("route_open_timing_tests.rs");
20211        }
20212        mod route_open_refusal_log {
20213            use super::*;
20214            include!("route_open_refusal_log_tests.rs");
20215        }
20216        mod activity {
20217            include!("activity_scope_tests.rs");
20218        }
20219        mod delta {
20220            include!("scope_handler_delta_tests.rs");
20221        }
20222        mod watch {
20223            include!("scope_watch_tests.rs");
20224        }
20225        mod call_modes {
20226            include!("scope_call_mode_tests.rs");
20227        }
20228        mod federated {
20229            include!("scope_federated_tests.rs");
20230        }
20231        mod authorize {
20232            include!("route_authorize_tests.rs");
20233        }
20234        #[tokio::test]
20235        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20236            let rig = rig().await;
20237            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20238                "s".into(),
20239                1,
20240                "tool".into(),
20241            ))
20242            .unwrap();
20243            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20244            let (direct, _rx) = wide_ctx(999);
20245            for (ctx, expected) in [
20246                (&rig.owner, FrameType::Response),
20247                (&direct, FrameType::Error),
20248            ] {
20249                let frame =
20250                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20251                        .unwrap();
20252                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20253                assert_eq!(replies[0].header.ty, expected);
20254                if expected == FrameType::Response {
20255                    let reply: subc_control::ScopeServedByReply =
20256                        serde_json::from_slice(&replies[0].body).unwrap();
20257                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20258                } else {
20259                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20260                }
20261            }
20262            let reply = call(
20263                &rig.handler,
20264                &rig.owner,
20265                &ModuleControlRequestFromModule::ScopeDescribe {
20266                    owner: Principal::Reserved {
20267                        module_id: OWNER.into(),
20268                    },
20269                    scope_ref: "s".into(),
20270                },
20271            )
20272            .await;
20273            assert!(matches!(
20274                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20275                ModuleControlResponseToModule::ScopeDescribe { .. }
20276            ));
20277        }
20278
20279        use subc_protocol::scope::{
20280            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20281            ScopeStatus,
20282        };
20283
20284        use super::*;
20285
20286        const OWNER: &str = "prefrontal-core";
20287
20288        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20289            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20290        }
20291
20292        async fn call(
20293            handler: &ControlHandler,
20294            ctx: &RouteCtx,
20295            request: &ModuleControlRequestFromModule,
20296        ) -> Frame {
20297            let body = serde_json::to_vec(request).unwrap();
20298            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20299            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20300            assert_eq!(replies.len(), 1, "{replies:?}");
20301            replies.pop().unwrap()
20302        }
20303
20304        async fn sync(
20305            handler: &ControlHandler,
20306            ctx: &RouteCtx,
20307            generation: u64,
20308            scopes: Vec<ScopeRecord>,
20309        ) -> Result<ModuleControlResponseToModule, String> {
20310            let reply = call(
20311                handler,
20312                ctx,
20313                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20314            )
20315            .await;
20316            match reply.header.ty {
20317                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20318                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20319            }
20320        }
20321
20322        async fn describe(
20323            handler: &ControlHandler,
20324            ctx: &RouteCtx,
20325            owner: &str,
20326            scope_ref: &str,
20327        ) -> ModuleControlResponseToModule {
20328            let reply = call(
20329                handler,
20330                ctx,
20331                &ModuleControlRequestFromModule::ScopeDescribe {
20332                    owner: Principal::Reserved {
20333                        module_id: owner.to_string(),
20334                    },
20335                    scope_ref: scope_ref.to_string(),
20336                },
20337            )
20338            .await;
20339            assert_eq!(
20340                reply.header.ty,
20341                FrameType::Response,
20342                "{:?}",
20343                parse_error(&reply)
20344            );
20345            serde_json::from_slice(&reply.body).unwrap()
20346        }
20347
20348        #[tokio::test]
20349        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20350            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20351            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20352            let mut rig = rig().await;
20353            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20354                .await;
20355            let _bound = rig
20356                .bound(
20357                    Some(AFT),
20358                    PLEXUS,
20359                    Some(
20360                        rig.selector("s", Some(1))
20361                            .with_bind_proof(Some(PROOF.into())),
20362                    ),
20363                )
20364                .await;
20365            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20366            let output = serde_json::to_string(&reply).unwrap();
20367            assert!(output.contains("\"status\":\"live\""));
20368            assert!(!output.contains(PROOF));
20369            assert!(!output.contains(HASH));
20370        }
20371
20372        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20373        async fn module(
20374            handler: &ControlHandler,
20375            connection: u64,
20376            module_id: &str,
20377            nonce: Option<&str>,
20378        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20379            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20380            hello_via_sink(
20381                handler,
20382                &ctx,
20383                &mut rx,
20384                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20385            )
20386            .await;
20387            (ctx, rx)
20388        }
20389
20390        /// `direct` and every other client connection has no registration, so
20391        /// it can neither sync nor own a scope.
20392        #[tokio::test]
20393        async fn a_client_connection_cannot_sync_or_describe() {
20394            let handler = ControlHandler::new(Arc::new(Registry::default()));
20395            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20396            for request in [
20397                ModuleControlRequestFromModule::ScopeSync {
20398                    generation: 1,
20399                    scopes: vec![head("s", 1)],
20400                },
20401                ModuleControlRequestFromModule::ScopeDescribe {
20402                    owner: Principal::Direct,
20403                    scope_ref: "s".to_string(),
20404                },
20405            ] {
20406                let reply = call(&handler, &ctx, &request).await;
20407                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20408            }
20409            assert!(
20410                !handler
20411                    .scopes
20412                    .read()
20413                    .unwrap()
20414                    .describe(
20415                        &Principal::Reserved {
20416                            module_id: OWNER.to_string()
20417                        },
20418                        "s"
20419                    )
20420                    .owner_synced
20421            );
20422        }
20423
20424        /// A module the supervisor did not spawn registers without a launch
20425        /// nonce, so it is never an owner's current launch.
20426        #[tokio::test]
20427        async fn a_module_without_a_supervised_launch_cannot_sync() {
20428            let handler = ControlHandler::new(Arc::new(Registry::default()));
20429            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20430            assert_eq!(
20431                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20432                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20433            );
20434        }
20435
20436        #[tokio::test]
20437        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20438            let supervisor = SupervisorHandle::new();
20439            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20440            let handler = ControlHandler::new(Arc::new(Registry::default()))
20441                .with_supervisor(supervisor.clone());
20442            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20443            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20444                .await
20445                .expect("the current launch syncs");
20446
20447            // A swap candidate registers with the swap token and is refused
20448            // while the incumbent keeps syncing.
20449            supervisor.open_swap(OWNER, "n2".to_string());
20450            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20451            assert_eq!(
20452                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20453                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20454            );
20455            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20456                .await
20457                .expect("the serving owner syncs during the swap");
20458
20459            // The swap fails and is rolled back. The candidate never held sync
20460            // authority, and still cannot sync.
20461            supervisor.close_swap(OWNER);
20462            assert_eq!(
20463                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20464                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20465            );
20466            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20467                .await
20468                .expect("the serving owner syncs after the rollback");
20469            handler.cleanup_connection(candidate.connection_id).unwrap();
20470
20471            // A swap that cuts over. Promotion records the candidate's nonce as
20472            // the module's spawn nonce, which is what `set_spawn_nonce` does
20473            // here; the promoted connection then takes authority at any
20474            // generation and the superseded incumbent is refused.
20475            supervisor.open_swap(OWNER, "n3".to_string());
20476            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20477            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20478            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20479                .await
20480                .expect("the promoted launch takes authority");
20481            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20482                panic!("unexpected reply {reply:?}");
20483            };
20484            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20485            assert_eq!(
20486                sync(&handler, &incumbent, 4, Vec::new()).await,
20487                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20488            );
20489        }
20490
20491        /// Authority dies with its connection: the cleanup path releases it,
20492        /// so the owner's next connection takes it at any generation.
20493        #[tokio::test]
20494        async fn closing_the_authority_connection_frees_sync_authority() {
20495            let supervisor = SupervisorHandle::new();
20496            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20497            let handler = ControlHandler::new(Arc::new(Registry::default()))
20498                .with_supervisor(supervisor.clone());
20499            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20500            sync(&handler, &first, 10, vec![head("s", 1)])
20501                .await
20502                .unwrap();
20503            handler.cleanup_connection(first.connection_id).unwrap();
20504
20505            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20506            sync(&handler, &second, 1, vec![head("s", 1)])
20507                .await
20508                .expect("the next connection takes the released authority");
20509        }
20510
20511        #[tokio::test]
20512        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20513            let supervisor = SupervisorHandle::new();
20514            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20515            let handler =
20516                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20517            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20518            sync(&handler, &first, 10, vec![head("s", 1)])
20519                .await
20520                .unwrap();
20521            handler
20522                .handle_control_frame(
20523                    &first,
20524                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20525                )
20526                .await
20527                .unwrap();
20528            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20529            sync(&handler, &second, 1, vec![head("s", 1)])
20530                .await
20531                .expect("GOODBYE releases authority even if the old socket remains open");
20532        }
20533
20534        #[tokio::test]
20535        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20536            let registry = Arc::new(Registry::default());
20537            let supervisor_handle = SupervisorHandle::new();
20538            let supervisor =
20539                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20540                    .with_handle(supervisor_handle.clone())
20541                    .with_daemon_incarnation("incarnation-7".to_string());
20542            // Configured with enabled: false, so the supervisor lists the
20543            // module without spawning a process for it.
20544            supervisor
20545                .supervise_configured(
20546                    ModuleSpec {
20547                        script: None,
20548                        carry_containment: false,
20549                        module_id: OWNER.to_string(),
20550                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20551                        args: Vec::new(),
20552                        env: Vec::new(),
20553                        reserved: false,
20554                        reserved_prefixes: Vec::new(),
20555                        protocol: ModuleProtocol::Subc,
20556                        overlap: Default::default(),
20557                    },
20558                    false,
20559                )
20560                .unwrap();
20561            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20562            let handler =
20563                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20564            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20565
20566            // Configured but not yet synced: a reader waits for the owner.
20567            let ModuleControlResponseToModule::ScopeDescribe {
20568                status,
20569                daemon_incarnation,
20570                owner_synced,
20571                owner_configured,
20572                scope,
20573                ..
20574            } = describe(&handler, &reader, OWNER, "s").await
20575            else {
20576                panic!("not a describe reply");
20577            };
20578            assert_eq!(status, ScopeStatus::NotLive);
20579            assert_eq!(daemon_incarnation, "incarnation-7");
20580            assert!(!owner_synced);
20581            assert!(owner_configured);
20582            assert!(scope.is_none());
20583
20584            // Not a supervised module: the owner will never sync, and a reader
20585            // refuses rather than waits.
20586            let ModuleControlResponseToModule::ScopeDescribe {
20587                status,
20588                owner_configured,
20589                ..
20590            } = describe(&handler, &reader, "ghost", "s").await
20591            else {
20592                panic!("not a describe reply");
20593            };
20594            assert_eq!(status, ScopeStatus::NotLive);
20595            assert!(!owner_configured);
20596
20597            // Live, with the stamp fields and the computed owner_authorized.
20598            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20599            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20600            let ModuleControlResponseToModule::ScopeDescribe {
20601                status,
20602                scope_epoch,
20603                owner_synced,
20604                scope,
20605                ..
20606            } = describe(&handler, &reader, OWNER, "s").await
20607            else {
20608                panic!("not a describe reply");
20609            };
20610            assert_eq!(status, ScopeStatus::Live);
20611            assert_eq!(scope_epoch, Some(4));
20612            assert!(owner_synced);
20613            let stamp = scope.expect("a live scope carries its stamp");
20614            assert!(
20615                stamp.owner_authorized,
20616                "prefrontal-core is the default authority"
20617            );
20618            assert_eq!(stamp.kind, ScopeKind::Head);
20619        }
20620
20621        #[tokio::test]
20622        async fn scope_authority_owners_decides_owner_authorized() {
20623            let supervisor = SupervisorHandle::new();
20624            supervisor.set_spawn_nonce("broca", "b1".to_string());
20625            let handler = ControlHandler::new(Arc::new(Registry::default()))
20626                .with_supervisor(supervisor)
20627                .with_scope_authority_owners(vec!["broca".to_string()]);
20628            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20629            let mut gated = head("s", 1);
20630            gated.attributes.agent_id = Some("agent".to_string());
20631            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20632            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20633                describe(&handler, &broca, "broca", "s").await
20634            else {
20635                panic!("not a describe reply");
20636            };
20637            assert!(scope.unwrap().owner_authorized);
20638        }
20639
20640        /// With route admission, the stamp, the commit re-check and drains in
20641        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20642        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20643        #[tokio::test]
20644        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20645            let handler = ControlHandler::new(Arc::new(Registry::default()));
20646            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20647            let ack = hello_via_sink(
20648                &handler,
20649                &ctx,
20650                &mut rx,
20651                hello_frame("m", PROTOCOL_VERSION, 1),
20652            )
20653            .await;
20654            let ack = parse_ack(&ack);
20655            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20656                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20657            }
20658            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20659
20660            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20661            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20662            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20663            let reply = handler
20664                .handle_control_frame(&client, frame)
20665                .await
20666                .unwrap()
20667                .pop()
20668                .unwrap();
20669            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20670                serde_json::from_slice(&reply.body).unwrap()
20671            else {
20672                panic!("not a server.describe reply");
20673            };
20674            assert!(
20675                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20676                "{capabilities:?}"
20677            );
20678        }
20679
20680        // ---- route admission, stamps, commit re-check and drains ----------
20681
20682        const PLEXUS: &str = "plexus";
20683        const OTHER: &str = "other";
20684        const AFT: &str = "aft";
20685        const BROCA: &str = "broca";
20686        const MAGIC: &str = "magic-context";
20687
20688        fn nonce(module_id: &str) -> String {
20689            format!("nonce-{module_id}")
20690        }
20691
20692        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20693            let (tx, rx) = mpsc::channel(64);
20694            (
20695                RouteCtx {
20696                    connection_id: ConnectionId::new(connection),
20697                    egress: FrameSink::new(tx),
20698                },
20699                rx,
20700            )
20701        }
20702
20703        /// A daemon with a configured owner (prefrontal-core) registered on its
20704        /// own module connection, two routable targets (plexus, other), and
20705        /// launch nonces minted for the modules that open routes as carriers.
20706        struct Rig {
20707            handler: ControlHandler,
20708            forwarding: Arc<ForwardingTable>,
20709            owner: RouteCtx,
20710            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20711            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20712            generation: u64,
20713            next_connection: u64,
20714            _supervisor: Supervisor,
20715        }
20716
20717        async fn rig() -> Rig {
20718            rig_with_flow_support(true).await
20719        }
20720
20721        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20722            rig_with_scope_capabilities(flow_support, false).await
20723        }
20724
20725        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20726            let mut provides = Vec::new();
20727            if flow_support {
20728                provides.push("flow-scopes/v1");
20729            }
20730            if run_support {
20731                provides.push("agent-run-scopes/v1");
20732            }
20733            rig_with_target_capabilities(&provides).await
20734        }
20735
20736        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20737            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20738            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20739            // Decoder versions alone cannot admit scoped calls: only a capability
20740            // declaration promises the required run or flow behaviour.
20741            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20742            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20743            Frame::build(
20744                FrameType::Hello,
20745                control_flags(),
20746                0,
20747                0,
20748                connection,
20749                serde_json::to_vec(&body).unwrap(),
20750            )
20751            .unwrap()
20752        }
20753
20754        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20755            let registry = Arc::new(Registry::default());
20756            let forwarding = Arc::new(ForwardingTable::default());
20757            let supervisor_handle = SupervisorHandle::new();
20758            let supervisor =
20759                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20760                    .with_handle(supervisor_handle.clone());
20761            supervisor
20762                .supervise_configured(
20763                    ModuleSpec {
20764                        script: None,
20765                        carry_containment: false,
20766                        module_id: OWNER.to_string(),
20767                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20768                        args: Vec::new(),
20769                        env: Vec::new(),
20770                        reserved: false,
20771                        reserved_prefixes: Vec::new(),
20772                        protocol: ModuleProtocol::Subc,
20773                        overlap: Default::default(),
20774                    },
20775                    false,
20776                )
20777                .unwrap();
20778            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20779                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20780            }
20781            let handler =
20782                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20783                    .with_supervisor(supervisor_handle);
20784            let (owner, mut owner_rx) = wide_ctx(1);
20785            hello_via_sink(
20786                &handler,
20787                &owner,
20788                &mut owner_rx,
20789                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20790            )
20791            .await;
20792            let mut modules = BTreeMap::new();
20793            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20794                let (ctx, mut rx) = wide_ctx(connection);
20795                let hello = hello_with_capabilities(module_id, connection, provides);
20796                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20797                modules.insert(module_id.to_string(), (ctx, rx));
20798            }
20799            Rig {
20800                handler,
20801                forwarding,
20802                owner,
20803                _owner_rx: owner_rx,
20804                modules,
20805                generation: 0,
20806                next_connection: 100,
20807                _supervisor: supervisor,
20808            }
20809        }
20810
20811        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20812            ScopeCarrier::new(Principal::Reserved {
20813                module_id: module_id.to_string(),
20814            })
20815            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20816        }
20817
20818        /// The scope most tests open under: aft carries to any module, broca
20819        /// only to plexus and other, and the owner delegates as agent-1.
20820        fn session(scope_epoch: u64) -> ScopeRecord {
20821            let mut record = head("s", scope_epoch);
20822            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20823            record.attributes.agent_id = Some("agent-1".to_string());
20824            record.attributes.delegates = true;
20825            record
20826        }
20827
20828        impl Rig {
20829            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20830                self.generation += 1;
20831                sync(&self.handler, &self.owner, self.generation, scopes)
20832                    .await
20833                    .expect("the owner's sync is accepted");
20834            }
20835
20836            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20837                ScopeSelector::new(
20838                    Principal::Reserved {
20839                        module_id: OWNER.to_string(),
20840                    },
20841                    scope_ref.to_string(),
20842                    scope_epoch,
20843                )
20844            }
20845
20846            fn open_frame(
20847                &mut self,
20848                opener: Option<&str>,
20849                target: &str,
20850                scope: Option<ScopeSelector>,
20851            ) -> (
20852                RouteCtx,
20853                mpsc::Receiver<crate::router::OutboundFrame>,
20854                Frame,
20855            ) {
20856                self.next_connection += 1;
20857                let (ctx, rx) = wide_ctx(self.next_connection);
20858                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20859                    busy_refusals: None,
20860                    target: RouteTarget::ToolProvider {
20861                        module_id: target.to_string(),
20862                    },
20863                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20864                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20865                        module_id: module_id.to_string(),
20866                        launch_nonce: nonce(module_id),
20867                    }),
20868                    consumer_capabilities: None,
20869                    role_versions: None,
20870                    admission_facts: None,
20871                    scope,
20872                })
20873                .unwrap();
20874                let frame = Frame::build(
20875                    FrameType::Request,
20876                    control_flags(),
20877                    0,
20878                    0,
20879                    self.next_connection,
20880                    body,
20881                )
20882                .unwrap();
20883                (ctx, rx, frame)
20884            }
20885
20886            /// Open and expect a refusal before anything is relayed.
20887            async fn refused(
20888                &mut self,
20889                opener: Option<&str>,
20890                target: &str,
20891                scope: Option<ScopeSelector>,
20892            ) -> String {
20893                self.refusal_body(opener, target, scope).await["code"]
20894                    .as_str()
20895                    .unwrap()
20896                    .to_string()
20897            }
20898
20899            async fn refusal_body(
20900                &mut self,
20901                opener: Option<&str>,
20902                target: &str,
20903                scope: Option<ScopeSelector>,
20904            ) -> Value {
20905                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20906                let replies = tokio::time::timeout(
20907                    Duration::from_secs(2),
20908                    self.handler.handle_control_frame(&ctx, frame),
20909                )
20910                .await
20911                .expect("the open must be refused before waiting for a bind ack")
20912                .unwrap();
20913                assert_eq!(replies.len(), 1, "{replies:?}");
20914                assert_eq!(replies[0].header.ty, FrameType::Error);
20915                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20916                assert!(
20917                    module_rx.try_recv().is_err(),
20918                    "a refused open relays nothing"
20919                );
20920                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20921                parse_error(&replies[0])
20922            }
20923
20924            /// Start an open and return its task and the bind the target got.
20925            async fn relayed(
20926                &mut self,
20927                opener: Option<&str>,
20928                target: &str,
20929                scope: Option<ScopeSelector>,
20930            ) -> Relayed {
20931                self.relayed_with_legacy_root(opener, target, scope, None)
20932                    .await
20933            }
20934
20935            async fn relayed_with_legacy_root(
20936                &mut self,
20937                opener: Option<&str>,
20938                target: &str,
20939                scope: Option<ScopeSelector>,
20940                legacy_root: Option<&std::path::Path>,
20941            ) -> Relayed {
20942                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20943                if let Some(root) = legacy_root {
20944                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20945                    body["identity"]["project_root"] = serde_json::json!(root);
20946                    frame.body = serde_json::to_vec(&body).unwrap();
20947                }
20948                let handler = self.handler.clone();
20949                let task_ctx = ctx.clone();
20950                let task = tokio::spawn(async move {
20951                    handler
20952                        .handle_control_frame(&task_ctx, frame)
20953                        .await
20954                        .unwrap()
20955                });
20956                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20957                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20958                    .await
20959                    .expect("the target receives the relayed route.bind")
20960                    .unwrap()
20961                    .frame;
20962                Relayed {
20963                    target: target.to_string(),
20964                    client: ctx,
20965                    client_rx: rx,
20966                    task,
20967                    bind,
20968                }
20969            }
20970
20971            async fn ack(&self, relayed: &Relayed) {
20972                let (module, _) = &self.modules[&relayed.target];
20973                self.handler
20974                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20975                    .await
20976                    .unwrap();
20977            }
20978
20979            /// Open, ack and return the bound route.
20980            async fn bound(
20981                &mut self,
20982                opener: Option<&str>,
20983                target: &str,
20984                scope: Option<ScopeSelector>,
20985            ) -> Bound {
20986                let relayed = self.relayed(opener, target, scope).await;
20987                self.commit_relayed(relayed).await
20988            }
20989
20990            async fn bound_with_legacy_root(
20991                &mut self,
20992                opener: Option<&str>,
20993                target: &str,
20994                scope: Option<ScopeSelector>,
20995                root: &std::path::Path,
20996            ) -> Bound {
20997                let relayed = self
20998                    .relayed_with_legacy_root(opener, target, scope, Some(root))
20999                    .await;
21000                self.commit_relayed(relayed).await
21001            }
21002
21003            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
21004                self.ack(&relayed).await;
21005                let Relayed {
21006                    target,
21007                    client,
21008                    mut client_rx,
21009                    task,
21010                    bind,
21011                } = relayed;
21012                assert!(
21013                    task.await.unwrap().is_empty(),
21014                    "the open is answered by commit"
21015                );
21016                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
21017                Bound {
21018                    target,
21019                    client,
21020                    client_rx,
21021                    channel,
21022                    epoch,
21023                    bind,
21024                }
21025            }
21026
21027            fn live(&self, route: &Bound) -> bool {
21028                matches!(
21029                    self.forwarding
21030                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21031                        .unwrap(),
21032                    DataRoute::Client(DataRouteState::Bound(_))
21033                )
21034            }
21035        }
21036
21037        struct Relayed {
21038            target: String,
21039            client: RouteCtx,
21040            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21041            task: tokio::task::JoinHandle<Vec<Frame>>,
21042            bind: Frame,
21043        }
21044
21045        struct Bound {
21046            target: String,
21047            client: RouteCtx,
21048            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21049            channel: u16,
21050            epoch: u32,
21051            bind: Frame,
21052        }
21053
21054        impl Bound {
21055            /// The reason of the `route.closed` this client was sent, after
21056            /// checking it also got a GOODBYE on exactly this route.
21057            fn closed_reason(&mut self) -> RouteCloseReason {
21058                let mut reason = None;
21059                let mut goodbye = false;
21060                while let Ok(outbound) = self.client_rx.try_recv() {
21061                    let frame = outbound.frame;
21062                    match frame.header.ty {
21063                        FrameType::Goodbye => {
21064                            assert_eq!(
21065                                (frame.header.channel, frame.header.epoch),
21066                                (self.channel, self.epoch)
21067                            );
21068                            goodbye = true;
21069                        }
21070                        FrameType::Push => {
21071                            let ClientControlPush::RouteClosed {
21072                                reason: r,
21073                                module_id,
21074                                ..
21075                            } = serde_json::from_slice(&frame.body).unwrap()
21076                            else {
21077                                panic!("unexpected push");
21078                            };
21079                            assert_eq!(module_id, self.target);
21080                            reason = Some(r);
21081                        }
21082                        other => panic!("unexpected frame {other:?}"),
21083                    }
21084                }
21085                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21086                reason.expect("the client is told why the route closed")
21087            }
21088
21089            fn untouched(&mut self) -> bool {
21090                self.client_rx.try_recv().is_err()
21091            }
21092
21093            fn stamp(&self) -> Option<ScopeStamp> {
21094                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21095                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21096                    other => panic!("expected a route.bind, got {other:?}"),
21097                }
21098            }
21099        }
21100
21101        #[tokio::test]
21102        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21103        ) {
21104            let mut rig = rig().await;
21105            let mut record = session(1);
21106            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21107            record.child_owners = vec![Principal::Reserved {
21108                module_id: MAGIC.to_string(),
21109            }];
21110            rig.sync(vec![record]).await;
21111            let scope = || Some(rig_selector("s", Some(1)));
21112
21113            // Admitted: the owner, a bare carrier to any module, a targeted
21114            // carrier to its listed module.
21115            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21116            rig.bound(Some(AFT), OTHER, scope()).await;
21117            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21118
21119            // Refused scope_not_carrier: a targeted carrier to an unlisted
21120            // module, a module that is not listed at all (a child owner is not
21121            // a carrier), and a direct key-holder.
21122            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21123                assert_eq!(
21124                    rig.refused(opener, target, scope()).await,
21125                    error_codes::SCOPE_NOT_CARRIER,
21126                    "{opener:?} -> {target}"
21127                );
21128            }
21129        }
21130
21131        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21132            ScopeSelector::new(
21133                Principal::Reserved {
21134                    module_id: OWNER.to_string(),
21135                },
21136                scope_ref.to_string(),
21137                scope_epoch,
21138            )
21139        }
21140
21141        #[tokio::test]
21142        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21143            let mut rig = rig().await;
21144            rig.sync(vec![session(1)]).await;
21145            for opener in [OWNER, AFT] {
21146                assert_eq!(
21147                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21148                        .await,
21149                    error_codes::SCOPE_EPOCH_REQUIRED,
21150                    "{opener}"
21151                );
21152            }
21153        }
21154
21155        #[tokio::test]
21156        async fn admission_separates_not_synced_not_live_and_ended() {
21157            let mut rig = rig().await;
21158            // Before the configured owner's first sync: retryable.
21159            let code = rig
21160                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21161                .await;
21162            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21163            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21164
21165            // An owner that is not configured will never sync: terminal.
21166            let ghost = ScopeSelector::new(
21167                Principal::Reserved {
21168                    module_id: "ghost".to_string(),
21169                },
21170                "s".to_string(),
21171                Some(1),
21172            );
21173            assert_eq!(
21174                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21175                error_codes::SCOPE_NOT_LIVE
21176            );
21177
21178            rig.sync(vec![session(2)]).await;
21179            assert_eq!(
21180                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21181                    .await,
21182                error_codes::SCOPE_NOT_LIVE
21183            );
21184            for epoch in [1, 3] {
21185                assert_eq!(
21186                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21187                        .await,
21188                    error_codes::SCOPE_ENDED,
21189                    "epoch {epoch}"
21190                );
21191            }
21192            // Control: the live epoch is admitted.
21193            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21194                .await;
21195        }
21196
21197        #[tokio::test]
21198        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21199            let mut rig = rig().await;
21200            rig.sync(vec![session(1)]).await;
21201            let route = rig
21202                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21203                .await;
21204            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21205            assert_eq!(stamp.scope_ref, "s");
21206            assert_eq!(stamp.scope_epoch, 1);
21207            assert_eq!(stamp.kind, ScopeKind::Head);
21208            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21209            assert!(stamp.attributes.delegates);
21210            assert!(stamp.owner_authorized);
21211            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21212            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21213
21214            // broca owns a scope of its own on its own module connection; it is
21215            // not in scope_authority_owners, so its stamp is not authorized.
21216            let (broca, mut broca_rx) = wide_ctx(50);
21217            hello_via_sink(
21218                &rig.handler,
21219                &broca,
21220                &mut broca_rx,
21221                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21222            )
21223            .await;
21224            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21225                .await
21226                .unwrap();
21227            let own = ScopeSelector::new(
21228                Principal::Reserved {
21229                    module_id: BROCA.to_string(),
21230                },
21231                "b".to_string(),
21232                Some(1),
21233            );
21234            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21235            assert!(!route.stamp().unwrap().owner_authorized);
21236        }
21237
21238        #[tokio::test]
21239        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21240            let mut rig = rig().await;
21241            let mut record = head("s", 1);
21242            record.carriers = vec![carrier(AFT, None)];
21243            let flow_id = "Flow:run-7/step_2!~";
21244            record.attributes.flow_id = Some(flow_id.to_string());
21245            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21246                .await
21247                .unwrap();
21248            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21249                panic!("not a sync reply");
21250            };
21251            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21252            let route = rig
21253                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21254                .await;
21255            assert!(rig.live(&route), "the stamped bind committed");
21256            let stamp = route.stamp().expect("a flow scope carries a stamp");
21257            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21258            assert_eq!(stamp.attributes.agent_id, None);
21259            assert!(!stamp.attributes.delegates);
21260            assert!(stamp.owner_authorized);
21261            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21262            assert_eq!(unscoped.stamp(), None);
21263        }
21264
21265        #[tokio::test]
21266        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21267            let mut rig = rig_with_flow_support(false).await;
21268            let mut record = session(1);
21269            record.attributes.flow_id = Some("flow:7".to_string());
21270            rig.sync(vec![record]).await;
21271            for opener in [OWNER, AFT] {
21272                let body = rig
21273                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21274                    .await;
21275                assert_eq!(body["code"], "target_flow_unsupported");
21276                let message = body["message"].as_str().unwrap();
21277                for required in [PLEXUS, "flow-scopes/v1"] {
21278                    assert!(message.contains(required), "{message}");
21279                }
21280            }
21281        }
21282
21283        #[tokio::test]
21284        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21285            let mut rig = rig_with_flow_support(true).await;
21286            let mut record = session(1);
21287            record.attributes.flow_id = Some("flow:7".to_string());
21288            rig.sync(vec![record]).await;
21289            for opener in [OWNER, AFT] {
21290                let route = rig
21291                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21292                    .await;
21293                assert!(rig.live(&route));
21294                assert_eq!(
21295                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21296                    Some("flow:7")
21297                );
21298            }
21299        }
21300
21301        #[tokio::test]
21302        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21303            use std::future::Future;
21304
21305            let mut rig = rig_with_flow_support(true).await;
21306            let mut record = session(1);
21307            record.attributes.flow_id = Some("flow:7".to_string());
21308            rig.sync(vec![record]).await;
21309            let (client, mut client_rx, frame) =
21310                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21311            // Hold the route-open response permit so admission sees the first
21312            // target but relay reservation cannot capture an endpoint yet.
21313            for _ in 0..64 {
21314                client.egress.try_send(route_bind_ack(1)).unwrap();
21315            }
21316            let handler = rig.handler.clone();
21317            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21318            std::future::poll_fn(|cx| {
21319                assert!(open.as_mut().poll(cx).is_pending());
21320                std::task::Poll::Ready(())
21321            })
21322            .await;
21323            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21324
21325            let old_connection = rig.modules[PLEXUS].0.connection_id;
21326            rig.handler.cleanup_connection(old_connection).unwrap();
21327            let (replacement, mut replacement_rx) = wide_ctx(200);
21328            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21329            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21330            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21331            let hello = Frame::build(
21332                FrameType::Hello,
21333                control_flags(),
21334                0,
21335                0,
21336                200,
21337                serde_json::to_vec(&body).unwrap(),
21338            )
21339            .unwrap();
21340            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21341
21342            client_rx.try_recv().unwrap();
21343            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21344                .await
21345                .expect("the replacement is refused without waiting for a bind ack")
21346                .unwrap();
21347            assert_eq!(replies.len(), 1);
21348            let body = parse_error(&replies[0]);
21349            assert_eq!(body["code"], "target_flow_unsupported");
21350            for required in [PLEXUS, "flow-scopes/v1"] {
21351                assert!(body["message"].as_str().unwrap().contains(required));
21352            }
21353            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21354            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21355            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21356            assert!(rig
21357                .handler
21358                .registry
21359                .get_module_by_connection(replacement.connection_id)
21360                .unwrap()
21361                .is_some());
21362        }
21363
21364        #[tokio::test]
21365        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21366            use std::future::Future;
21367            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21368            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21369            const NEXT_HASH: &str =
21370                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21371            let mut rig = rig().await;
21372            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21373            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21374            rig.sync(vec![record.clone()]).await;
21375            let (client, mut rx, frame) = rig.open_frame(
21376                None,
21377                PLEXUS,
21378                Some(
21379                    rig.selector("s", Some(1))
21380                        .with_bind_proof(Some(PROOF.into())),
21381                ),
21382            );
21383            // Hold egress reservation while the scope owner changes its bind-proof
21384            // hash, so a proof valid at admission must be checked again at relay.
21385            for _ in 0..64 {
21386                client.egress.try_send(route_bind_ack(1)).unwrap();
21387            }
21388            let handler = rig.handler.clone();
21389            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21390            std::future::poll_fn(|cx| {
21391                assert!(open.as_mut().poll(cx).is_pending());
21392                std::task::Poll::Ready(())
21393            })
21394            .await;
21395            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21396            rig.sync(vec![record]).await;
21397            rx.try_recv().unwrap();
21398            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21399                .await
21400                .unwrap()
21401                .unwrap();
21402            assert_eq!(
21403                parse_error(&replies[0])["code"],
21404                error_codes::SCOPE_BIND_PROOF_MISMATCH
21405            );
21406            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21407            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21408            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21409        }
21410
21411        #[tokio::test]
21412        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21413            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21414            let mut rig = rig().await;
21415            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21416                .await;
21417            for opener in [OWNER, AFT] {
21418                for proof in [None, Some("malformed+proof=")] {
21419                    let route = rig
21420                        .bound(
21421                            Some(opener),
21422                            PLEXUS,
21423                            Some(
21424                                rig.selector("s", Some(1))
21425                                    .with_bind_proof(proof.map(str::to_string)),
21426                            ),
21427                        )
21428                        .await;
21429                    assert!(rig.live(&route));
21430                }
21431            }
21432        }
21433
21434        #[tokio::test]
21435        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21436            use std::future::Future;
21437            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21438            const NEXT_HASH: &str =
21439                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21440            let mut rig = rig().await;
21441            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21442                .await;
21443            let (client, mut rx, frame) =
21444                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21445            for _ in 0..64 {
21446                client.egress.try_send(route_bind_ack(1)).unwrap();
21447            }
21448            let handler = rig.handler.clone();
21449            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21450            std::future::poll_fn(|cx| {
21451                assert!(open.as_mut().poll(cx).is_pending());
21452                std::task::Poll::Ready(())
21453            })
21454            .await;
21455            rig.sync(vec![
21456                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21457            ])
21458            .await;
21459            rx.try_recv().unwrap();
21460            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21461            let bind = std::future::poll_fn(|cx| {
21462                assert!(open.as_mut().poll(cx).is_pending());
21463                module_rx.poll_recv(cx)
21464            })
21465            .await
21466            .unwrap()
21467            .frame;
21468            handler
21469                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21470                .await
21471                .unwrap();
21472            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21473                .await
21474                .unwrap()
21475                .unwrap();
21476            assert_eq!(replies.len(), 1);
21477            // Proof rechecking allowed the relay. Independent tag settlement
21478            // still asks the opener to retry after any same-epoch content change.
21479            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21480            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21481            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21482            let route = rig
21483                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21484                .await;
21485            assert!(rig.live(&route));
21486        }
21487
21488        #[tokio::test]
21489        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21490        {
21491            let mut rig = rig_with_flow_support(false).await;
21492            rig.sync(vec![session(1)]).await;
21493            let route = rig
21494                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21495                .await;
21496            assert!(rig.live(&route));
21497            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21498            let mut record = session(1);
21499            record.attributes.flow_id = Some("flow:7".to_string());
21500            rig.sync(vec![record]).await;
21501            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21502            assert!(rig.live(&unscoped));
21503            assert_eq!(unscoped.stamp(), None);
21504        }
21505
21506        #[tokio::test]
21507        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21508            let mut rig = rig().await;
21509            let mut record = session(1);
21510            record.attributes.flow_id = Some("flow:7".to_string());
21511            rig.sync(vec![record.clone()]).await;
21512            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21513            let mut owner_route = rig
21514                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21515                .await;
21516            let mut carrier_route = rig
21517                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21518                .await;
21519            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21520            rig.sync(vec![record.clone()]).await;
21521            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21522            assert!(rig.live(&owner_route) && owner_route.untouched());
21523            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21524
21525            record.attributes.flow_id = Some("flow:8".to_string());
21526            rig.sync(vec![record]).await;
21527            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21528            let before = before.unwrap();
21529            assert_eq!(after.scope_epoch, before.scope_epoch);
21530            assert!(after.version > before.version);
21531            for route in [&mut owner_route, &mut carrier_route] {
21532                assert!(!rig.live(route));
21533                assert_eq!(
21534                    route.closed_reason(),
21535                    RouteCloseReason::ScopeDelegationChanged
21536                );
21537            }
21538            assert!(rig.live(&unscoped) && unscoped.untouched());
21539            // Each provider also receives a GOODBYE for its drained route;
21540            // consume it before expecting the next route.bind on that sink.
21541            for target in [PLEXUS, OTHER] {
21542                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21543                let goodbye = module_rx
21544                    .try_recv()
21545                    .expect("the provider sees the drain")
21546                    .frame;
21547                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21548                assert!(module_rx.try_recv().is_err());
21549            }
21550            let rebound = rig
21551                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21552                .await;
21553            assert_eq!(
21554                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21555                Some("flow:8")
21556            );
21557        }
21558
21559        /// The owner's sync lands between admission and the module's ack. The
21560        /// open is refused by name, the module's other routes stay up, and the
21561        /// reserved pair is released. Changed content is retryable; an ended
21562        /// scope is not.
21563        #[tokio::test]
21564        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21565            let mut rig = rig().await;
21566            rig.sync(vec![session(1)]).await;
21567            let mut cotenant = rig
21568                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21569                .await;
21570
21571            let mut changed = session(1);
21572            changed.child_owners.push(Principal::Reserved {
21573                module_id: MAGIC.to_string(),
21574            });
21575            let mut ended = None;
21576            for (code, next) in [
21577                (error_codes::SCOPE_CHANGED, vec![changed]),
21578                (error_codes::SCOPE_ENDED, Vec::new()),
21579            ] {
21580                let relayed = rig
21581                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21582                    .await;
21583                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21584                ended = Some(next.is_empty());
21585                rig.sync(next).await;
21586                rig.ack(&relayed).await;
21587                let replies = relayed.task.await.unwrap();
21588                assert_eq!(replies.len(), 1, "{replies:?}");
21589                assert_eq!(parse_error(&replies[0])["code"], code);
21590                assert_eq!(
21591                    subc_protocol::error_codes::is_retryable_route_open(code),
21592                    code == error_codes::SCOPE_CHANGED
21593                );
21594                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21595                // The module is told to drop just the binding it created.
21596                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21597                // Collected, because ending the scope also closes the co-tenant
21598                // route, whose GOODBYE comes first.
21599                let mut goodbyes = Vec::new();
21600                while let Ok(outbound) = plexus_rx.try_recv() {
21601                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21602                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21603                }
21604                assert!(
21605                    goodbyes.contains(&(bind_channel, bind_epoch)),
21606                    "{goodbyes:?}"
21607                );
21608                assert!(rig
21609                    .handler
21610                    .registry
21611                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21612                    .unwrap()
21613                    .is_some());
21614            }
21615            assert_eq!(ended, Some(true));
21616            // The co-tenant stayed up through the change, and closed only when
21617            // the scope ended, by the drain rule rather than by the commit.
21618            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21619        }
21620
21621        /// Each row of the drain table on one set of routes: the owner's, a
21622        /// bare carrier's, and a targeted carrier's to each of its targets.
21623        #[tokio::test]
21624        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21625            struct Case {
21626                name: &'static str,
21627                change: fn(&mut ScopeRecord),
21628                /// Closed routes by index: owner->plexus, aft->plexus,
21629                /// broca->plexus, broca->other.
21630                closed: [Option<RouteCloseReason>; 4],
21631            }
21632            use RouteCloseReason::*;
21633            let cases = [
21634                Case {
21635                    name: "a carrier entry removed",
21636                    change: |r| {
21637                        r.carriers.retain(|c| {
21638                            c.principal
21639                                != Principal::Reserved {
21640                                    module_id: AFT.to_string(),
21641                                }
21642                        })
21643                    },
21644                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21645                },
21646                Case {
21647                    name: "a target removed from a carrier",
21648                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21649                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21650                },
21651                Case {
21652                    name: "a bare carrier narrowed to targets",
21653                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21654                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21655                },
21656                Case {
21657                    name: "delegates turned off",
21658                    change: |r| r.attributes.delegates = false,
21659                    closed: [Some(ScopeDelegationChanged); 4],
21660                },
21661                Case {
21662                    name: "agent_id changed",
21663                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21664                    closed: [Some(ScopeDelegationChanged); 4],
21665                },
21666                Case {
21667                    name: "a carrier added, child owners changed, the record re-sent",
21668                    change: |r| {
21669                        r.carriers.push(carrier(MAGIC, None));
21670                        r.child_owners.push(Principal::Reserved {
21671                            module_id: MAGIC.to_string(),
21672                        });
21673                    },
21674                    closed: [None; 4],
21675                },
21676                Case {
21677                    name: "a target added",
21678                    change: |r| {
21679                        r.carriers[1]
21680                            .targets
21681                            .as_mut()
21682                            .unwrap()
21683                            .push("third".to_string())
21684                    },
21685                    closed: [None; 4],
21686                },
21687                Case {
21688                    name: "delegates turned on",
21689                    change: |r| r.attributes.delegates = true,
21690                    closed: [None; 4],
21691                },
21692            ];
21693            for case in cases {
21694                let mut rig = rig().await;
21695                rig.sync(vec![session(1)]).await;
21696                let scope = || Some(rig_selector("s", Some(1)));
21697                let mut routes = [
21698                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21699                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21700                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21701                    rig.bound(Some(BROCA), OTHER, scope()).await,
21702                ];
21703                let mut record = session(1);
21704                (case.change)(&mut record);
21705                rig.sync(vec![record]).await;
21706                for (index, expected) in case.closed.iter().enumerate() {
21707                    let route = &mut routes[index];
21708                    match expected {
21709                        Some(reason) => {
21710                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21711                            assert_eq!(
21712                                route.closed_reason(),
21713                                *reason,
21714                                "{}: route {index}",
21715                                case.name
21716                            );
21717                        }
21718                        None => {
21719                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21720                            assert!(
21721                                route.untouched(),
21722                                "{}: route {index} was told something",
21723                                case.name
21724                            );
21725                        }
21726                    }
21727                }
21728            }
21729        }
21730
21731        #[tokio::test]
21732        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21733            // Removed, and replaced by a higher epoch.
21734            for next in [Vec::new(), vec![session(2)]] {
21735                let mut rig = rig().await;
21736                rig.sync(vec![session(1)]).await;
21737                let mut route = rig
21738                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21739                    .await;
21740                rig.sync(next).await;
21741                assert!(!rig.live(&route));
21742                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21743            }
21744
21745            // A child whose parent ends: its routes close as parent-ended, the
21746            // child stays live, and routes under the parent close as ended.
21747            let mut rig = rig().await;
21748            let mut child = session(1);
21749            child.scope_ref = "child".to_string();
21750            child.kind = ScopeKind::Worker;
21751            child.parent = Some(ScopeParent::new(
21752                Principal::Reserved {
21753                    module_id: OWNER.to_string(),
21754                },
21755                "s".to_string(),
21756                1,
21757            ));
21758            rig.sync(vec![session(1), child.clone()]).await;
21759            let mut child_route = rig
21760                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21761                .await;
21762            assert_eq!(
21763                child_route.stamp().unwrap().parent_state,
21764                Some(ParentState::Linked)
21765            );
21766            rig.sync(vec![child]).await;
21767            assert!(!rig.live(&child_route));
21768            assert_eq!(
21769                child_route.closed_reason(),
21770                RouteCloseReason::ScopeParentEnded
21771            );
21772        }
21773
21774        #[tokio::test]
21775        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21776        ) {
21777            let mut rig = rig().await;
21778            rig.sync(vec![session(1)]).await;
21779            let mut route = rig
21780                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21781                .await;
21782            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21783            rig.sync(vec![session(1)]).await;
21784            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21785            assert!(rig.live(&route) && route.untouched());
21786
21787            // A call in flight on the route when another carrier is added. A
21788            // forwarded REQUEST holds one credit on the route's flow until the
21789            // module answers; the router takes it exactly like this.
21790            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21791                .forwarding
21792                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21793                .unwrap()
21794            else {
21795                panic!("the route is bound");
21796            };
21797            binding.flow.acquire_tagged(9, false).await.unwrap();
21798            let mut widened = session(1);
21799            widened.carriers.push(carrier(MAGIC, None));
21800            rig.sync(vec![widened]).await;
21801            assert!(rig.live(&route) && route.untouched());
21802            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21803            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21804            // The call's credit is still held on an open flow, so its answer
21805            // will be delivered: closing the route would have closed the flow.
21806            assert_eq!(binding.flow.in_flight(), 1);
21807            binding
21808                .flow
21809                .acquire_tagged(10, false)
21810                .await
21811                .expect("the flow is still open");
21812        }
21813
21814        /// A swap's superseded endpoint keeps its routes until drained; ending
21815        /// the scope closes them there too.
21816        #[tokio::test]
21817        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21818            let mut rig = rig().await;
21819            rig.sync(vec![session(1)]).await;
21820            let mut on_incumbent = rig
21821                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21822                .await;
21823
21824            // Swap plexus: register a candidate and cut over, leaving the
21825            // incumbent superseded with the route still on it.
21826            let (candidate, _candidate_rx) = wide_ctx(9);
21827            let registration = rig
21828                .handler
21829                .registry
21830                .register_candidate_with_control_ops(
21831                    manifest(PLEXUS, PROTOCOL_VERSION),
21832                    PROTOCOL_VERSION,
21833                    candidate.connection_id,
21834                    module_baseline_control_ops(),
21835                )
21836                .unwrap();
21837            rig.forwarding
21838                .register_candidate_module_connection(
21839                    candidate.connection_id,
21840                    PLEXUS.to_string(),
21841                    PROTOCOL_VERSION,
21842                    manifest_concurrency(&registration.manifest),
21843                    candidate.egress.clone(),
21844                )
21845                .unwrap();
21846            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21847            rig.handler
21848                .registry
21849                .promote_candidate(PLEXUS)
21850                .unwrap()
21851                .unwrap();
21852            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21853
21854            rig.sync(Vec::new()).await;
21855            assert!(!rig.live(&on_incumbent));
21856            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21857            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21858            let goodbye = incumbent_rx
21859                .try_recv()
21860                .expect("the superseded endpoint is told")
21861                .frame;
21862            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21863        }
21864    }
21865}
21866
21867#[cfg(test)]
21868mod concurrency_default_exposure_tests {
21869    use super::*;
21870
21871    fn hello_body(role_json: &str) -> Vec<u8> {
21872        format!(
21873            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":[]}}}}}}}}"#
21874        )
21875        .into_bytes()
21876    }
21877
21878    fn manifest_from(body: &[u8]) -> ModuleManifest {
21879        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21880        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21881            .expect("manifest parses")
21882    }
21883
21884    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21885
21886    #[test]
21887    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21888        let body = hello_body(&format!(
21889            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21890        ));
21891        let manifest = manifest_from(&body);
21892        // Precondition: serde really resolved it to the default, so the typed
21893        // manifest alone cannot answer the question this probe exists for.
21894        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21895        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21896    }
21897
21898    #[test]
21899    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21900        let body = hello_body(&format!(
21901            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21902        ));
21903        let manifest = manifest_from(&body);
21904        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21905        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21906    }
21907
21908    #[test]
21909    fn non_management_roles_are_never_reported() {
21910        let body = hello_body(
21911            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21912        );
21913        let manifest = manifest_from(&body);
21914        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21915    }
21916}