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    module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
376}
377
378/// Refusal labels passed to `observe_route_open_refusal` that mean the target
379/// module is not serving right now, and so open or extend an outage in the
380/// route outage tracker. Every one of them is only reachable after the target
381/// was found in the registry, which is what keeps an arbitrary client-chosen
382/// id from ever creating tracker state.
383///
384/// Deliberately absent: `not_registered` and `removed` (the id may be
385/// anything a client sent, and a removed module is gone on purpose),
386/// `protocol_none` (such a module never serves routes, so nothing is out),
387/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
388/// capability and admission-facts refusals (they refuse the caller, not a
389/// module outage), and `relay_reservation_failed` (its code ranges over
390/// capacity limits as well as a vanished connection). Capacity, breaker,
391/// relay-timeout and module-rejection refusals do not pass through that
392/// function at all; the breaker logs its own transitions.
393///
394/// The two not-serving refusals that bypass that function record themselves
395/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
396/// `required_capability_unprovided` is not tracked: the module itself is up,
397/// and the outage belongs to the missing provider.
398const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
399    "reloading",
400    "supervisor_not_live",
401    "registration_not_active",
402    "no_forwarding_connection",
403    "relay_send_failed",
404];
405
406/// Observe test request cancellation relative to the connection's cleanup.
407#[cfg(test)]
408struct ActivityRequestPause {
409    connection: ConnectionId,
410    started: tokio::sync::Notify,
411    cancelled: tokio::sync::Notify,
412    cleanup_started: std::sync::atomic::AtomicBool,
413    cancelled_after_cleanup: std::sync::atomic::AtomicBool,
414}
415
416#[cfg(test)]
417struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
418
419#[cfg(test)]
420impl Drop for ActivityRequestCancellation {
421    fn drop(&mut self) {
422        self.0.cancelled_after_cleanup.store(
423            self.0
424                .cleanup_started
425                .load(std::sync::atomic::Ordering::Acquire),
426            std::sync::atomic::Ordering::Release,
427        );
428        self.0.cancelled.notify_one();
429    }
430}
431
432/// A test hold: signal arrival, then wait for release on the holding thread.
433#[cfg(test)]
434type TestPause = (
435    tokio::sync::oneshot::Sender<()>,
436    std::sync::mpsc::Receiver<()>,
437);
438
439/// A test hook run once at a fixed point in a handler.
440#[cfg(test)]
441type TestHook = Box<dyn FnOnce() + Send>;
442
443/// A test hold for async code: signal arrival, then await release.
444#[cfg(test)]
445type AsyncTestPause = (
446    tokio::sync::oneshot::Sender<()>,
447    tokio::sync::oneshot::Receiver<()>,
448);
449
450/// Real channel-0 control handler for subc itself.
451#[derive(Clone)]
452pub struct ControlHandler {
453    #[cfg(test)]
454    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
455    /// Holds connection cleanup at a numbered point: 0 is just after the agent
456    /// declaration queue closes, 1 just after the registration channel is
457    /// forgotten.
458    #[cfg(test)]
459    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
460    /// Runs once in `route.open`'s launch-nonce attestation, right after the
461    /// nonce is resolved, to interleave a nonce withdrawal there.
462    #[cfg(test)]
463    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
464    /// Holds a registration channel's HELLO after its reader resolved the
465    /// channel and before the blocking HELLO handler starts.
466    #[cfg(test)]
467    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
468    /// Holds an agent command declaration at a numbered point in its handler.
469    #[cfg(test)]
470    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
471    claims: Arc<claims::Claims>,
472    registry: Arc<Registry>,
473    control_usage: Arc<Mutex<usage::ControlUsage>>,
474    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
475    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
476    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
477    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
478    config_review_admission_is_default: bool,
479    activity: Option<crate::activity::ActivityLedger>,
480    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
481    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
482    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
483    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
484    forwarding: Arc<ForwardingTable>,
485    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
486    supervisor: SupervisorHandle,
487    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
488    agent_declarations: agent_commands::Queues,
489    list_admission: Arc<tokio::sync::Semaphore>,
490    subc_capabilities: Arc<[String]>,
491    /// Daemon-wide route.bind relay budget. Used as the fallback when the
492    /// target module has no per-module override in
493    /// `route_bind_relay_timeouts`.
494    route_bind_relay_timeout: Duration,
495    /// Per-module route.bind relay budget overrides, keyed by module id. When
496    /// `handle_route_open` resolves the deadline for a target module, a
497    /// per-module entry wins over the daemon-wide value above.
498    route_bind_relay_timeouts: BTreeMap<String, Duration>,
499    /// Per-target-module bind-relay breaker state. Shared with the forwarding
500    /// table, which is where a new module connection resets it.
501    route_bind_breakers: RouteBindBreakers,
502    /// Live relay admissions keyed by target module. Shared through the
503    /// forwarding table so cloned or separately built handlers enforce one cap.
504    route_bind_concurrency: RouteBindConcurrency,
505    /// Start and end of each module's not-serving period as seen by
506    /// `route.open`, so an outage gets one line at each edge instead of only
507    /// the per-refusal INFO lines. Taken from the forwarding table, so every
508    /// handler built over one table shares it.
509    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
510    /// Consecutive relay timeouts that open a module's breaker.
511    route_bind_breaker_threshold: u32,
512    /// How long a breaker stays open before one probe is admitted.
513    route_bind_breaker_cooldown: Duration,
514    health_probe_timeout: Duration,
515    /// Central storage policy. When set, each registering module receives its
516    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
517    storage_config: Option<crate::daemon_config::StorageConfig>,
518    /// The machine id established at boot, served on every HELLO_ACK and on
519    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
520    /// changes the file, never this value. `None` serves no id.
521    machine_id: Option<crate::machine_id::MachineId>,
522    admission_facts_carrier_module_id: Option<String>,
523    admission_facts_targets: Option<Vec<String>>,
524    /// Scope records with their sync authorities and tombstones; see
525    /// `crate::scopes`. Shared by clones of this handler, so every connection
526    /// reads and writes one table.
527    scopes: Arc<RwLock<ScopeTable>>,
528    /// Wakes the expiry loop when an accepted scope change may have added a
529    /// deadline, so the loop can wait without ticking while no live scope has
530    /// one. A permit is stored when nothing waits, so no wake is lost.
531    scope_deadline_added: Arc<tokio::sync::Notify>,
532    /// The configured `scope_authority_owners`, kept so a rescan can report a
533    /// changed value as needing a daemon restart; rescan never applies it.
534    scope_authority_owners: Vec<String>,
535    federated_scope_owner: String,
536    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
537    privileged_operator_prompt: PrivilegedOperatorPrompt,
538    /// The local and peer address of each accepted TCP client connection, read
539    /// from the daemon's own socket, so a privileged request can name its caller.
540    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
541    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
542    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
543    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
544    config_desktop_stamps:
545        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
546    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
547    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
548    pub(crate) operator_apps:
549        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
550    /// One launch entry per app, behind a leaf lock: no other lock is taken
551    /// while it is held. Entries are memory-only, so a daemon or
552    /// installed-service restart drops them and a relaunched daemon never
553    /// mistakes an older process for its own launch.
554    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
555    /// Serializes `app.open` launches: the liveness check in the decision and
556    /// the later publish must not interleave across concurrent calls, or two
557    /// calls could both launch and the second publish would orphan the first
558    /// process. Refusals and `already_running` answers share the same lock;
559    /// `app.open` is rare, so the cost is negligible.
560    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
561    // Portable wire samples exercise dispatch without starting an OS process.
562    #[cfg(test)]
563    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
564    #[cfg(test)]
565    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
566    #[cfg(test)]
567    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
568    #[cfg(test)]
569    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
570    #[cfg(test)]
571    recovery_exit_test_completed: Option<fn(u64)>,
572    #[cfg(test)]
573    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
574    #[cfg(test)]
575    recovery_exit_test_quiet_retry: bool,
576    #[cfg(test)]
577    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
578    #[cfg(test)]
579    config_delivery_test_wakes:
580        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
581    #[cfg(all(test, unix))]
582    config_delivery_test_idle:
583        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
584    /// Test-only Windows signature and flash hooks. Production builds carry
585    /// neither: with the publisher unset, the production table never reaches
586    /// verification, and the default attention hook only logs.
587    #[allow(dead_code)]
588    #[cfg(windows)]
589    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
590    #[allow(dead_code)]
591    #[cfg(windows)]
592    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
593    /// Test-only tracking fault hook: makes opening the tracking handle on
594    /// the launched pid fail, so a test can prove an untrackable launch is
595    /// stopped rather than left running.
596    #[allow(dead_code)]
597    #[cfg(windows)]
598    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
599    /// Test-only count of Windows spawn attempts, so a test can prove a
600    /// refused launch started no process. Unit tests only.
601    #[cfg(all(test, windows))]
602    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
603    #[cfg(test)]
604    caller_lookup: Option<TestCallerLookup>,
605    /// The launch nonce each module connection presented at HELLO, which is how
606    /// a `scope.sync` is matched to the owner's current launch.
607    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
608    rescan: Option<SupervisorRescanContext>,
609    connected_clients: ConnectedClients,
610    counters: DaemonCounters,
611    /// Why this daemon serves no local endpoint, when binding one failed. `None`
612    /// when the endpoint is served, and also on a handler that was never told.
613    local_endpoint_unavailable: Option<String>,
614    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
615    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
616    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
617    /// their usual severity (see [`log_requirement_events`]). A handler built
618    /// without one has a flag that is never set.
619    daemon_shutdown: DaemonShutdownFlag,
620    daemon_provenance: DaemonProvenanceFacts,
621    #[cfg(test)]
622    control_dispatch_delay: Option<Duration>,
623    #[cfg(test)]
624    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
625    /// Holds `route.open` after the route.bind is queued to the module and
626    /// before it is marked enqueued, so a test can make the module's reply (or
627    /// a client teardown) land exactly inside that window.
628    #[cfg(test)]
629    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
630    /// Holds a HELLO after its registry entry is reserved and before its
631    /// forwarding endpoint is installed, so a test can read the catalog and
632    /// open routes while the module is registered but not yet routable. A
633    /// blocking barrier because the HELLO handler is synchronous; the test
634    /// runs the HELLO on its own thread.
635    #[cfg(test)]
636    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
637    #[cfg(test)]
638    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
639    #[cfg(test)]
640    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
641    #[cfg(test)]
642    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
643    #[cfg(test)]
644    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
645}
646
647impl fmt::Debug for ControlHandler {
648    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649        f.debug_struct("ControlHandler")
650            .field("registry", &self.registry)
651            .field("forwarding", &self.forwarding)
652            .field("process_liveness", &self.process_liveness.is_some())
653            .field("supervisor", &self.supervisor)
654            .field("subc_capabilities", &self.subc_capabilities)
655            .finish()
656    }
657}
658
659struct RouteOpenRequest {
660    target: RouteTarget,
661    identity: BindIdentity,
662    consumer_identity: Option<ConsumerIdentity>,
663    consumer_capabilities: Option<Vec<String>>,
664    role_versions: Option<BTreeMap<String, String>>,
665    busy_refusals: Option<bool>,
666    admission_facts: Option<serde_json::Value>,
667    scope: Option<ScopeSelector>,
668    accepts_close_reasons: Option<Vec<String>>,
669}
670
671#[derive(Clone, Copy)]
672enum RouteOpenPhase {
673    Admission,
674    ProjectRoot,
675    EgressReservation,
676    BindSend,
677    BindAckWait,
678}
679
680/// Store elapsed time for each route-open phase, including attempts that end
681/// in an early refusal or backend error. Admission also includes rechecks and
682/// commit bookkeeping performed between the other timed phases.
683struct RouteOpenTimings {
684    module_id: String,
685    principal: String,
686    admission: Duration,
687    project_root: Duration,
688    egress_reservation: Duration,
689    bind_send: Duration,
690    bind_ack_wait: Duration,
691    phase: Option<RouteOpenPhase>,
692    phase_started_at: Instant,
693}
694
695impl RouteOpenTimings {
696    fn new() -> Self {
697        Self {
698            module_id: String::new(),
699            // Refusals before attestation must not claim a verified principal.
700            principal: "unresolved".to_string(),
701            admission: Duration::ZERO,
702            project_root: Duration::ZERO,
703            egress_reservation: Duration::ZERO,
704            bind_send: Duration::ZERO,
705            bind_ack_wait: Duration::ZERO,
706            phase: Some(RouteOpenPhase::Admission),
707            phase_started_at: Instant::now(),
708        }
709    }
710
711    fn finish(&mut self) {
712        let elapsed = self.phase_started_at.elapsed();
713        match self.phase.take() {
714            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
715            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
716            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
717            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
718            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
719            None => {}
720        }
721    }
722
723    fn enter(&mut self, phase: RouteOpenPhase) {
724        self.finish();
725        self.phase = Some(phase);
726        self.phase_started_at = Instant::now();
727    }
728}
729
730struct RouteBindReservationGuard {
731    forwarding: Arc<ForwardingTable>,
732    endpoint: ModuleEndpointId,
733    relay_corr: u64,
734    armed: bool,
735}
736
737struct ModuleControlRpcGuard {
738    forwarding: Arc<ForwardingTable>,
739    endpoint: ModuleEndpointId,
740    corr: u64,
741    armed: bool,
742}
743
744impl ModuleControlRpcGuard {
745    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
746        Self {
747            forwarding,
748            endpoint,
749            corr,
750            armed: true,
751        }
752    }
753
754    fn disarm(&mut self) {
755        self.armed = false;
756    }
757}
758
759impl Drop for ModuleControlRpcGuard {
760    fn drop(&mut self) {
761        if self.armed {
762            let _ = self
763                .forwarding
764                .cancel_module_control_rpc(self.endpoint, self.corr);
765        }
766    }
767}
768
769impl RouteBindReservationGuard {
770    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
771        Self {
772            forwarding,
773            endpoint,
774            relay_corr,
775            armed: true,
776        }
777    }
778
779    fn release_and_disarm(&mut self) {
780        if !self.armed {
781            return;
782        }
783        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
784            self.endpoint,
785            self.relay_corr,
786            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
787        ) {
788            send_goodbye_target_best_effort(
789                &self.forwarding.counters(),
790                &target,
791                "canceled route.bind",
792            );
793        }
794        self.armed = false;
795    }
796
797    fn disarm(&mut self) {
798        self.armed = false;
799    }
800}
801
802impl Drop for RouteBindReservationGuard {
803    fn drop(&mut self) {
804        self.release_and_disarm();
805    }
806}
807
808/// Per-target-module circuit breaker around the `route.bind` relay.
809///
810/// The connection reader is serial per connection, so a module whose `on_bind`
811/// sits on the ack blocks every LATER frame on the connections that call it,
812/// including calls to unrelated modules. This does not make any module's bind
813/// fast; it stops the daemon paying the full budget again and again for a
814/// condition it has already observed.
815///
816/// State is keyed by TARGET MODULE and shared by every connection: a wedged
817/// module wedges everyone, so what one connection learned should protect the
818/// rest.
819///
820/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
821/// relay to that module has actually timed out, and is removed again when a
822/// relay is accepted or the module reconnects, so it cannot grow with traffic
823/// or with modules that behave.
824///
825/// # Why a `std` mutex here is not the head-of-line defect again
826///
827/// Acquisition never awaits. The critical section is a hash lookup plus a few
828/// integer updates, with no I/O and no `.await` inside it, so a reader task
829/// cannot be descheduled behind it the way it can behind
830/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
831/// primitive, held for the same kind of work, as the refusal counter this very
832/// path already increments.
833///
834/// It is also NOT on the data-plane splice path: only `route.open` and module
835/// registration touch it, so bound-route frames gain no state check and no
836/// contention.
837#[derive(Debug, Clone, Default)]
838pub(crate) struct RouteBindBreakers {
839    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
840}
841
842#[derive(Debug, Clone, Default)]
843pub(crate) struct RouteBindConcurrency {
844    modules: Arc<Mutex<HashMap<String, usize>>>,
845}
846
847struct RouteBindConcurrencyGuard {
848    concurrency: RouteBindConcurrency,
849    module_id: String,
850}
851
852impl RouteBindConcurrency {
853    /// Admit without waiting. Waiting here would move the bind stall from the
854    /// module reply to a semaphore and restore reader head-of-line blocking.
855    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
856        let mut modules = self
857            .modules
858            .lock()
859            .expect("route.bind concurrency mutex poisoned");
860        let in_flight = modules.entry(module_id.to_string()).or_default();
861        if *in_flight >= limit {
862            return Err(*in_flight);
863        }
864        *in_flight += 1;
865        Ok(RouteBindConcurrencyGuard {
866            concurrency: self.clone(),
867            module_id: module_id.to_string(),
868        })
869    }
870}
871
872impl Drop for RouteBindConcurrencyGuard {
873    fn drop(&mut self) {
874        let mut modules = self
875            .concurrency
876            .modules
877            .lock()
878            .expect("route.bind concurrency mutex poisoned");
879        let remove = {
880            let in_flight = modules
881                .get_mut(&self.module_id)
882                .expect("admitted route.bind has a concurrency entry");
883            *in_flight -= 1;
884            *in_flight == 0
885        };
886        if remove {
887            modules.remove(&self.module_id);
888        }
889    }
890}
891
892#[derive(Debug, Default)]
893struct ModuleBreakerState {
894    /// Relay timeouts observed with no accepted relay in between.
895    consecutive_timeouts: u32,
896    /// `Some` while the breaker is open: the instant the cooldown expires and
897    /// the next arrival may probe. `None` means closed.
898    cooldown_until: Option<Instant>,
899    /// A half-open probe has been admitted and has not settled yet. This is
900    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
901    /// that read the cooldown, so concurrent opens arriving at the moment the
902    /// cooldown expires cannot all decide that they are the probe.
903    probe_in_flight: Option<Arc<()>>,
904}
905
906/// What the breaker decided for one `route.open`, before any relay work.
907enum RouteBindAdmission<'a> {
908    Admitted {
909        guard: RouteBindBreakerGuard<'a>,
910        /// This open is the single half-open probe, so the transition is worth
911        /// one log line.
912        probe: bool,
913    },
914    Refused {
915        consecutive_timeouts: u32,
916        /// What is left of the cooldown. Zero when the refusal is because the
917        /// one probe is already in flight rather than because the cooldown has
918        /// not elapsed.
919        retry_in: Duration,
920        probe_in_flight: bool,
921    },
922}
923
924/// An outstanding admission, which must be told how its relay settled.
925///
926/// `Drop` settles it as inconclusive, so an early return between admission and
927/// the relay -- or the whole handler being cancelled when the client
928/// disconnects -- releases a half-open probe slot instead of leaving the
929/// breaker wedged half-open with no further probes.
930struct RouteBindBreakerGuard<'a> {
931    breakers: RouteBindBreakers,
932    module_id: &'a str,
933    probe_token: Option<Arc<()>>,
934    settled: bool,
935}
936
937impl RouteBindBreakerGuard<'_> {
938    /// The module answered within the budget and took the bind. THE ONLY
939    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
940    /// breaker, which is a transition worth logging.
941    fn record_accepted(&mut self) -> bool {
942        self.settled = true;
943        self.breakers.record_accepted(self.module_id)
944    }
945
946    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
947    /// COUNTS TOWARD OPENING.
948    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
949        self.settled = true;
950        self.breakers.record_timeout(
951            self.module_id,
952            self.probe_token.as_ref(),
953            threshold,
954            cooldown,
955        )
956    }
957
958    /// Everything else: the module REJECTED the bind, its connection went away
959    /// mid-relay, or the waiter was cancelled.
960    ///
961    /// None of these is evidence that a module is slow, and each already has
962    /// its own refusal with its own code. A module that rejects a bind in
963    /// microseconds is healthy and must never be convicted for it; a module
964    /// that died has said nothing about the module that replaces it. So these
965    /// neither increment nor reset the count -- they only release a probe slot.
966    fn record_inconclusive(&mut self) {
967        self.settled = true;
968        self.breakers
969            .record_inconclusive(self.module_id, self.probe_token.as_ref());
970    }
971}
972
973impl Drop for RouteBindBreakerGuard<'_> {
974    fn drop(&mut self) {
975        if !self.settled {
976            self.breakers
977                .record_inconclusive(self.module_id, self.probe_token.as_ref());
978        }
979    }
980}
981
982/// The breaker moved to open, reported so the caller can log it outside the
983/// lock. Opening is rare and load-bearing; the refusals that follow are
984/// frequent and are counted rather than logged.
985struct BreakerOpened {
986    consecutive_timeouts: u32,
987    /// True when a failed probe re-opened an already-open breaker, which reads
988    /// very differently in a log from a first opening.
989    reopened_after_probe: bool,
990}
991
992impl RouteBindBreakers {
993    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
994        self.modules
995            .lock()
996            .expect("route.bind breaker mutex poisoned")
997    }
998
999    /// Decide whether this `route.open` may attempt its relay. Takes the map
1000    /// lock and nothing else, and never awaits.
1001    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
1002        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
1003            probe: probe_token.is_some(),
1004            guard: RouteBindBreakerGuard {
1005                breakers: self.clone(),
1006                module_id,
1007                probe_token,
1008                settled: false,
1009            },
1010        };
1011
1012        let mut modules = self.lock();
1013        let Some(state) = modules.get_mut(module_id) else {
1014            return admitted(None);
1015        };
1016        let Some(cooldown_until) = state.cooldown_until else {
1017            return admitted(None);
1018        };
1019        if state.probe_in_flight.is_some() {
1020            return RouteBindAdmission::Refused {
1021                consecutive_timeouts: state.consecutive_timeouts,
1022                retry_in: Duration::ZERO,
1023                probe_in_flight: true,
1024            };
1025        }
1026        let now = Instant::now();
1027        if now < cooldown_until {
1028            return RouteBindAdmission::Refused {
1029                consecutive_timeouts: state.consecutive_timeouts,
1030                retry_in: cooldown_until - now,
1031                probe_in_flight: false,
1032            };
1033        }
1034        let token = Arc::new(());
1035        state.probe_in_flight = Some(Arc::clone(&token));
1036        admitted(Some(token))
1037    }
1038
1039    fn record_accepted(&self, module_id: &str) -> bool {
1040        self.lock()
1041            .remove(module_id)
1042            .is_some_and(|state| state.cooldown_until.is_some())
1043    }
1044
1045    fn record_timeout(
1046        &self,
1047        module_id: &str,
1048        probe_token: Option<&Arc<()>>,
1049        threshold: u32,
1050        cooldown: Duration,
1051    ) -> Option<BreakerOpened> {
1052        let mut modules = self.lock();
1053        let state = modules.entry(module_id.to_string()).or_default();
1054        let was_open = state.cooldown_until.is_some();
1055        let was_probe = Self::owns_probe(state, probe_token);
1056        if was_probe {
1057            state.probe_in_flight = None;
1058        }
1059        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
1060        if state.consecutive_timeouts < threshold {
1061            return None;
1062        }
1063        state.cooldown_until = Some(Instant::now() + cooldown);
1064        Some(BreakerOpened {
1065            consecutive_timeouts: state.consecutive_timeouts,
1066            reopened_after_probe: was_open && was_probe,
1067        })
1068    }
1069
1070    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
1071        // A relay can finish after the breaker was reset or after it opened
1072        // again and started a new probe. Only the guard whose token matches the
1073        // active probe may release it, so a late relay never frees a newer probe.
1074        state
1075            .probe_in_flight
1076            .as_ref()
1077            .zip(token)
1078            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
1079    }
1080
1081    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
1082        if let Some(state) = self.lock().get_mut(module_id) {
1083            if Self::owns_probe(state, probe_token) {
1084                state.probe_in_flight = None;
1085            }
1086        }
1087    }
1088
1089    /// Discard what was learned about a module, because the process it was
1090    /// learned about is gone. Returns the discarded count when it was non-zero.
1091    ///
1092    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
1093    /// `module_id` is a configuration identity that outlives any particular
1094    /// child; what the breaker observed was the process behind the module
1095    /// connection of the moment. When a new connection registers under that id
1096    /// the verdict's subject no longer exists, so the verdict is stale by
1097    /// construction rather than merely likely to be wrong. Keeping it would
1098    /// apply a dead process's record to a live one, which is the same defect
1099    /// class this breaker exists to stop the daemon committing.
1100    ///
1101    /// A half-open probe in flight is discarded with the rest: it was a
1102    /// question about the old process.
1103    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
1104        self.lock()
1105            .remove(module_id)
1106            .map(|state| state.consecutive_timeouts)
1107            .filter(|discarded| *discarded > 0)
1108    }
1109
1110    /// Open breakers, for the `server.describe` counters object. `None` when
1111    /// none is open, so the key stays absent rather than present-and-empty.
1112    ///
1113    /// This is the operator's answer to "is this module refusing instantly or
1114    /// is it fine?", which look identical from a client that retries and then
1115    /// succeeds.
1116    fn open_snapshot(&self) -> Option<serde_json::Value> {
1117        let now = Instant::now();
1118        let modules = self.lock();
1119        let open = modules
1120            .iter()
1121            .filter_map(|(module_id, state)| {
1122                let cooldown_until = state.cooldown_until?;
1123                Some((
1124                    module_id.clone(),
1125                    serde_json::json!({
1126                        "consecutive_timeouts": state.consecutive_timeouts,
1127                        "cooldown_remaining_ms":
1128                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
1129                        "probe_in_flight": state.probe_in_flight.is_some(),
1130                    }),
1131                ))
1132            })
1133            .collect::<serde_json::Map<String, serde_json::Value>>();
1134        (!open.is_empty()).then_some(serde_json::Value::Object(open))
1135    }
1136}
1137
1138impl ControlHandler {
1139    pub(crate) fn install_registration_service(
1140        &self,
1141        router: std::sync::Weak<crate::Router>,
1142        auth: crate::server::ServerAuth,
1143    ) {
1144        self.supervisor.install_registration_service(router, auth);
1145    }
1146    pub fn new(registry: Arc<Registry>) -> Self {
1147        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
1148    }
1149
1150    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
1151        let counters = forwarding.counters();
1152        // Taken from the forwarding table rather than created here, so that the
1153        // breaker a `route.open` consults is the same one a module's
1154        // registration resets, however many handlers are built over one table.
1155        let route_bind_breakers = forwarding.route_bind_breakers();
1156        let route_bind_concurrency = forwarding.route_bind_concurrency();
1157        let route_outages = forwarding.route_outages();
1158        Self {
1159            registry,
1160            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
1161            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
1162            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1163            #[cfg(test)]
1164            activity_request_pause: Arc::new(Mutex::new(None)),
1165            #[cfg(test)]
1166            cleanup_pause: Arc::new(Mutex::new(None)),
1167            #[cfg(test)]
1168            after_nonce_attestation: Arc::new(Mutex::new(None)),
1169            #[cfg(test)]
1170            hello_ingress_pause: Arc::new(Mutex::new(None)),
1171            #[cfg(test)]
1172            agent_commands_pause: Arc::new(Mutex::new(None)),
1173            claims: Arc::new(claims::Claims::default()),
1174            config_runtime: None,
1175            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
1176            config_review_admission_is_default: true,
1177            activity: None,
1178            activity_streams: Arc::new(Mutex::new(HashMap::new())),
1179            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
1180            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
1181            scope_streams: Arc::new(Mutex::new(HashMap::new())),
1182            forwarding,
1183            process_liveness: None,
1184            supervisor: SupervisorHandle::new(),
1185            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
1186                env!("CARGO_PKG_VERSION").to_owned(),
1187            )),
1188            agent_declarations: agent_commands::Queues::default(),
1189            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
1190            subc_capabilities: Arc::from([
1191                CAP_MANIFEST_REGISTRATION.to_string(),
1192                CAP_CHANNEL_LIFECYCLE.to_string(),
1193                CAP_PING_PONG.to_string(),
1194                CAP_SESSION_ATTACH.to_string(),
1195                CAP_ADMISSION_FACTS_RELAY.to_string(),
1196                CAP_SCOPES_V1.to_string(),
1197                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
1198                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1199                PEER_BUILD_CAPABILITY.to_string(),
1200                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1201                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1202                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1203                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1204                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1205                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1206                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1207                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1208                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1209                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1210                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1211                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1212            ]),
1213            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1214            route_bind_relay_timeouts: BTreeMap::new(),
1215            route_bind_breakers,
1216            route_bind_concurrency,
1217            route_outages,
1218            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1219            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1220            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1221            storage_config: None,
1222            machine_id: None,
1223            admission_facts_carrier_module_id: None,
1224            admission_facts_targets: None,
1225            scopes: Arc::new(RwLock::new(ScopeTable::new(
1226                crate::daemon_config::default_scope_authority_owners(),
1227            ))),
1228            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1229            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1230            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1231            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1232            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1233            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1234            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1235            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1236            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1237            local_connections: Arc::new(Mutex::new(HashSet::new())),
1238            operator_app_policy: Default::default(),
1239            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1240            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1241            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1242            #[cfg(test)]
1243            app_open_test_platform: None,
1244            #[cfg(test)]
1245            app_open_test_launch: None,
1246            #[cfg(test)]
1247            config_review_test_reply: None,
1248            #[cfg(test)]
1249            recovery_exit_test_after_step: None,
1250            #[cfg(test)]
1251            recovery_exit_test_completed: None,
1252            #[cfg(test)]
1253            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1254            #[cfg(test)]
1255            recovery_exit_test_quiet_retry: false,
1256            #[cfg(test)]
1257            recovery_exit_test_retry_pause: None,
1258            #[cfg(test)]
1259            config_delivery_test_wakes: None,
1260            #[cfg(all(test, unix))]
1261            config_delivery_test_idle: None,
1262            #[cfg(windows)]
1263            windows_verify: None,
1264            #[cfg(windows)]
1265            windows_flash: None,
1266            #[cfg(windows)]
1267            windows_track: None,
1268            #[cfg(all(test, windows))]
1269            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1270            #[cfg(test)]
1271            caller_lookup: None,
1272            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1273            rescan: None,
1274            connected_clients: ConnectedClients::new(),
1275            local_endpoint_unavailable: None,
1276            counters,
1277            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1278            daemon_shutdown: DaemonShutdownFlag::default(),
1279            daemon_provenance: DaemonProvenanceFacts::default(),
1280            #[cfg(test)]
1281            control_dispatch_delay: None,
1282            #[cfg(test)]
1283            provenance_probe_override: None,
1284            #[cfg(test)]
1285            route_bind_relay_sent_hold: None,
1286            #[cfg(test)]
1287            hello_registry_to_forwarding_hold: None,
1288            #[cfg(test)]
1289            hello_ack_to_publication_hold: None,
1290            #[cfg(test)]
1291            hello_before_publication_hold: None,
1292            #[cfg(test)]
1293            hello_after_launch_check_hold: None,
1294            #[cfg(test)]
1295            hello_inside_publication_hold: None,
1296        }
1297    }
1298
1299    /// Set the central storage policy: registering modules then receive their
1300    /// resolved storage descriptor in HELLO_ACK.
1301    pub fn with_storage_config(
1302        mut self,
1303        storage_config: Option<crate::daemon_config::StorageConfig>,
1304    ) -> Self {
1305        self.storage_config = storage_config;
1306        self
1307    }
1308
1309    /// Open the ledger on its own writer thread; an unavailable sink does not
1310    /// prevent the daemon from serving routing or supervisor requests.
1311    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1312        self.activity = Some(crate::activity::ActivityLedger::open(
1313            run_dir.join("activity.jsonl"),
1314            incarnation,
1315        ));
1316        self.supervisor.set_activity(self.activity.clone());
1317        self
1318    }
1319
1320    /// Set the machine id served to every registering module (HELLO_ACK) and on
1321    /// `server.describe`.
1322    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1323        self.machine_id = machine_id;
1324        self
1325    }
1326
1327    /// Configure the exact reserved module and target ids permitted to relay
1328    /// opaque admission facts. Config-file loading validates this authority;
1329    /// this builder keeps the same policy available to embedded test daemons.
1330    pub fn with_admission_facts_config(
1331        mut self,
1332        carrier_module_id: Option<String>,
1333        targets: Option<Vec<String>>,
1334    ) -> Self {
1335        self.admission_facts_carrier_module_id = carrier_module_id;
1336        self.admission_facts_targets = targets;
1337        self
1338    }
1339
1340    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1341    /// Replaces the scope table with an empty one under the new list, so call it
1342    /// while building the handler, before any module can sync.
1343    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1344        self.scopes = Arc::new(RwLock::new(
1345            ScopeTable::new(owners.iter().cloned())
1346                .with_federated_owner(self.federated_scope_owner.clone()),
1347        ));
1348        self.scope_authority_owners = owners;
1349        self
1350    }
1351
1352    /// Set the exclusive federated owner while building the handler, before syncs.
1353    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1354        self.scopes = Arc::new(RwLock::new(
1355            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1356                .with_federated_owner(owner.clone()),
1357        ));
1358        self.federated_scope_owner = owner;
1359        self
1360    }
1361
1362    /// Set the startup policy before installing the rescan context or serving requests.
1363    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1364        self.privileged_operator_prompt = mode;
1365        self
1366    }
1367
1368    /// Override the route.bind relay timeout. Used by tests that assert the
1369    /// timeout path so they don't block on the production-safe default.
1370    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1371        self.route_bind_relay_timeout = timeout;
1372        self
1373    }
1374
1375    /// Install per-module route.bind relay budget overrides. A module id
1376    /// listed here wins over the daemon-wide default set via
1377    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1378    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1379    /// the same `Duration` the bind path will use.
1380    pub fn with_route_bind_relay_timeouts(
1381        mut self,
1382        timeouts: impl IntoIterator<Item = (String, Duration)>,
1383    ) -> Self {
1384        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1385        self
1386    }
1387
1388    /// Resolve the route.bind relay budget for a specific target module id.
1389    /// Per-module overrides win; the daemon-wide value (set via
1390    /// `with_route_bind_relay_timeout` or the built-in default) is the
1391    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1392    /// the same resolution `handle_route_open` will use.
1393    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1394        self.route_bind_relay_timeouts
1395            .get(module_id)
1396            .copied()
1397            .unwrap_or(self.route_bind_relay_timeout)
1398    }
1399
1400    /// Override the per-module bind-relay breaker policy.
1401    ///
1402    /// Used by tests, which cannot spend three production budgets opening a
1403    /// breaker or twenty seconds waiting for its cooldown. The production
1404    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1405    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1406    /// reasoning for the numbers.
1407    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1408        self.route_bind_breaker_threshold = threshold.max(1);
1409        self.route_bind_breaker_cooldown = cooldown;
1410        self
1411    }
1412
1413    #[cfg(test)]
1414    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1415        self.health_probe_timeout = timeout;
1416        self
1417    }
1418
1419    #[cfg(test)]
1420    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1421        self.control_dispatch_delay = Some(delay);
1422        self
1423    }
1424
1425    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1426    /// announce it is parked, once to be released. Build the barrier for two
1427    /// parties, the test being the other one.
1428    #[cfg(test)]
1429    pub(crate) fn with_route_bind_relay_sent_hold(
1430        mut self,
1431        hold: Arc<tokio::sync::Barrier>,
1432    ) -> Self {
1433        self.route_bind_relay_sent_hold = Some(hold);
1434        self
1435    }
1436
1437    /// A HELLO waits on `hold` twice between reserving its registry entry and
1438    /// installing its forwarding endpoint: once to announce it is parked, once
1439    /// to be released. Build the barrier for two parties, the test being the
1440    /// other one, and run the HELLO on a thread of its own.
1441    #[cfg(test)]
1442    pub(crate) fn with_hello_registry_to_forwarding_hold(
1443        mut self,
1444        hold: Arc<std::sync::Barrier>,
1445    ) -> Self {
1446        self.hello_registry_to_forwarding_hold = Some(hold);
1447        self
1448    }
1449
1450    #[cfg(test)]
1451    fn hold_between_registry_and_forwarding(&self) {
1452        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1453            hold.wait();
1454            hold.wait();
1455        }
1456    }
1457
1458    /// Park after the ACK is queued and forwarding is installed, until a test
1459    /// has read the ACK and issued a registry lookup from another connection.
1460    #[cfg(test)]
1461    fn hold_between_ack_and_publication(&self) {
1462        if let Some(hold) = &self.hello_ack_to_publication_hold {
1463            hold.wait();
1464            hold.wait();
1465        }
1466    }
1467
1468    #[cfg(all(test, unix))]
1469    pub(crate) fn with_hello_before_publication_hold(
1470        mut self,
1471        hold: Arc<std::sync::Barrier>,
1472    ) -> Self {
1473        self.hello_before_publication_hold = Some(hold);
1474        self
1475    }
1476
1477    #[cfg(all(test, unix))]
1478    pub(crate) fn with_hello_after_launch_check_hold(
1479        mut self,
1480        hold: Arc<std::sync::Barrier>,
1481    ) -> Self {
1482        self.hello_after_launch_check_hold = Some(hold);
1483        self
1484    }
1485
1486    #[cfg(all(test, unix))]
1487    pub(crate) fn with_hello_inside_publication_hold(
1488        mut self,
1489        hold: Arc<std::sync::Barrier>,
1490    ) -> Self {
1491        self.hello_inside_publication_hold = Some(hold);
1492        self
1493    }
1494
1495    pub fn with_process_liveness(
1496        mut self,
1497        process_liveness: Arc<dyn ModuleProcessLiveness>,
1498    ) -> Self {
1499        self.process_liveness = Some(process_liveness);
1500        self
1501    }
1502
1503    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1504        self.supervisor = supervisor;
1505        if let Some(owner) = &self.config_runtime {
1506            self.supervisor.install_binding_retirement(owner);
1507        }
1508        self.supervisor.set_activity(self.activity.clone());
1509        self
1510    }
1511
1512    pub fn with_daemon_provenance(
1513        mut self,
1514        pid: u32,
1515        started_at_ms: u64,
1516        executable_path: Option<PathBuf>,
1517        build_git_sha: Option<String>,
1518        build_lock_digest: Option<String>,
1519    ) -> Self {
1520        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1521        let process_start_time = process_start_time(pid);
1522        self.daemon_provenance = DaemonProvenanceFacts {
1523            build: DaemonBuildProvenance {
1524                build_git_sha,
1525                build_lock_digest,
1526            },
1527            pid: Some(pid),
1528            started_at_ms: Some(started_at_ms),
1529            start_clock: None,
1530            executable_path,
1531            executable_identity,
1532            process_start_time,
1533            probe: ExecutableIdentityProbe::default(),
1534        };
1535        self
1536    }
1537
1538    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1539        self.daemon_provenance.start_clock = Some(clock);
1540        self
1541    }
1542
1543    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1544    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1545        self.scopes
1546            .write()
1547            .unwrap_or_else(|poisoned| poisoned.into_inner())
1548            .set_wall_clock(Arc::new(clock));
1549        self
1550    }
1551
1552    #[cfg(test)]
1553    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1554        self.provenance_probe_override = Some(result);
1555        self
1556    }
1557
1558    /// Install the configured module set and its reserved capability bindings.
1559    /// Bindings are configuration-scoped and may point at a provider that has not
1560    /// been installed yet, so this does not require the bound module to exist.
1561    pub fn with_capability_config(
1562        self,
1563        modules: impl IntoIterator<Item = (String, bool)>,
1564        reserved_capabilities: BTreeMap<String, String>,
1565    ) -> Self {
1566        self.capability_evaluator
1567            .configure(modules, reserved_capabilities);
1568        self
1569    }
1570
1571    /// Share the supervisor's daemon-shutdown flag with this handler, so
1572    /// requirement changes after the daemon has begun its announced shutdown
1573    /// are not reported as faults.
1574    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1575        self.daemon_shutdown = flag;
1576        self
1577    }
1578
1579    pub fn with_supervisor_rescan(
1580        mut self,
1581        supervisor: Supervisor,
1582        config_path: impl Into<PathBuf>,
1583        configured_port: Option<u16>,
1584    ) -> Self {
1585        self.rescan = Some(SupervisorRescanContext {
1586            supervisor,
1587            config_path: config_path.into(),
1588            configured_port,
1589            storage_config: self.storage_config.clone(),
1590            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1591            admission_facts_targets: self.admission_facts_targets.clone(),
1592            scope_authority_owners: self.scope_authority_owners.clone(),
1593            federated_scope_owner: self.federated_scope_owner.clone(),
1594            privileged_operator_prompt: self.privileged_operator_prompt,
1595            generation: Arc::default(),
1596            module_entries: Arc::default(),
1597        });
1598        self
1599    }
1600
1601    pub(crate) fn with_supervisor_rescan_entries(
1602        self,
1603        modules: &[crate::daemon_config::ConfiguredModule],
1604    ) -> Self {
1605        if let Some(context) = &self.rescan {
1606            let mut entries = context
1607                .module_entries
1608                .lock()
1609                .unwrap_or_else(|e| e.into_inner());
1610            entries.seed(modules);
1611        }
1612        self
1613    }
1614
1615    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1616        self.connected_clients = connected_clients;
1617        self
1618    }
1619
1620    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1621    /// an operator can see a bind failure without reading the daemon log.
1622    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1623        self.local_endpoint_unavailable = reason;
1624        self
1625    }
1626
1627    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1628        Arc::clone(&self.forwarding)
1629    }
1630
1631    pub(crate) fn counters(&self) -> DaemonCounters {
1632        self.counters.clone()
1633    }
1634
1635    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1636    /// requirement event without depending on an operator polling a status command.
1637    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1638        let handler = Arc::downgrade(&self);
1639        let evaluator = self.capability_evaluator.clone();
1640        tokio::spawn(async move {
1641            loop {
1642                evaluator.wait_for_change_or_deadline().await;
1643                let Some(handler) = handler.upgrade() else {
1644                    break;
1645                };
1646                handler.refresh_capability_requirements();
1647            }
1648        });
1649    }
1650
1651    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1652    /// deadline passed during sleep is enforced on the first tick after wake.
1653    /// While no live scope carries a deadline the loop waits for an accepted
1654    /// scope change instead of ticking, so a daemon without deadlines never
1655    /// wakes for expiry.
1656    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1657        let context = scope_expiry::ScopeExpiryContext::new(&self);
1658        let deadline_added = self.scope_deadline_added.clone();
1659        tokio::spawn(async move {
1660            loop {
1661                if !context.has_deadlines() {
1662                    deadline_added.notified().await;
1663                    continue;
1664                }
1665                tokio::time::sleep(Duration::from_secs(1)).await;
1666                if let Err(error) = context.sweep() {
1667                    warn!(%error, "scope expiry sweep failed");
1668                }
1669            }
1670        });
1671    }
1672
1673    #[cfg(test)]
1674    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1675        scope_expiry::ScopeExpiryContext::new(self).sweep()
1676    }
1677
1678    fn publish_scope_changes(
1679        &self,
1680        changes: &[crate::scopes::ScopeTagChange],
1681        expired: &[crate::scopes::ScopeExpired],
1682    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1683        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1684    }
1685
1686    fn runtime_capability_snapshot(
1687        &self,
1688    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1689        let runtime = self
1690            .supervisor
1691            .list()
1692            .into_iter()
1693            .map(|module| {
1694                let status = module.status().map_err(|err| {
1695                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1696                })?;
1697                Ok(RuntimeModule {
1698                    module_id: status.module_id,
1699                    state: status.state,
1700                    enabled: status.enabled,
1701                })
1702            })
1703            .collect::<Result<Vec<_>, RouterError>>()?;
1704        // Include every registration, published or not. The capability
1705        // evaluator counts a module as providing its capabilities as soon as it
1706        // has registered, even before `catalog.list` shows it, so a HELLO in
1707        // progress does not change other modules' required-capability
1708        // verdicts. See `Registry::list_registered_modules`.
1709        let registrations = self.registry.list_registered_modules().map_err(|err| {
1710            RouterError::backend(
1711                0,
1712                0,
1713                format!("failed to list capability registrations: {err}"),
1714            )
1715        })?;
1716        let registrations = registrations
1717            .into_iter()
1718            .map(|registration| RegisteredModule {
1719                module_id: registration.manifest.module_id,
1720                module_version: registration.manifest.module_version,
1721                capabilities: registration.manifest.capabilities,
1722            })
1723            .collect();
1724        Ok((runtime, registrations))
1725    }
1726
1727    /// The capability side effects of a module becoming the active registration
1728    /// for its id: cache its manifest (logging how it differs from the cached
1729    /// one), run the deny census when its declarations call for one, and recompute the
1730    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1731    /// candidate's does not, and the supervisor does it at promotion instead,
1732    /// through [`crate::supervise::SwapPromotionObserver`].
1733    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1734        let cached_registration = RegisteredModule {
1735            module_id: registration.manifest.module_id.clone(),
1736            module_version: registration.manifest.module_version.clone(),
1737            capabilities: registration.manifest.capabilities.clone(),
1738        };
1739        let change = self.capability_evaluator.record_hello(&cached_registration);
1740        log_manifest_change(&cached_registration.module_id, &change);
1741        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1742            self.enforce_capability_denies();
1743        }
1744        self.refresh_capability_requirements();
1745    }
1746
1747    /// Point the shared supervisor handle at this handler for swap promotions.
1748    /// Called wherever a handler is put behind the `Arc` the router serves, so
1749    /// it can be held weakly.
1750    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1751        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1752            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1753        self.supervisor.set_swap_promotion_observer(observer);
1754    }
1755
1756    pub fn refresh_capability_requirements(&self) {
1757        match self.runtime_capability_snapshot() {
1758            Ok((runtime, registrations)) => {
1759                let events = self
1760                    .capability_evaluator
1761                    .evaluate_now(&runtime, &registrations);
1762                if !events.is_empty() {
1763                    self.catalog_readiness_revision
1764                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1765                }
1766                log_requirement_events(events, &self.daemon_shutdown);
1767            }
1768            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1769        }
1770    }
1771
1772    /// Reconcile only live, attested route bindings after a capability deny edge
1773    /// or target claim was added. This is deliberately a control-plane census:
1774    /// the opaque forwarding hot path must not grow a per-frame capability check.
1775    fn enforce_capability_denies(&self) {
1776        let registrations = match self.registry.list_registered_modules() {
1777            Ok(snapshot) => snapshot,
1778            Err(err) => {
1779                warn!(error = %err, "failed to read registrations for capability deny census");
1780                return;
1781            }
1782        };
1783        let manifests = registrations
1784            .into_iter()
1785            .map(|registration| {
1786                (
1787                    registration.manifest.module_id.clone(),
1788                    registration.manifest,
1789                )
1790            })
1791            .collect::<BTreeMap<_, _>>();
1792        let census = match self.forwarding.route_census(None) {
1793            Ok(census) => census,
1794            Err(err) => {
1795                warn!(error = %err, "failed to read route census for capability deny enforcement");
1796                return;
1797            }
1798        };
1799
1800        for (target_module_id, routes) in census {
1801            let Some(target_manifest) = manifests.get(&target_module_id) else {
1802                continue;
1803            };
1804            let mut closed_routes = Vec::new();
1805            let mut goodbyes = Vec::new();
1806            for route in routes {
1807                let Principal::Reserved {
1808                    module_id: opening_module_id,
1809                } = &route.principal
1810                else {
1811                    continue;
1812                };
1813                let Some(opening_manifest) = manifests.get(opening_module_id) else {
1814                    continue;
1815                };
1816                let Some(capability) = denied_capability(
1817                    opening_manifest.capabilities.as_ref(),
1818                    target_manifest.capabilities.as_ref(),
1819                ) else {
1820                    continue;
1821                };
1822
1823                match self.forwarding.release_client_route(
1824                    route.goodbye_target.connection_id,
1825                    route.goodbye_target.channel,
1826                    route.goodbye_target.epoch,
1827                ) {
1828                    Ok(RouteRelease::Removed(module_goodbye)) => {
1829                        warn!(
1830                            opening_module_id,
1831                            target_module_id,
1832                            capability,
1833                            "force-closing route because an attested capability deny edge now matches"
1834                        );
1835                        goodbyes.push(module_goodbye);
1836                        goodbyes.push(route.goodbye_target.clone());
1837                        closed_routes.push(route);
1838                    }
1839                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
1840                    Err(err) => warn!(
1841                        opening_module_id,
1842                        target_module_id,
1843                        capability,
1844                        error = %err,
1845                        "failed to force-close capability-denied route"
1846                    ),
1847                }
1848            }
1849
1850            if closed_routes.is_empty() {
1851                continue;
1852            }
1853            send_route_control_pushes(
1854                &self.forwarding,
1855                closed_routes,
1856                ClientControlPush::RouteClosed {
1857                    module_id: target_module_id,
1858                    channels: Vec::new(),
1859                    reason: RouteCloseReason::CapabilityDenied,
1860                    drained: false,
1861                    abandoned: 0,
1862                    excluded_subscriptions: 0,
1863                    terminal: Some(false),
1864                },
1865            );
1866            // route.closed records the reason; the route GOODBYE ends the
1867            // client's handle and settles any calls still pending on it.
1868            self.emit_route_goodbyes(goodbyes);
1869        }
1870    }
1871
1872    /// Why a registered module is not accepting new route binds, or `None` when
1873    /// it is. This is the module's effective readiness: its declared readiness
1874    /// first, then every `need: required` capability it declares evaluating to
1875    /// `provided`. `route.open` and `catalog.list` both read it here so the
1876    /// catalog never reports a module routable that `route.open` would refuse.
1877    fn not_ready_reason(
1878        &self,
1879        registration: &crate::registry::ModuleRegistration,
1880    ) -> Option<NotReadyReason> {
1881        if !registration.ready {
1882            return Some(NotReadyReason {
1883                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1884                capability: None,
1885            });
1886        }
1887        self.first_unprovided_required_capability(registration)
1888            .map(|capability| NotReadyReason {
1889                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1890                capability: Some(capability),
1891            })
1892    }
1893
1894    /// The lexicographically first capability this registration declares
1895    /// `need: required` whose evaluator verdict is not `provided`.
1896    ///
1897    /// The verdicts are the capability evaluator's own; nothing here decides
1898    /// what "provided" means. The evaluator counts a capability provided as
1899    /// soon as a module claiming it has REGISTERED, not once that module is
1900    /// ready. That distinction is what keeps two modules that require each
1901    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1902    /// is ready", each would wait for the other to become ready first and
1903    /// neither ever would. Do not tighten it to readiness.
1904    ///
1905    /// A required capability with no verdict at all means this registration's
1906    /// HELLO or catalog.update landed after the last recompute; recompute once
1907    /// rather than let a missing verdict read as either answer. If it is still
1908    /// missing (the recompute itself failed) the capability counts as
1909    /// unprovided: the refusal is retryable, and routing a module whose
1910    /// required provider is unknown is the outcome this check exists to stop.
1911    fn first_unprovided_required_capability(
1912        &self,
1913        registration: &crate::registry::ModuleRegistration,
1914    ) -> Option<String> {
1915        self.first_unprovided_required_capability_for(
1916            &registration.manifest.module_id,
1917            registration.manifest.capabilities.as_ref(),
1918        )
1919    }
1920
1921    fn first_unprovided_required_capability_for(
1922        &self,
1923        module_id: &str,
1924        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1925    ) -> Option<String> {
1926        let required = capabilities
1927            .into_iter()
1928            .flat_map(|declarations| declarations.requires.iter())
1929            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1930            .map(|requirement| requirement.capability.as_str())
1931            .collect::<BTreeSet<_>>();
1932        if required.is_empty() {
1933            return None;
1934        }
1935        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1936        if required
1937            .iter()
1938            .any(|capability| verdict(capability).is_none())
1939        {
1940            self.refresh_capability_requirements();
1941        }
1942        required
1943            .into_iter()
1944            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1945            .map(str::to_string)
1946    }
1947
1948    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1949        self.capability_evaluator
1950            .statuses()
1951            .into_iter()
1952            .map(capability_requirement_status)
1953            .collect()
1954    }
1955
1956    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1957    /// registration-release watch. The signal is what the supervisor waits on
1958    /// before spawning a replacement, so it must only fire once forwarding
1959    /// teardown is also done (see [`Self::cleanup_connection`] /
1960    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1961    /// registry-only path below because publication already owns the spawn lock.
1962    fn deregister_connection(
1963        &self,
1964        connection_id: ConnectionId,
1965        reason: RegistrationEndReason,
1966    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1967        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1968            spawn.end_primary_registration();
1969        }
1970        self.registry
1971            .deregister_connection_with_reason(connection_id, reason)
1972    }
1973
1974    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1975    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1976    // or claim-bound consumers to revoke. Remove only its unpublished registry
1977    // entry without re-entering primary-registration teardown.
1978    fn rollback_unpublished_hello(
1979        &self,
1980        connection: ConnectionId,
1981    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1982        self.registry.deregister_connection_with_reason(
1983            connection,
1984            RegistrationEndReason::RegistrationFailed,
1985        )
1986    }
1987
1988    fn request_refusal_close(
1989        &self,
1990        connection: ConnectionId,
1991        sink: Option<&crate::FrameSink>,
1992        reason: CloseReason,
1993    ) {
1994        if let Some(sink) = sink {
1995            sink.terminate_ingress();
1996        }
1997        if self.claims.close_notifications_enabled() {
1998            self.forwarding.request_connection_close(connection, reason);
1999        }
2000    }
2001
2002    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
2003        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
2004            return None;
2005        }
2006        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
2007            parse_client_control_request(&frame.body)
2008        else {
2009            return None;
2010        };
2011        Some(target_module_id(&target).to_string())
2012    }
2013
2014    pub(crate) fn route_open_capacity_refusal(
2015        &self,
2016        ctx: &RouteCtx,
2017        frame: &Frame,
2018        target_module_id: &str,
2019        in_flight: usize,
2020        limit: usize,
2021    ) -> Result<Frame, RouterError> {
2022        // Sent before the request reaches `handle_route_open`, so the caller
2023        // fields come from the raw frame here.
2024        let caller = self.route_open_caller_from_frame(ctx, frame);
2025        self.route_open_admission_refusal_frame(
2026            ctx,
2027            &caller,
2028            frame,
2029            target_module_id,
2030            "open_admission_full",
2031            (in_flight, limit),
2032            format!(
2033                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
2034            ),
2035        )
2036    }
2037
2038    fn route_open_target_capacity_refusal(
2039        &self,
2040        ctx: &RouteCtx,
2041        caller: &RouteOpenCaller,
2042        frame: &Frame,
2043        target_module_id: &str,
2044        in_flight: usize,
2045    ) -> Result<Frame, RouterError> {
2046        self.route_open_admission_refusal_frame(
2047            ctx,
2048            caller,
2049            frame,
2050            target_module_id,
2051            "target_binds_full",
2052            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
2053            format!(
2054                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
2055            ),
2056        )
2057    }
2058
2059    /// Admission pressure clears as existing binds settle, so its refusal must
2060    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
2061    /// `module_reloading`, `module_warming`, `target_unavailable`, or
2062    /// `module_timeout`. `target_unavailable` is honest for an attempt that
2063    /// cannot currently reach its target; `module_timeout` would falsely claim
2064    /// that a wait expired. A new, cleaner code would be terminal to deployed
2065    /// clients, so it requires a client-tolerance rollout before daemon emission.
2066    #[allow(clippy::too_many_arguments)]
2067    fn route_open_admission_refusal_frame(
2068        &self,
2069        ctx: &RouteCtx,
2070        caller: &RouteOpenCaller,
2071        frame: &Frame,
2072        target_module_id: &str,
2073        reason: &'static str,
2074        (in_flight, limit): (usize, usize),
2075        message: impl Into<String>,
2076    ) -> Result<Frame, RouterError> {
2077        let code = error_codes::TARGET_UNAVAILABLE;
2078        self.counters.increment_route_open_refused(code);
2079        info!(
2080            target: "control",
2081            code,
2082            reason,
2083            module_id = ?target_module_id,
2084            connection_id = ctx.connection_id.get(),
2085            principal = %caller.principal,
2086            scope = %caller.scope,
2087            harness = %caller.harness,
2088            in_flight,
2089            limit,
2090            "route.open refused"
2091        );
2092        control_error_frame(frame, code, message.into())
2093    }
2094
2095    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
2096    ///
2097    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
2098    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
2099    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
2100    #[cfg(test)]
2101    pub fn handle_control(
2102        &self,
2103        connection_id: ConnectionId,
2104        frame: Frame,
2105    ) -> Result<Vec<Frame>, RouterError> {
2106        match frame.header.ty {
2107            FrameType::Ping => Ok(vec![pong(&frame)?]),
2108            FrameType::Hello => self.handle_hello(connection_id, None, frame),
2109            FrameType::Goodbye => self.handle_goodbye(connection_id),
2110            ty => Ok(vec![control_error_frame(
2111                &frame,
2112                "unsupported_control_frame",
2113                format!("unsupported channel-0 frame {ty:?}"),
2114            )?]),
2115        }
2116    }
2117
2118    pub async fn handle_control_frame(
2119        &self,
2120        ctx: &RouteCtx,
2121        frame: Frame,
2122    ) -> Result<Vec<Frame>, RouterError> {
2123        self.handle_control_frame_timed(ctx, frame, None).await
2124    }
2125
2126    #[cfg(any(test, feature = "test-support"))]
2127    pub fn with_test_operator_app_policy(
2128        mut self,
2129        policy: crate::operator_apps::TestOperatorAppPolicy,
2130    ) -> Self {
2131        self.operator_app_policy = policy.into();
2132        self
2133    }
2134
2135    /// Inject the Windows signature check for tests. The injected check
2136    /// answers the verified version string or the rejection reason; the
2137    /// daemon enforces the floor itself on the returned version.
2138    #[cfg(all(windows, any(test, feature = "test-support")))]
2139    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
2140        self.windows_verify = Some(verify);
2141        self
2142    }
2143
2144    /// Record which pids the daemon would flash for `already_running`.
2145    #[cfg(all(windows, any(test, feature = "test-support")))]
2146    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
2147        self.windows_flash = Some(flash);
2148        self
2149    }
2150
2151    /// Inject a tracking failure for tests: makes `track_launched_process`
2152    /// fail so a test can prove a launch that cannot be tracked is stopped,
2153    /// never left running.
2154    #[cfg(all(windows, any(test, feature = "test-support")))]
2155    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2156        self.windows_track = Some(track);
2157        self
2158    }
2159
2160    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2161        self.local_connections
2162            .lock()
2163            .unwrap_or_else(|p| p.into_inner())
2164            .insert(connection);
2165    }
2166
2167    // Keep the connection-level delivery decision shared with route.bind. The
2168    // target's capability opt-in is separate from recognition of the caller.
2169    fn connection_operator_app(
2170        &self,
2171        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2172    ) -> Option<subc_protocol::peer::OperatorApp> {
2173        stamp
2174            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2175            .map(|stamp| stamp.app.clone())
2176    }
2177
2178    pub(crate) fn record_observed_peer(
2179        &self,
2180        connection: ConnectionId,
2181        peer: subc_os::local_peer::ObservedPeer,
2182    ) {
2183        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2184        let peer = match peer {
2185            OsPeer::Unobserved => ObservedPeer::unobserved(),
2186            OsPeer::Observed(peer) => {
2187                let observed = match peer.user {
2188                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2189                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2190                };
2191                observed
2192                    .with_exe(
2193                        peer.exe
2194                            .and_then(|path| path.into_os_string().into_string().ok()),
2195                    )
2196                    .with_signing_id(peer.signing_id)
2197            }
2198        };
2199        self.observed_peers
2200            .lock()
2201            .unwrap_or_else(|p| p.into_inner())
2202            .insert(connection, peer);
2203    }
2204
2205    pub(crate) fn record_caller_endpoints(
2206        &self,
2207        connection: ConnectionId,
2208        endpoints: Option<(SocketAddr, SocketAddr)>,
2209    ) {
2210        let mut callers = self
2211            .caller_endpoints
2212            .lock()
2213            .unwrap_or_else(|p| p.into_inner());
2214        callers.remove(&connection);
2215        if let Some(endpoints) = endpoints {
2216            callers.insert(connection, endpoints);
2217        }
2218    }
2219
2220    #[cfg(test)]
2221    pub(crate) fn with_caller_lookup_for_test(
2222        mut self,
2223        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2224    ) -> Self {
2225        self.caller_lookup = Some(Arc::new(lookup));
2226        self
2227    }
2228
2229    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2230        let endpoints = self
2231            .caller_endpoints
2232            .lock()
2233            .unwrap_or_else(|p| p.into_inner())
2234            .get(&connection)
2235            .copied();
2236        #[cfg(test)]
2237        let lookup = self.caller_lookup.clone();
2238        tokio::task::spawn_blocking(move || {
2239            #[cfg(test)]
2240            if let Some(lookup) = lookup {
2241                return lookup(endpoints);
2242            }
2243            endpoints
2244                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2245                .unwrap_or_default()
2246        })
2247        .await
2248        .unwrap_or_default()
2249    }
2250
2251    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2252        frame.header.channel == 0
2253            && frame.header.ty == FrameType::Request
2254            && self
2255                .forwarding
2256                .module_endpoint_for_connection(ctx.connection_id)
2257                .is_ok_and(|endpoint| endpoint.is_none())
2258            && parse_client_control_request(&frame.body)
2259                .ok()
2260                .is_some_and(|request| privileged_operation(&request).is_some())
2261    }
2262
2263    pub(crate) async fn handle_control_frame_timed(
2264        &self,
2265        ctx: &RouteCtx,
2266        frame: Frame,
2267        dispatch_started_at: Option<StdInstant>,
2268    ) -> Result<Vec<Frame>, RouterError> {
2269        let first = ctx.egress.first_ingress_frame();
2270        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2271            .await
2272    }
2273
2274    pub(crate) async fn handle_control_frame_ingress(
2275        &self,
2276        ctx: &RouteCtx,
2277        frame: Frame,
2278        dispatch_started_at: Option<StdInstant>,
2279        first: bool,
2280    ) -> Result<Vec<Frame>, RouterError> {
2281        if ctx.egress.ingress_terminal() {
2282            return Ok(Vec::new());
2283        }
2284        #[cfg(test)]
2285        self.claims.record_dispatch(frame.header.corr);
2286        let claim_binding = self.claims.binding(ctx.connection_id);
2287        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2288            && claim_binding
2289                .as_ref()
2290                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2291        .then(|| self.prefix_hello_attempt(ctx));
2292        if claim_binding
2293            .as_ref()
2294            .is_some_and(|binding| binding.prefix_module_id().is_some())
2295        {
2296            let registered = self
2297                .forwarding
2298                .module_endpoint_for_connection(ctx.connection_id)
2299                .map_err(RouterError::Forwarding)?
2300                .is_some();
2301            if !registered && frame.header.ty != FrameType::Hello {
2302                return self
2303                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2304                    .await;
2305            }
2306            if registered && frame.header.ty == FrameType::Goodbye {
2307                ctx.egress.terminate_ingress();
2308                let result = self.handle_goodbye(ctx.connection_id);
2309                self.claims.connection_closed(ctx.connection_id);
2310                self.request_refusal_close(
2311                    ctx.connection_id,
2312                    Some(&ctx.egress),
2313                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2314                );
2315                return result;
2316            }
2317            if registered && frame.header.ty == FrameType::Request {
2318                let allowed =
2319                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2320                        matches!(
2321                            probe.op.as_str(),
2322                            "catalog.update"
2323                                | "catalog.update_role_declarations"
2324                                | "scope.describe"
2325                                | "scope.watch"
2326                                | "supervisor.live_roots"
2327                                | "activity.record"
2328                        )
2329                    });
2330                if !allowed {
2331                    return Ok(vec![control_error_frame(
2332                        &frame,
2333                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2334                        "prefix registrations have only brokered module operations",
2335                    )?]);
2336                }
2337            }
2338            if registered
2339                && frame.header.ty == FrameType::Push
2340                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2341                    .is_ok_and(|probe| probe.op == "route.status")
2342            {
2343                return Ok(vec![control_error_frame(
2344                    &frame,
2345                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2346                    "prefix registrations may push only route.status for routes they serve",
2347                )?]);
2348            }
2349        }
2350        match frame.header.ty {
2351            FrameType::Ping => Ok(vec![pong(&frame)?]),
2352            FrameType::Hello => {
2353                if claim_binding
2354                    .as_ref()
2355                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2356                {
2357                    return self
2358                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2359                        .await;
2360                }
2361                // Resolved once, here: the blocking HELLO below may outlive this
2362                // reader and run after cleanup has forgotten the channel, and it
2363                // must still be judged as this channel's HELLO.
2364                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2365                if let Some(spawn) = &channel_spawn {
2366                    spawn.wait_launch().await;
2367                    // Refused launches close the channel. Leave their pending
2368                    // HELLO unanswered instead of racing a reply against shutdown.
2369                    if !spawn.launch_ready() {
2370                        ctx.egress.terminate_ingress();
2371                        return Ok(Vec::new());
2372                    }
2373                    #[cfg(test)]
2374                    self.pause_hello_ingress_for_test().await;
2375                } else if claim_binding.is_none() {
2376                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2377                        if let (Some(module), Some(nonce)) = (
2378                            hello
2379                                .get("manifest")
2380                                .and_then(|value| value.get("module_id"))
2381                                .and_then(|value| value.as_str()),
2382                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2383                        ) {
2384                            if !self
2385                                .config_runtime
2386                                .as_ref()
2387                                .is_some_and(|owner| owner.module_is_gated(module))
2388                                && !self.supervisor.wait_program_binding(module, nonce).await
2389                            {
2390                                self.request_refusal_close(
2391                                    ctx.connection_id,
2392                                    Some(&ctx.egress),
2393                                    CloseReason::new(
2394                                        "program_refused",
2395                                        "the spawned program binding failed",
2396                                    ),
2397                                );
2398                                return Ok(vec![control_error_frame(
2399                                    &frame,
2400                                    if self
2401                                        .config_runtime
2402                                        .as_ref()
2403                                        .is_some_and(|owner| owner.is_recovering())
2404                                    {
2405                                        "config_gated"
2406                                    } else {
2407                                        "program_refused"
2408                                    },
2409                                    "the spawned program binding failed",
2410                                )?]);
2411                            }
2412                        }
2413                    }
2414                }
2415                let handler = self.clone();
2416                let connection = ctx.connection_id;
2417                let egress = ctx.egress.clone();
2418                let correlation = frame.header.corr;
2419                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2420                let span = tracing::Span::current();
2421                let hello_binding = claim_binding.clone();
2422                let replies = tokio::task::spawn_blocking(move || {
2423                    tracing::dispatcher::with_default(&dispatcher, || {
2424                        span.in_scope(|| {
2425                            handler.handle_hello_checked(
2426                                connection,
2427                                Some(egress),
2428                                frame,
2429                                true,
2430                                hello_binding,
2431                                channel_spawn,
2432                            )
2433                        })
2434                    })
2435                })
2436                .await
2437                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2438                #[cfg(test)]
2439                if prefix_attempt.is_some() {
2440                    self.claims.pause_prefix_commit_for_test(false).await;
2441                }
2442                if let Some(attempt) = &mut prefix_attempt {
2443                    let accepted = !replies
2444                        .iter()
2445                        .any(|reply| reply.header.ty == FrameType::Error)
2446                        && self
2447                            .registry
2448                            .get_module_by_connection(ctx.connection_id)
2449                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2450                            .is_some();
2451                    if accepted {
2452                        attempt.accepted = true;
2453                    } else {
2454                        ctx.egress.terminate_ingress();
2455                        for reply in replies {
2456                            ctx.egress.send_flushed(reply).await?;
2457                        }
2458                        return Ok(Vec::new());
2459                    }
2460                }
2461                Ok(replies)
2462            }
2463            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2464            FrameType::Cancel => {
2465                // Channel-0 cancellation withdraws approvals and subscriptions
2466                // and fences pending agent declarations;
2467                // successful cancellation has no ordinary reply.
2468                // A config Apply may also own an OS prompt. Cancel that prompt
2469                // before config cancellation can report the request handled.
2470                if self
2471                    .agent_declarations
2472                    .cancel(ctx.connection_id, frame.header.corr)
2473                    || self
2474                        .forwarding
2475                        .operator_confirms()
2476                        .cancel(ctx.connection_id, frame.header.corr)
2477                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2478                    || self
2479                        .supervisor
2480                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2481                    || self.cancel_activity_subscription(ctx, &frame)?
2482                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2483                    || self
2484                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2485                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2486                {
2487                    Ok(Vec::new())
2488                } else {
2489                    Ok(vec![control_error_frame(
2490                        &frame,
2491                        "unknown_subscription",
2492                        "no subscription has this correlation id",
2493                    )?])
2494                }
2495            }
2496            FrameType::Request => {
2497                // This additive operation is not part of the existing exhaustive
2498                // module-control enum. Probe the op before decoding that enum.
2499                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2500                if let Some(probe) = &op {
2501                    self.record_control_usage(ctx.connection_id, &probe.op);
2502                }
2503                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2504                if let Some(refusal) = self
2505                    .recovery_request_refusal(
2506                        ctx,
2507                        &frame,
2508                        op.as_ref().map(|probe| probe.op.as_str()),
2509                    )
2510                    .await?
2511                {
2512                    if claim_present {
2513                        self.reclaim_presented_expiry(&frame);
2514                        return self
2515                            .refuse_claim_connection(ctx, &frame, "config_gated")
2516                            .await;
2517                    }
2518                    return Ok(vec![refusal]);
2519                }
2520                if claim_present {
2521                    return self.handle_claim_present(ctx, &frame, first).await;
2522                }
2523                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2524                    return self.handle_claim_mint(ctx, &frame).await;
2525                }
2526                if let Some(refusal) = self.registration_operation_refusal(
2527                    ctx,
2528                    &frame,
2529                    op.as_ref().map(|probe| probe.op.as_str()),
2530                )? {
2531                    return Ok(vec![refusal]);
2532                }
2533                if op
2534                    .as_ref()
2535                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2536                {
2537                    return self.handle_catalog_watch(ctx, frame);
2538                }
2539                if op
2540                    .as_ref()
2541                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2542                {
2543                    return self.handle_scope_watch(ctx, frame);
2544                }
2545                if op
2546                    .as_ref()
2547                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2548                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2549                        .unwrap_or(false)
2550                {
2551                    return Ok(vec![control_error_frame(
2552                        &frame,
2553                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2554                        "provider_declarations are fixed at HELLO; restart the module to change them",
2555                    )?]);
2556                }
2557                if let Some(probe) = op
2558                    .as_ref()
2559                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2560                {
2561                    return self
2562                        .handle_module_config_request(ctx, frame, &probe.op)
2563                        .await;
2564                }
2565                if op
2566                    .as_ref()
2567                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2568                {
2569                    return self.handle_config_gate_request(ctx, frame).await;
2570                }
2571                if op
2572                    .as_ref()
2573                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2574                {
2575                    return self.handle_activity_record(ctx, frame).await;
2576                }
2577                if op.as_ref().is_some_and(|probe| {
2578                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2579                }) {
2580                    return self.handle_activity_read(ctx, frame).await;
2581                }
2582                if op
2583                    .as_ref()
2584                    .is_some_and(|probe| probe.op == "operator.confirm")
2585                {
2586                    return self.handle_operator_confirm(ctx, frame).await;
2587                }
2588                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2589                    return self
2590                        .observe_control_wait(
2591                            ctx,
2592                            None,
2593                            ops::APP_OPEN,
2594                            self.handle_app_open(ctx, frame),
2595                        )
2596                        .await;
2597                }
2598                if op
2599                    .as_ref()
2600                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2601                {
2602                    return self.handle_connection_describe(ctx, frame).await;
2603                }
2604                if op
2605                    .as_ref()
2606                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2607                {
2608                    return self.handle_scope_served_by(ctx.connection_id, frame);
2609                }
2610                if self
2611                    .forwarding
2612                    .module_endpoint_for_connection(ctx.connection_id)
2613                    .map_err(RouterError::Forwarding)?
2614                    .is_some()
2615                {
2616                    if !is_known_module_request_op(&frame.body) {
2617                        return Ok(vec![control_error_frame(
2618                            &frame,
2619                            "unsupported_control_frame",
2620                            "module-originated channel-0 REQUEST is not supported",
2621                        )?]);
2622                    }
2623                    let request = match parse_module_control_request_from_module(&frame.body) {
2624                        Ok(request) => request,
2625                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2626                            return Ok(vec![control_error_frame(
2627                                &frame,
2628                                "unsupported_control_frame",
2629                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2630                            )?])
2631                        }
2632                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2633                            return Ok(vec![control_error_frame(
2634                                &frame,
2635                                "invalid_control_body",
2636                                format!("malformed module control body: {err}"),
2637                            )?])
2638                        }
2639                    };
2640                    let op = module_control_request_op(&request);
2641                    let corr = frame.header.corr;
2642                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2643                    if let ModuleControlRequestFromModule::AgentCommands {
2644                        started,
2645                        finished,
2646                        known,
2647                    } = request
2648                    {
2649                        return self
2650                            .agent_declarations
2651                            .enqueue(
2652                                self,
2653                                ctx,
2654                                frame,
2655                                crate::resource_totals::Declaration {
2656                                    started,
2657                                    finished,
2658                                    known,
2659                                },
2660                            )
2661                            .await;
2662                    }
2663                    let result =
2664                        self.handle_module_control_request(ctx.connection_id, frame, request);
2665                    log_slow_control_dispatch(
2666                        dispatch_started_at,
2667                        op,
2668                        ctx.connection_id,
2669                        corr,
2670                        None,
2671                    );
2672                    return result;
2673                }
2674
2675                if is_known_module_request_op(&frame.body) {
2676                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2677                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2678                    let code = if is_agents {
2679                        "not_supervised"
2680                    } else if op
2681                        .as_ref()
2682                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2683                    {
2684                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2685                    } else {
2686                        "not_registered"
2687                    };
2688                    return Ok(vec![control_error_frame(
2689                        &frame,
2690                        code,
2691                        "module-originated control requests require the module's own registered connection",
2692                    )?]);
2693                }
2694
2695                let request = match parse_client_control_request(&frame.body) {
2696                    Ok(request) => request,
2697                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2698                        return Ok(vec![control_error_frame(
2699                            &frame,
2700                            "unknown_control_op",
2701                            format!("unknown client control op: {err}"),
2702                        )?])
2703                    }
2704                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2705                        return Ok(vec![control_error_frame(
2706                            &frame,
2707                            "invalid_control_body",
2708                            format!("malformed client control body: {err}"),
2709                        )?])
2710                    }
2711                };
2712                let op = client_control_request_op(&request);
2713                let corr = frame.header.corr;
2714                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2715                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2716                #[cfg(test)]
2717                if let Some(delay) = self.control_dispatch_delay {
2718                    tokio::time::sleep(delay).await;
2719                }
2720                let result = self
2721                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2722                    .await;
2723                if let Some(timings) = route_open_timings.as_mut() {
2724                    timings.finish();
2725                }
2726                log_slow_control_dispatch(
2727                    dispatch_started_at,
2728                    op,
2729                    ctx.connection_id,
2730                    corr,
2731                    route_open_timings.as_ref(),
2732                );
2733                result
2734            }
2735            FrameType::Push => {
2736                let Some(endpoint) = self
2737                    .forwarding
2738                    .module_endpoint_for_connection(ctx.connection_id)
2739                    .map_err(RouterError::Forwarding)?
2740                else {
2741                    return Ok(vec![control_error_frame(
2742                        &frame,
2743                        "unsupported_control_frame",
2744                        "client-originated channel-0 PUSH is not supported",
2745                    )?]);
2746                };
2747                self.handle_status_update(endpoint, frame)
2748            }
2749            FrameType::Response | FrameType::Error
2750                if self
2751                    .forwarding
2752                    .module_endpoint_for_connection(ctx.connection_id)
2753                    .map_err(RouterError::Forwarding)?
2754                    .is_some() =>
2755            {
2756                self.handle_module_relay_response(ctx.connection_id, frame)
2757            }
2758            ty => Ok(vec![control_error_frame(
2759                &frame,
2760                "unsupported_control_frame",
2761                format!("unsupported channel-0 frame {ty:?}"),
2762            )?]),
2763        }
2764    }
2765
2766    #[cfg(test)]
2767    fn pause_cleanup_for_test(&self, stage: u8) {
2768        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2769        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2770            let (_, (reached, release)) = slot.take().unwrap();
2771            drop(slot);
2772            let _ = reached.send(());
2773            let _ = release.recv_timeout(Duration::from_secs(5));
2774        }
2775    }
2776
2777    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2778    /// right after the nonce is resolved.
2779    #[cfg(all(test, unix, feature = "test-support"))]
2780    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2781        *self
2782            .after_nonce_attestation
2783            .lock()
2784            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2785    }
2786
2787    #[cfg(test)]
2788    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2789        let hook = self
2790            .after_nonce_attestation
2791            .lock()
2792            .unwrap_or_else(|p| p.into_inner())
2793            .take();
2794        if let Some(hook) = hook {
2795            hook();
2796        }
2797    }
2798
2799    #[cfg(test)]
2800    async fn pause_hello_ingress_for_test(&self) {
2801        let pause = self
2802            .hello_ingress_pause
2803            .lock()
2804            .unwrap_or_else(|p| p.into_inner())
2805            .take();
2806        if let Some((reached, release)) = pause {
2807            let _ = reached.send(());
2808            let _ = release.await;
2809        }
2810    }
2811
2812    pub fn cleanup_connection(
2813        &self,
2814        connection_id: ConnectionId,
2815    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2816        // The server loop joins its offloaded request tasks (route opens,
2817        // privileged requests and activity reads) before this cleanup runs, and
2818        // inline dispatch has ended. Two kinds of work are not joined. Agent
2819        // command declarations run on their queue's detached worker, so the
2820        // queue is closed first: every declaration still queued or validating
2821        // has its commit fence cancelled before anything below can change how
2822        // the connection resolves. A HELLO whose reader was dropped keeps
2823        // running on its blocking thread. It carries the channel spawn its
2824        // reader resolved at ingress instead of re-reading the index forgotten
2825        // below, so it is still judged as that channel's HELLO: the retired
2826        // spawn refuses it before it records anything, and a channel HELLO
2827        // never records a launch nonce, so it cannot leave this connection any
2828        // nonce authority.
2829        self.agent_declarations.close(connection_id);
2830        self.close_catalog_subscriptions(connection_id);
2831        self.close_config_settings_subscriptions(connection_id);
2832        self.close_scope_subscriptions(connection_id);
2833        #[cfg(test)]
2834        self.pause_cleanup_for_test(0);
2835        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2836            spawn.retire_registration_channel();
2837        }
2838        self.supervisor
2839            .forget_registration_connection(connection_id);
2840        #[cfg(test)]
2841        self.pause_cleanup_for_test(1);
2842        self.local_connections
2843            .lock()
2844            .unwrap_or_else(|p| p.into_inner())
2845            .remove(&connection_id);
2846        self.caller_endpoints
2847            .lock()
2848            .unwrap_or_else(|p| p.into_inner())
2849            .remove(&connection_id);
2850        self.build_class_warned
2851            .lock()
2852            .unwrap_or_else(|p| p.into_inner())
2853            .remove(&connection_id);
2854        // Retire the capture before its published facts so an in-flight
2855        // verification cannot recreate them after cleanup.
2856        self.captured_peers
2857            .lock()
2858            .unwrap_or_else(|p| p.into_inner())
2859            .remove(&connection_id);
2860        self.observed_peers
2861            .lock()
2862            .unwrap_or_else(|p| p.into_inner())
2863            .remove(&connection_id);
2864        self.config_desktop_stamps
2865            .lock()
2866            .unwrap_or_else(|p| p.into_inner())
2867            .remove(&connection_id);
2868        self.operator_apps
2869            .lock()
2870            .unwrap_or_else(|p| p.into_inner())
2871            .remove(&connection_id);
2872        self.forwarding
2873            .operator_confirms()
2874            .connection_closed(connection_id);
2875        let cleanup = self.cleanup_connection_with_end_reason(
2876            connection_id,
2877            RegistrationEndReason::ConnectionClosed,
2878        );
2879        // A draining writer can still be reached by a route until forwarding
2880        // cleanup finishes. Keep its claim sink visible to launch retirement.
2881        self.claims.connection_closed(connection_id);
2882        cleanup
2883    }
2884
2885    fn cleanup_connection_with_end_reason(
2886        &self,
2887        connection_id: ConnectionId,
2888        requested_reason: RegistrationEndReason,
2889    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2890        #[cfg(test)]
2891        if let Some(pause) = self
2892            .activity_request_pause
2893            .lock()
2894            .unwrap()
2895            .as_ref()
2896            .filter(|pause| pause.connection == connection_id)
2897        {
2898            pause
2899                .cleanup_started
2900                .store(true, std::sync::atomic::Ordering::Release);
2901        }
2902        if let Some(runtime) = &self.config_runtime {
2903            runtime.disconnected(connection_id);
2904        }
2905        self.agent_declarations.close(connection_id);
2906        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2907            self.registry
2908                .get_module_by_connection(connection_id)?
2909                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2910                .and_then(|module| module.registration_end_reason().ok().flatten())
2911                .unwrap_or(requested_reason)
2912        } else {
2913            requested_reason
2914        };
2915        let crash_closed = self
2916            .registry
2917            .get_module_by_connection(connection_id)?
2918            .and_then(|registration| {
2919                self.forwarding
2920                    .module_endpoint_for_connection(connection_id)
2921                    .ok()
2922                    .flatten()
2923                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2924                    .map(|routes| (registration.manifest.module_id, routes))
2925            });
2926        let crash_closed = crash_closed.map(|(module_id, routes)| {
2927            let terminal = match self.supervisor.get(&module_id) {
2928                None => false,
2929                Some(module) => match module.will_recover_after_connection_loss() {
2930                    Ok(will_recover) => !will_recover,
2931                    Err(err) => {
2932                        warn!(
2933                            %module_id,
2934                            error = %err,
2935                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2936                        );
2937                        false
2938                    }
2939                },
2940            };
2941            // The forwarding table gates all providers at the start of daemon
2942            // shutdown, before their connections are closed. An ordinary
2943            // module disconnect still reports crash if that gate is not set.
2944            let (reason, drained) = match self
2945                .forwarding
2946                .daemon_drain_result_for_connection(connection_id)
2947            {
2948                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
2949                Ok(None) => (RouteCloseReason::Crash, false),
2950                Err(err) => {
2951                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
2952                    (RouteCloseReason::Crash, false)
2953                }
2954            };
2955            (module_id, routes, reason, drained, terminal)
2956        });
2957        let registrations = self.deregister_connection(connection_id, end_reason);
2958        // Read before teardown: the spawn whose registration this connection
2959        // was. Its registration ending is an authority change for it.
2960        let ended_authority = self
2961            .forwarding
2962            .target_authority_for_connection(connection_id)
2963            .ok()
2964            .flatten();
2965        let cleanup = if crash_closed.is_some() {
2966            self.forwarding.cleanup_connection_counted(connection_id)
2967        } else {
2968            // A module connection's teardown needs the count of abandoned
2969            // route.bind relays for its route.closed notice below. Any other
2970            // connection, such as a client's, sends no such notice and needs
2971            // only its routes released, so it uses the route-only wrapper and
2972            // reports zero.
2973            self.forwarding
2974                .cleanup_connection(connection_id)
2975                .map(|released| crate::forwarding::ConnectionCleanup {
2976                    released,
2977                    abandoned_relays: 0,
2978                })
2979        };
2980        // The route.closed push waits for forwarding teardown because only
2981        // teardown knows how many pending route.bind relays it aborted. It still
2982        // goes out before the GOODBYEs for the released routes, and its targets
2983        // were captured above, before teardown removed those routes.
2984        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
2985            let abandoned = cleanup
2986                .as_ref()
2987                .map_or(0, |cleanup| cleanup.abandoned_relays);
2988            send_route_control_pushes(
2989                &self.forwarding,
2990                routes,
2991                ClientControlPush::RouteClosed {
2992                    module_id,
2993                    channels: Vec::new(),
2994                    reason,
2995                    drained,
2996                    abandoned,
2997                    excluded_subscriptions: 0,
2998                    terminal: Some(terminal),
2999                },
3000            );
3001        }
3002        if let Ok(cleanup) = cleanup {
3003            self.emit_route_goodbyes(cleanup.released);
3004        }
3005        if let Some(record) = ended_authority {
3006            self.change_spawn_authority(&record);
3007        }
3008        // Signal the registration-release watch only now that BOTH registry and
3009        // forwarding teardown are done, so a supervisor waiting to spawn a
3010        // replacement never observes release while old routes still exist.
3011        if matches!(&registrations, Ok(r) if !r.is_empty()) {
3012            crate::supervise::notify_registration_release();
3013            self.capability_evaluator.wake_deadline_loop();
3014            self.refresh_capability_requirements();
3015        }
3016        self.supervisor.remove_spawn_subscribers(connection_id);
3017        self.activity_streams
3018            .lock()
3019            .unwrap_or_else(|p| p.into_inner())
3020            .retain(|(id, _), task| {
3021                if *id == connection_id {
3022                    task.abort();
3023                    false
3024                } else {
3025                    true
3026                }
3027            });
3028        // Sync authority dies with its connection, so the owner's next
3029        // connection can take it; the owner's scopes stay as they are.
3030        self.hello_launch_nonces
3031            .lock()
3032            .unwrap_or_else(|poisoned| poisoned.into_inner())
3033            .forget(connection_id);
3034        self.scopes
3035            .write()
3036            .unwrap_or_else(|poisoned| poisoned.into_inner())
3037            .release_connection(connection_id);
3038        registrations
3039    }
3040
3041    pub(crate) fn handle_route_goodbye(
3042        &self,
3043        connection_id: ConnectionId,
3044        route_channel: u16,
3045        route_epoch: u32,
3046    ) -> Result<bool, RouterError> {
3047        debug!(
3048            connection_id = connection_id.get(),
3049            route_channel, route_epoch, "handling route GOODBYE"
3050        );
3051        let RouteRelease::Removed(released_route) = self
3052            .forwarding
3053            .release_client_route(connection_id, route_channel, route_epoch)
3054            .map_err(RouterError::Forwarding)?
3055        else {
3056            return Ok(false);
3057        };
3058        self.emit_route_goodbyes(vec![released_route]);
3059        Ok(true)
3060    }
3061
3062    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
3063        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
3064    }
3065
3066    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
3067    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
3068    /// own commit failed after the module had already accepted). Without this, a
3069    /// module that accepts late keeps a binding subc has torn down, so a later
3070    /// frame on that module channel could misdeliver if the channel is reused.
3071    ///
3072    /// Never closes the shared module connection on failure: a dropped notification
3073    /// only wastes a bounded amount of warm module-side state, which the module's
3074    /// own idle reaper reclaims. Only call this once the route.bind relay was
3075    /// actually enqueued to the module — if the relay send itself failed, the
3076    /// module never created a binding and there is nothing to tear down.
3077    fn send_abandoned_route_bind_goodbye(
3078        &self,
3079        module_sink: &crate::FrameSink,
3080        negotiated_ver: u8,
3081        module_channel: u16,
3082        module_epoch: u32,
3083    ) {
3084        let frame = match Frame::build_with_version(
3085            negotiated_ver,
3086            FrameType::Goodbye,
3087            control_flags(),
3088            module_channel,
3089            module_epoch,
3090            0,
3091            Vec::new(),
3092        ) {
3093            Ok(frame) => frame,
3094            Err(err) => {
3095                warn!(
3096                    route_channel = module_channel,
3097                    error = %err,
3098                    "failed to build GOODBYE for abandoned route.bind"
3099                );
3100                return;
3101            }
3102        };
3103        crate::forwarding::send_module_route_goodbye(
3104            &self.counters,
3105            module_sink,
3106            frame,
3107            None,
3108            "abandoned route.bind",
3109        );
3110    }
3111
3112    #[cfg(test)]
3113    fn handle_hello(
3114        &self,
3115        connection_id: ConnectionId,
3116        egress: Option<crate::router::FrameSink>,
3117        frame: Frame,
3118    ) -> Result<Vec<Frame>, RouterError> {
3119        let binding = self.claims.binding(connection_id);
3120        let channel_spawn = self.supervisor.registration_spawn(connection_id);
3121        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
3122    }
3123
3124    fn handle_hello_checked(
3125        &self,
3126        connection_id: ConnectionId,
3127        sink: Option<crate::FrameSink>,
3128        frame: Frame,
3129        wait_for_gate: bool,
3130        prefix_binding: Option<claims::ClaimBinding>,
3131        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3132    ) -> Result<Vec<Frame>, RouterError> {
3133        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
3134        #[cfg(test)]
3135        if prefix_binding.is_some() {
3136            self.claims.pause_prefix_hello_for_test(5);
3137            match self.claims.take_prefix_hello_failure_for_test() {
3138                Some("error") => {
3139                    return Err(RouterError::backend(
3140                        0,
3141                        frame.header.corr,
3142                        "injected HELLO failure",
3143                    ))
3144                }
3145                Some("panic") => panic!("injected HELLO task panic"),
3146                _ => {}
3147            }
3148        }
3149        if let Some(binding) = &prefix_binding {
3150            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3151            let module = value
3152                .as_ref()
3153                .and_then(|value| value["manifest"]["module_id"].as_str());
3154            if !binding.admit_prefix_hello(module)
3155                || !self.prefix_binding_live(binding, connection_id)
3156                || !module.is_some_and(|module| {
3157                    self.supervisor
3158                        .prefix_claim_authorized(&binding.registration.module_id, module)
3159                })
3160                || binding.registration.check().is_err()
3161            {
3162                return Ok(vec![control_error_frame(
3163                    &frame,
3164                    "claim_prefix_refused",
3165                    "HELLO must name the prefix claim's exact module id once",
3166                )?]);
3167            }
3168        }
3169        struct RefuseUnregisteredChannel {
3170            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3171            sink: Option<crate::FrameSink>,
3172        }
3173        impl Drop for RefuseUnregisteredChannel {
3174            fn drop(&mut self) {
3175                if let Some(spawn) = &self.spawn {
3176                    if !spawn.registered() {
3177                        if let Some(sink) = &self.sink {
3178                            sink.terminate_ingress();
3179                        }
3180                        spawn.retire_registration_channel();
3181                    }
3182                }
3183            }
3184        }
3185        let _channel_attempt = RefuseUnregisteredChannel {
3186            spawn: channel_spawn.clone(),
3187            sink: sink.clone(),
3188        };
3189        if let Some(spawn) = &channel_spawn {
3190            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3191            if let Err(code) = spawn.admit_hello(
3192                value
3193                    .as_ref()
3194                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3195            ) {
3196                return Ok(vec![control_error_frame(
3197                    &frame,
3198                    code,
3199                    "registration channel HELLO refused",
3200                )?]);
3201            }
3202        }
3203        debug!(
3204            connection_id = connection_id.get(),
3205            corr = frame.header.corr,
3206            "handling HELLO"
3207        );
3208        // A module connection has one identity for its entire lifetime. A second
3209        // registration would leave the old registry owner behind while replacing
3210        // its forwarding endpoint and launch nonce.
3211        if self
3212            .registry
3213            .get_module_by_connection(connection_id)
3214            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3215            .is_some()
3216        {
3217            return Ok(vec![control_error_frame(
3218                &frame,
3219                "invalid_hello",
3220                "connection is already registered as a module",
3221            )?]);
3222        }
3223        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3224            Ok(value) => value,
3225            Err(err) => {
3226                return Ok(vec![control_error_frame(
3227                    &frame,
3228                    "invalid_hello",
3229                    format!("malformed HELLO body: {err}"),
3230                )?])
3231            }
3232        };
3233        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3234            return Ok(vec![control_error_frame(
3235                &frame,
3236                error_codes::INVALID_PROVIDER_DECLARATIONS,
3237                detail,
3238            )?]);
3239        }
3240        if let Some(module) = hello_value
3241            .get("manifest")
3242            .and_then(|value| value.get("module_id"))
3243            .and_then(|value| value.as_str())
3244        {
3245            let recovering = self
3246                .config_runtime
3247                .as_ref()
3248                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3249            // Defence in depth: RuntimeOwner::module_is_gated in
3250            // config_gate/admission.rs already gates every id during recovery.
3251            // A registration channel still never uses the nonce fallback.
3252            if recovering
3253                && channel_spawn.as_ref().is_none_or(|spawn| {
3254                    !self.supervisor.has_live_verified_channel_binding(spawn)
3255                        || spawn.check().is_err()
3256                })
3257                && !(channel_spawn.is_none()
3258                    && hello_value
3259                        .get("launch_nonce")
3260                        .and_then(|value| value.as_str())
3261                        .is_some_and(|nonce| {
3262                            self.supervisor.spawned_consumer_authorized(module, nonce)
3263                                && self
3264                                    .supervisor
3265                                    .has_live_verified_program_binding(module, nonce)
3266                        }))
3267            {
3268                return Ok(vec![control_error_frame(
3269                    &frame,
3270                    "config_gated",
3271                    "recovery admits only previously bound supervised launches",
3272                )?]);
3273            }
3274            if self
3275                .config_runtime
3276                .as_ref()
3277                .is_some_and(|owner| owner.module_is_gated(module))
3278                && (channel_spawn
3279                    .as_ref()
3280                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3281                    || self.config_runtime.as_ref().is_some_and(|owner| {
3282                        !recovering && owner.check_module_hold(module).is_err()
3283                    }))
3284            {
3285                return Ok(vec![control_error_frame(
3286                    &frame,
3287                    "reserved_module",
3288                    "a gated identity belongs only to its supervised child",
3289                )?]);
3290            }
3291        }
3292        if channel_spawn.is_none() {
3293            if let (Some(module), Some(nonce)) = (
3294                hello_value
3295                    .get("manifest")
3296                    .and_then(|value| value.get("module_id"))
3297                    .and_then(|value| value.as_str()),
3298                hello_value
3299                    .get("launch_nonce")
3300                    .and_then(|value| value.as_str()),
3301            ) {
3302                let binding = self.supervisor.has_program_binding_record(module, nonce);
3303                let required = self
3304                    .config_runtime
3305                    .as_ref()
3306                    .is_some_and(|owner| owner.module_is_gated(module));
3307                if let Some(error) = (binding || required)
3308                    .then(|| {
3309                        self.supervisor
3310                            .check_current_program_binding(module, nonce)
3311                            .err()
3312                    })
3313                    .flatten()
3314                {
3315                    let code = if error.code == "program_refused" {
3316                        "program_refused"
3317                    } else {
3318                        "config_delivery_deferred"
3319                    };
3320                    self.request_refusal_close(
3321                        connection_id,
3322                        sink.as_ref(),
3323                        CloseReason::new(code, error.detail.clone()),
3324                    );
3325                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3326                }
3327            }
3328        }
3329        if let Err(err) = validate_hello_display_name(&hello_value) {
3330            return Ok(vec![control_error_frame(
3331                &frame,
3332                "invalid_manifest",
3333                err.to_string(),
3334            )?]);
3335        }
3336        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3337            return Ok(vec![control_error_frame(
3338                &frame,
3339                "invalid_capability_grammar",
3340                err.to_string(),
3341            )?]);
3342        }
3343        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3344            return Ok(vec![control_error_frame(
3345                &frame,
3346                "invalid_manifest",
3347                err.to_string(),
3348            )?]);
3349        }
3350        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3351            return Ok(vec![control_error_frame(
3352                &frame,
3353                "invalid_event_declaration",
3354                err.to_string(),
3355            )?]);
3356        }
3357        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3358            return Ok(vec![control_error_frame(
3359                &frame,
3360                "invalid_manifest",
3361                err.to_string(),
3362            )?]);
3363        }
3364        if let Some(provenance) = hello_value
3365            .get("manifest")
3366            .and_then(|manifest| manifest.get("provenance"))
3367        {
3368            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3369                return Ok(vec![control_error_frame(
3370                    &frame,
3371                    "invalid_manifest",
3372                    format!("malformed manifest provenance: {err}"),
3373                )?]);
3374            }
3375        }
3376        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3377            let module_id = hello_value["manifest"]["module_id"]
3378                .as_str()
3379                .unwrap_or("<unknown>");
3380            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3381        }
3382        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3383            let module_id = hello_value
3384                .get("manifest")
3385                .and_then(|m| m.get("module_id"))
3386                .and_then(serde_json::Value::as_str)
3387                .unwrap_or("unknown");
3388            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3389        }
3390        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3391            let module_id = hello_value["manifest"]["module_id"]
3392                .as_str()
3393                .unwrap_or("<unknown>");
3394            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3395        }
3396        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3397            let module_id = hello_value["manifest"]["module_id"]
3398                .as_str()
3399                .unwrap_or("<unknown>");
3400            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3401        }
3402        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3403            Ok(hello) => hello,
3404            Err(err) => {
3405                return Ok(vec![control_error_frame(
3406                    &frame,
3407                    "invalid_hello",
3408                    format!("malformed HELLO body: {err}"),
3409                )?])
3410            }
3411        };
3412
3413        if hello.protocol_ver != hello.manifest.protocol_ver {
3414            return Ok(vec![control_error_frame(
3415                &frame,
3416                "invalid_manifest",
3417                format!(
3418                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3419                    hello.protocol_ver, hello.manifest.protocol_ver
3420                ),
3421            )?]);
3422        }
3423
3424        if hello.manifest.module_id.trim().is_empty() {
3425            return Ok(vec![control_error_frame(
3426                &frame,
3427                "invalid_manifest",
3428                "manifest module_id must not be empty",
3429            )?]);
3430        }
3431
3432        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3433            Ok(negotiated_ver) => negotiated_ver,
3434            Err(message) => {
3435                return Ok(vec![control_error_frame(
3436                    &frame,
3437                    "version_unsupported",
3438                    message,
3439                )?])
3440            }
3441        };
3442
3443        // Registration and forwarding publication use the same module gate as
3444        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3445        // precede those transitions. A program-refusal hold blocks future
3446        // spawns, but does not take this gate or revoke a HELLO whose supervised
3447        // child's image has already passed the check.
3448        let _publication_gate = if let Some(owner) = &self.config_runtime {
3449            let gate = owner
3450                .module_gate(&hello.manifest.module_id)
3451                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3452            Some(if wait_for_gate {
3453                gate.blocking_lock_owned()
3454            } else {
3455                match gate.try_lock_owned() {
3456                    Ok(guard) => guard,
3457                    Err(_) => {
3458                        return Ok(vec![control_error_frame(
3459                            &frame,
3460                            "config_delivery_deferred",
3461                            "module admission is busy",
3462                        )?])
3463                    }
3464                }
3465            })
3466        } else {
3467            None
3468        };
3469        #[cfg(test)]
3470        if let Some(hold) = &self.hello_before_publication_hold {
3471            hold.wait();
3472            hold.wait();
3473        }
3474        let module = &hello.manifest.module_id;
3475        let required = self
3476            .config_runtime
3477            .as_ref()
3478            .is_some_and(|owner| owner.module_is_gated(module));
3479        let recovering = self
3480            .config_runtime
3481            .as_ref()
3482            .is_some_and(|owner| owner.is_recovering());
3483        // Both entry paths (handle_control -> handle_hello and
3484        // handle_control_frame_timed -> spawn_blocking) enter this same
3485        // handle_hello_checked function. Its fresh, fail-closed store check
3486        // precedes parsing and this publication-gate check; this cached read
3487        // also observes any recovery transition published during that work.
3488        // The nonce-connection-only fallback is defence in depth alongside
3489        // RuntimeOwner::module_is_gated's all-id recovery gate.
3490        if recovering
3491            && channel_spawn.as_ref().is_none_or(|spawn| {
3492                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3493            })
3494            && !(channel_spawn.is_none()
3495                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3496                    self.supervisor.spawned_consumer_authorized(module, nonce)
3497                        && self
3498                            .supervisor
3499                            .has_live_verified_program_binding(module, nonce)
3500                }))
3501        {
3502            return Ok(vec![control_error_frame(
3503                &frame,
3504                "config_gated",
3505                "recovery admits only previously bound supervised launches",
3506            )?]);
3507        }
3508        if required
3509            && (channel_spawn
3510                .as_ref()
3511                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3512                || self
3513                    .config_runtime
3514                    .as_ref()
3515                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3516        {
3517            return Ok(vec![control_error_frame(
3518                &frame,
3519                "reserved_module",
3520                "gated admission requires the current supervised child's registration channel and verified image binding",
3521            )?]);
3522        }
3523        if let Some(spawn) = &channel_spawn {
3524            if let Err(code) = spawn.check() {
3525                return Ok(vec![control_error_frame(
3526                    &frame,
3527                    code,
3528                    "registration launch is no longer live",
3529                )?]);
3530            }
3531        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3532            if required || self.supervisor.has_program_binding_record(module, nonce) {
3533                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3534                    let code = if error.code == "program_refused" {
3535                        "program_refused"
3536                    } else {
3537                        "config_delivery_deferred"
3538                    };
3539                    self.request_refusal_close(
3540                        connection_id,
3541                        sink.as_ref(),
3542                        CloseReason::new(code, error.detail.clone()),
3543                    );
3544                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3545                }
3546            }
3547        }
3548
3549        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3550        // swap is open for this id, the only HELLO admitted as a second process
3551        // is the one carrying the candidate's launch nonce (the swap token), and
3552        // it registers into the candidate slot rather than being refused as a
3553        // duplicate. Run after the reserved gate, a reserved module's candidate
3554        // would be refused `reserved_module` for presenting a nonce that gate
3555        // does not know. See `SupervisorHandle::swap_hello_admission`.
3556        let swap_admission = match &channel_spawn {
3557            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3558            Some(_) => SwapHelloAdmission::NotSwapping,
3559            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3560            None => self
3561                .supervisor
3562                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3563        };
3564        if swap_admission == SwapHelloAdmission::ProtocolNone {
3565            warn!(
3566                module_id = %hello.manifest.module_id,
3567                connection_id = connection_id.get(),
3568                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3569            );
3570            // The code stays `swap_token_invalid` for existing callers; only the
3571            // explanation names the actual reason.
3572            return Ok(vec![control_error_frame(
3573                &frame,
3574                "swap_token_invalid",
3575                format!(
3576                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3577                    hello.manifest.module_id
3578                ),
3579            )?]);
3580        }
3581        if swap_admission == SwapHelloAdmission::ChannelRequired {
3582            warn!(
3583                module_id = %hello.manifest.module_id,
3584                connection_id = connection_id.get(),
3585                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3586            );
3587            // The code stays `swap_token_invalid` for existing callers; only the
3588            // explanation names the actual reason.
3589            return Ok(vec![control_error_frame(
3590                &frame,
3591                "swap_token_invalid",
3592                format!(
3593                    "module_id '{}' is gated; it must register over its supervised registration channel",
3594                    hello.manifest.module_id
3595                ),
3596            )?]);
3597        }
3598        if swap_admission == SwapHelloAdmission::Refused {
3599            warn!(
3600                module_id = %hello.manifest.module_id,
3601                connection_id = connection_id.get(),
3602                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3603            );
3604            return Ok(vec![control_error_frame(
3605                &frame,
3606                "swap_token_invalid",
3607                format!(
3608                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3609                    hello.manifest.module_id
3610                ),
3611            )?]);
3612        }
3613        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3614
3615        // A swap candidate proves its identity with the candidate nonce above.
3616        // Other registrations receive this catalog fact only when reserved-module
3617        // policy required and accepted a nonce; unreserved registrations require
3618        // no nonce check.
3619        let verification = if swap_candidate && channel_spawn.is_none() {
3620            ReservedHelloVerification {
3621                nonce_verified: true,
3622                prefix_owner: None,
3623            }
3624        } else {
3625            let verification = if let Some(binding) = &prefix_binding {
3626                if !self.supervisor.prefix_claim_authorized(
3627                    &binding.registration.module_id,
3628                    &hello.manifest.module_id,
3629                ) {
3630                    return Ok(vec![control_error_frame(
3631                        &frame,
3632                        "claim_prefix_refused",
3633                        "prefix ownership changed",
3634                    )?]);
3635                }
3636                Ok(ReservedHelloVerification {
3637                    nonce_verified: true,
3638                    prefix_owner: Some(binding.registration.module_id.clone()),
3639                })
3640            } else if channel_spawn.is_some() {
3641                self.supervisor
3642                    .channel_hello_verification(&hello.manifest.module_id)
3643            } else {
3644                self.supervisor.reserved_hello_verification(
3645                    &hello.manifest.module_id,
3646                    hello.launch_nonce.as_deref(),
3647                )
3648            };
3649            match verification {
3650                Ok(verified) => verified,
3651                Err(rejection) => {
3652                    let message = match rejection {
3653                        ReservedHelloRejection::Exact { module_id } => format!(
3654                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3655                        ),
3656                        ReservedHelloRejection::Prefix {
3657                            prefix,
3658                            owner_module_id,
3659                        } => format!(
3660                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3661                            hello.manifest.module_id
3662                        ),
3663                    };
3664                    return Ok(vec![control_error_frame(
3665                        &frame,
3666                        "reserved_module",
3667                        message,
3668                    )?]);
3669                }
3670            }
3671        };
3672
3673        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3674            &hello.manifest.module_id,
3675            hello.manifest.capabilities.as_ref(),
3676        );
3677        if let Some(refusal) = reserved_capability_refusals.first() {
3678            let capability = refusal.capability.clone();
3679            let bound_module = refusal.claimants[0].clone();
3680            log_duplicate_claim_events(reserved_capability_refusals);
3681            return Ok(vec![control_error_frame(
3682                &frame,
3683                "reserved_capability",
3684                format!(
3685                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3686                    capability, bound_module, hello.manifest.module_id
3687                ),
3688            )?]);
3689        }
3690
3691        // A connection that already opened client routes must not also register as
3692        // a module: cleanup would then release only one side and leak the other.
3693        if self
3694            .forwarding
3695            .connection_has_client_routes(connection_id)
3696            .map_err(RouterError::Forwarding)?
3697        {
3698            return Ok(vec![control_error_frame(
3699                &frame,
3700                "invalid_hello",
3701                "connection has open client routes and cannot also register as a module",
3702            )?]);
3703        }
3704
3705        // Kept for scope sync authority, which goes only to the connection that
3706        // presented the module's current launch nonce. Recorded before the
3707        // registration is attempted: a connection whose registration then fails
3708        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3709        // A registration channel's authority is the channel itself, never a
3710        // nonce it also presented, and a prefix registration's is its claim:
3711        // neither records one, so neither can fall back to nonce authority.
3712        self.hello_launch_nonces
3713            .lock()
3714            .unwrap_or_else(|poisoned| poisoned.into_inner())
3715            .record(
3716                connection_id,
3717                if prefix_binding.is_some() || channel_spawn.is_some() {
3718                    None
3719                } else {
3720                    hello.launch_nonce.as_deref()
3721                },
3722            );
3723        let control_ops = effective_module_control_ops(hello.control_ops);
3724        let prefix_submodule = verification.prefix_owner.is_some();
3725        // Built before anything is registered so an encoding failure leaves no
3726        // registry or forwarding state behind.
3727        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3728        #[cfg(test)]
3729        struct PublicationFinished(Arc<std::sync::Barrier>);
3730        #[cfg(test)]
3731        impl Drop for PublicationFinished {
3732            fn drop(&mut self) {
3733                self.0.wait();
3734            }
3735        }
3736        #[cfg(test)]
3737        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3738            hold.wait();
3739            hold.wait();
3740            PublicationFinished(hold.clone())
3741        });
3742        let publication_spawn = channel_spawn
3743            .as_ref()
3744            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3745        #[cfg(test)]
3746        if prefix_binding.is_some() {
3747            self.claims.pause_prefix_hello_for_test(7);
3748        }
3749        let _registration_publication = match publication_spawn {
3750            Some(spawn) => Some(match spawn.begin_publication() {
3751                Ok(guard) => guard,
3752                Err(code) => {
3753                    return Ok(vec![control_error_frame(
3754                        &frame,
3755                        code,
3756                        "registration ended before HELLO publication",
3757                    )?])
3758                }
3759            }),
3760            None => None,
3761        };
3762        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3763            let live = self.claims.lock_prefix_binding(binding, connection_id);
3764            let ownership = self.supervisor.prefix_claim_publication(
3765                &binding.registration.module_id,
3766                &hello.manifest.module_id,
3767            );
3768            if live.is_none()
3769                || ownership.is_none()
3770                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3771                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3772            {
3773                return Ok(vec![control_error_frame(
3774                    &frame,
3775                    "claim_prefix_refused",
3776                    "prefix authority ended before publication",
3777                )?]);
3778            }
3779            (live, ownership)
3780        } else {
3781            (None, None)
3782        };
3783        if let Some(spawn) = publication_spawn {
3784            self.forwarding
3785                .bind_spawn(connection_id, spawn)
3786                .map_err(RouterError::Forwarding)?;
3787        }
3788        // The spawn whose own registration this HELLO is, for `target` on
3789        // the route.open reply: its channel, or the launch its nonce was
3790        // minted for. A prefix child's HELLO names no spawn of its own. It is
3791        // only looked up here. The connection is bound to it and its
3792        // requested declarations are frozen once the registry has accepted
3793        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3794        // duplicate, or for any other reason, leaves the spawn untouched: its
3795        // closing connection is then no registration of the spawn and ends
3796        // none of the spawn's routes.
3797        let hello_authority = match (&channel_spawn, &prefix_binding) {
3798            (Some(spawn), _) => Some(spawn.authority.clone()),
3799            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3800                self.supervisor
3801                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3802            }),
3803            (None, Some(_)) => None,
3804        }
3805        .map(|record| HelloAuthority {
3806            record,
3807            requested: hello
3808                .manifest
3809                .provider_declarations
3810                .clone()
3811                .unwrap_or_default(),
3812            froze: Default::default(),
3813        });
3814        #[cfg(test)]
3815        if prefix_binding.is_some() {
3816            self.claims.pause_prefix_hello_for_test(8);
3817        }
3818        if swap_candidate {
3819            let module_id = hello.manifest.module_id.clone();
3820            let mut differing_declarations = Default::default();
3821            let reply = self.register_swap_candidate(
3822                connection_id,
3823                sink,
3824                &frame,
3825                hello.manifest,
3826                negotiated_ver,
3827                control_ops,
3828                hello_ack,
3829                hello_authority.as_ref(),
3830                &mut differing_declarations,
3831                #[cfg(windows)]
3832                hello.launch_nonce.as_deref(),
3833            )?;
3834            if let Some(spawn) = &channel_spawn {
3835                if self
3836                    .registry
3837                    .get_module_by_connection(connection_id)
3838                    .ok()
3839                    .flatten()
3840                    .is_some()
3841                {
3842                    if let Some(sink) = primary_sink {
3843                        spawn.bind_primary_sink(sink);
3844                    }
3845                    spawn.hello_accepted();
3846                }
3847            } else if self
3848                .registry
3849                .get_module_by_connection(connection_id)
3850                .ok()
3851                .flatten()
3852                .is_some()
3853            {
3854                self.supervisor
3855                    .retire_unused_registration_channel(&module_id, true);
3856            }
3857            if self
3858                .registry
3859                .get_module_by_connection(connection_id)
3860                .ok()
3861                .flatten()
3862                .is_some()
3863            {
3864                self.file_development_widening(
3865                    hello_authority.map(|authority| authority.record),
3866                    differing_declarations,
3867                );
3868            }
3869            return Ok(reply);
3870        }
3871        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3872        // is refused, but `catalog.list` does not show the module and the
3873        // catalog generation does not move until it is published below, once
3874        // its forwarding endpoint exists. Listing it now would advertise a
3875        // module that `route.open` still refuses for having no forwarding
3876        // connection.
3877        let registration = match self
3878            .registry
3879            .register_unpublished_verified_with_control_ops(
3880                hello.manifest,
3881                negotiated_ver,
3882                connection_id,
3883                control_ops,
3884                verification.nonce_verified,
3885            ) {
3886            Ok(registration) => registration,
3887            Err(RegistryError::DuplicateModuleId { module_id }) => {
3888                return Ok(vec![control_error_frame(
3889                    &frame,
3890                    "duplicate_module_id",
3891                    format!(
3892                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3893                    ),
3894                )?])
3895            }
3896            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3897                return Ok(vec![control_error_frame(
3898                    &frame,
3899                    "invalid_module_id",
3900                    err.to_string(),
3901                )?])
3902            }
3903            Err(err) => {
3904                return Ok(vec![control_error_frame(
3905                    &frame,
3906                    "registry_error",
3907                    err.to_string(),
3908                )?])
3909            }
3910        };
3911        let differing_declarations =
3912            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3913                Ok(differing) => differing,
3914                Err(err) => {
3915                    if matches!(
3916                        self.rollback_unpublished_hello(connection_id),
3917                        Ok(r) if !r.is_empty()
3918                    ) {
3919                        crate::supervise::notify_registration_release();
3920                    }
3921                    return Err(RouterError::Forwarding(err));
3922                }
3923            };
3924        #[cfg(test)]
3925        self.hold_between_registry_and_forwarding();
3926
3927        let mut reply = Vec::new();
3928        // Registry readers must wait from before the ACK can be read until
3929        // publication. Nest forwarding inside the registry lock, never reverse.
3930        let publication = self
3931            .registry
3932            .publish_registration_after(connection_id, || {
3933                if let Some(sink) = sink {
3934                    // The forwarding table's module store is also the daemon-to-module
3935                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3936                    // manifest has no routable provider role. Non-routable modules still
3937                    // cannot receive route.bind in production: `handle_route_open` checks
3938                    // the registry manifest with `target_has_required_role` before the
3939                    // only production call to `begin_route_bind_relay_for` below that
3940                    // route.open path. The remaining direct relay callers are unit tests
3941                    // and benchmark harnesses that construct forwarding state explicitly.
3942                    //
3943                    // The HELLO_ACK is queued by the forwarding table itself, before the
3944                    // endpoint becomes visible, and is NOT returned as a reply. A module
3945                    // reads HELLO_ACK first and exits on anything else; a reply is only
3946                    // written after this handler returns, by which time a route.open on
3947                    // another connection could already have queued a route.bind request
3948                    // for this module ahead of it.
3949                    let concurrency = manifest_concurrency(&registration.manifest);
3950                    self.forwarding.register_module_connection_acked(
3951                        connection_id,
3952                        registration.manifest.module_id.clone(),
3953                        negotiated_ver,
3954                        concurrency,
3955                        sink,
3956                        crate::forwarding::ModuleHelloAck {
3957                            frame: hello_ack,
3958                            verified_prefix_owner: verification.prefix_owner,
3959                        },
3960                    )?;
3961                } else {
3962                    // No sink means no forwarding endpoint, so nothing can be routed
3963                    // ahead of the ack; it goes out as the reply.
3964                    reply.push(hello_ack);
3965                }
3966                #[cfg(test)]
3967                self.hold_between_ack_and_publication();
3968                Ok(())
3969            })
3970            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3971        let published = match publication {
3972            Ok(published) => published,
3973            Err(err) => {
3974                // The registry lock has been released, so rollback can take it
3975                // again. No forwarding endpoint or route was published. Keep
3976                // forwarding's weak connection-to-spawn association until the
3977                // connection's read loop ends and removes its remaining routes.
3978                // Removing this unpublished entry does not advance the catalog
3979                // generation.
3980                if matches!(
3981                    self.rollback_unpublished_hello(connection_id),
3982                    Ok(r) if !r.is_empty()
3983                ) {
3984                    crate::supervise::notify_registration_release();
3985                }
3986                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3987                return Ok(vec![control_error_frame(
3988                    &frame,
3989                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
3990                        "invalid_hello"
3991                    } else {
3992                        forwarding_error_code(&err)
3993                    },
3994                    err.to_string(),
3995                )?]);
3996            }
3997        };
3998        if !published {
3999            debug!(
4000                module_id = %registration.manifest.module_id,
4001                connection_id = connection_id.get(),
4002                "registration was removed before it could be published"
4003            );
4004            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
4005            return Ok(reply);
4006        }
4007
4008        drop(_prefix_ownership);
4009        drop(_prefix_live);
4010
4011        // Exposure over assumption: Concurrency's serde default is pinned to the
4012        // pre-field behavior (ModuleManaged), so a management surface that is
4013        // genuinely Serial and just never declared it inherits concurrent
4014        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
4015        // turns "no module has been bitten yet" into the checkable claim "no
4016        // module is exposed" -- one read of the boot log instead of a fleet
4017        // audit. Detected from the raw HELLO bytes because the serde default
4018        // deliberately erases the absent/declared distinction from the type.
4019        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
4020            info!(
4021                module_id = %registration.manifest.module_id,
4022                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
4023            );
4024        }
4025        if registration.manifest.registration_channel == Some(false)
4026            && self
4027                .supervisor
4028                .module_is_gated(&registration.manifest.module_id)
4029            && self
4030                .config_runtime
4031                .as_ref()
4032                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
4033                .as_deref()
4034                == Some("declared")
4035        {
4036            warn!(module_id = %registration.manifest.module_id,
4037                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
4038        }
4039
4040        self.apply_registration_capabilities(&registration);
4041
4042        self.supervisor
4043            .record_activity_registration(&registration.manifest.module_id);
4044
4045        info!(
4046            module_id = %registration.manifest.module_id,
4047            module_version = %registration.manifest.module_version,
4048            negotiated_ver,
4049            routable_provider = manifest_provides_routable_role(&registration.manifest),
4050            connection_id = connection_id.get(),
4051            "module registered"
4052        );
4053
4054        if let Some(spawn) = &channel_spawn {
4055            if let Some(sink) = primary_sink {
4056                spawn.bind_primary_sink(sink);
4057            }
4058            spawn.hello_accepted();
4059        } else if !prefix_submodule {
4060            self.supervisor
4061                .retire_unused_registration_channel(&registration.manifest.module_id, false);
4062        }
4063        self.file_development_widening(
4064            hello_authority.map(|authority| authority.record),
4065            differing_declarations,
4066        );
4067        #[cfg(windows)]
4068        if let Some(nonce) = hello.launch_nonce.as_deref() {
4069            self.supervisor
4070                .program_hello_accepted(&registration.manifest.module_id, nonce);
4071        }
4072
4073        #[cfg(test)]
4074        if let Some(hold) = &self.hello_inside_publication_hold {
4075            hold.wait();
4076            hold.wait();
4077        }
4078
4079        Ok(reply)
4080    }
4081
4082    /// Register a HELLO the swap gate admitted into the candidate slot of the
4083    /// registry and of forwarding, where it is reachable over its own
4084    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
4085    /// nothing routes to it until the supervisor cuts over.
4086    ///
4087    /// Registry first (unpublished), then forwarding, then publication, the
4088    /// same order as an ordinary HELLO; a forwarding failure removes the
4089    /// registry entry again. The swap supervisor treats a published, ready
4090    /// candidate as registered and promotes it, and promotion needs the
4091    /// candidate's forwarding endpoint, so the candidate is published only
4092    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
4093    /// recompute capability verdicts or run the capability deny census
4094    /// (`enforce_capability_denies`): both are about the module in the active
4095    /// slot, which `route.open` can target. A candidate sits in the candidate
4096    /// slot, so it neither provides capabilities to other modules nor can be
4097    /// routed to until promotion moves it into the active slot.
4098    #[allow(clippy::too_many_arguments)]
4099    fn register_swap_candidate(
4100        &self,
4101        connection_id: ConnectionId,
4102        sink: Option<crate::FrameSink>,
4103        frame: &Frame,
4104        manifest: ModuleManifest,
4105        negotiated_ver: u8,
4106        control_ops: Vec<String>,
4107        hello_ack: Frame,
4108        hello_authority: Option<&HelloAuthority>,
4109        differing_declarations: &mut ProviderDeclarations,
4110        #[cfg(windows)] launch_nonce: Option<&str>,
4111    ) -> Result<Vec<Frame>, RouterError> {
4112        let module_id = manifest.module_id.clone();
4113        // Closing a swap and publishing its candidate must be ordered. The
4114        // spawn role proves which slot is intended, not that the slot is open.
4115        self.supervisor
4116            .with_swap_candidate_admission(&module_id, || {
4117                let reply = self.publish_swap_candidate(
4118                    connection_id,
4119                    sink,
4120                    frame,
4121                    manifest,
4122                    negotiated_ver,
4123                    control_ops,
4124                    hello_ack,
4125                    hello_authority,
4126                    differing_declarations,
4127                    #[cfg(windows)]
4128                    launch_nonce,
4129                );
4130                let admitted = self
4131                    .registry
4132                    .get_candidate(&module_id)
4133                    .ok()
4134                    .flatten()
4135                    .is_some_and(|candidate| candidate.connection_id == connection_id);
4136                (reply, admitted)
4137            })
4138            .unwrap_or_else(|| {
4139                Ok(vec![control_error_frame(
4140                    frame,
4141                    "swap_token_invalid",
4142                    "swap ended before candidate HELLO publication",
4143                )?])
4144            })
4145    }
4146
4147    #[allow(clippy::too_many_arguments)]
4148    fn publish_swap_candidate(
4149        &self,
4150        connection_id: ConnectionId,
4151        sink: Option<crate::FrameSink>,
4152        frame: &Frame,
4153        manifest: ModuleManifest,
4154        negotiated_ver: u8,
4155        control_ops: Vec<String>,
4156        hello_ack: Frame,
4157        hello_authority: Option<&HelloAuthority>,
4158        differing_declarations: &mut ProviderDeclarations,
4159        #[cfg(windows)] launch_nonce: Option<&str>,
4160    ) -> Result<Vec<Frame>, RouterError> {
4161        let module_id = manifest.module_id.clone();
4162        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4163            manifest,
4164            negotiated_ver,
4165            connection_id,
4166            control_ops,
4167        ) {
4168            Ok(registration) => registration,
4169            Err(RegistryError::DuplicateModuleId { module_id }) => {
4170                return Ok(vec![control_error_frame(
4171                    frame,
4172                    "duplicate_module_id",
4173                    format!(
4174                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4175                    ),
4176                )?])
4177            }
4178            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4179                return Ok(vec![control_error_frame(
4180                    frame,
4181                    "invalid_module_id",
4182                    err.to_string(),
4183                )?])
4184            }
4185            Err(err) => {
4186                return Ok(vec![control_error_frame(
4187                    frame,
4188                    "registry_error",
4189                    err.to_string(),
4190                )?])
4191            }
4192        };
4193        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4194            Ok(differing) => differing,
4195            Err(err) => {
4196                if matches!(
4197                    self.rollback_unpublished_hello(connection_id),
4198                    Ok(r) if !r.is_empty()
4199                ) {
4200                    crate::supervise::notify_registration_release();
4201                }
4202                return Err(RouterError::Forwarding(err));
4203            }
4204        };
4205        #[cfg(test)]
4206        self.hold_between_registry_and_forwarding();
4207        let mut reply = Vec::new();
4208        let publication = self
4209            .registry
4210            .publish_registration_after(connection_id, || {
4211                if let Some(sink) = sink {
4212                    // Same ordering as an ordinary HELLO: queue the ACK before
4213                    // inserting the endpoint, and keep registry readers excluded
4214                    // until the candidate is published.
4215                    let concurrency = manifest_concurrency(&registration.manifest);
4216                    self.forwarding.register_candidate_module_connection_acked(
4217                        connection_id,
4218                        module_id.clone(),
4219                        negotiated_ver,
4220                        concurrency,
4221                        sink,
4222                        hello_ack,
4223                    )?;
4224                } else {
4225                    reply.push(hello_ack);
4226                }
4227                #[cfg(test)]
4228                self.hold_between_ack_and_publication();
4229                Ok(())
4230            })
4231            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4232        let published = match publication {
4233            Ok(published) => published,
4234            Err(err) => {
4235                if matches!(
4236                    self.rollback_unpublished_hello(connection_id),
4237                    Ok(r) if !r.is_empty()
4238                ) {
4239                    crate::supervise::notify_registration_release();
4240                }
4241                self.refuse_hello_authority(connection_id, hello_authority);
4242                return Ok(vec![control_error_frame(
4243                    frame,
4244                    forwarding_error_code(&err),
4245                    err.to_string(),
4246                )?]);
4247            }
4248        };
4249        if !published {
4250            debug!(
4251                module_id = %module_id,
4252                connection_id = connection_id.get(),
4253                "swap candidate registration was removed before it could be published"
4254            );
4255            self.refuse_hello_authority(connection_id, hello_authority);
4256            return Ok(reply);
4257        }
4258        info!(
4259            module_id = %module_id,
4260            module_version = %registration.manifest.module_version,
4261            negotiated_ver,
4262            ready = registration.ready,
4263            connection_id = connection_id.get(),
4264            "swap candidate registered; not routable until cutover"
4265        );
4266        #[cfg(windows)]
4267        if let Some(nonce) = launch_nonce {
4268            self.supervisor.program_hello_accepted(&module_id, nonce);
4269        }
4270        Ok(reply)
4271    }
4272
4273    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4274    /// spawn's requested provider declarations. Runs only once the registry
4275    /// has accepted the HELLO, before its endpoint is published, so a route
4276    /// reserved on the endpoint always finds the spawn. Returns the requested
4277    /// entries that differ from the saved approvals, for a widening request.
4278    fn admit_hello_authority(
4279        &self,
4280        connection: ConnectionId,
4281        authority: Option<&HelloAuthority>,
4282    ) -> Result<ProviderDeclarations, ForwardingError> {
4283        let Some(authority) = authority else {
4284            return Ok(ProviderDeclarations::new());
4285        };
4286        let froze = authority
4287            .record
4288            .freeze_declarations(authority.requested.clone());
4289        authority
4290            .froze
4291            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4292        self.forwarding
4293            .bind_target_authority(connection, authority.record.clone())
4294            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4295        Ok(froze.unwrap_or_default())
4296    }
4297
4298    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4299    /// registry accepted it, so the refused connection is no registration of
4300    /// the spawn and the spawn's declarations are left for the HELLO that
4301    /// does register it to freeze.
4302    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4303        let Some(authority) = authority else {
4304            return;
4305        };
4306        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4307            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4308        }
4309        if authority
4310            .froze
4311            .swap(false, std::sync::atomic::Ordering::Relaxed)
4312        {
4313            authority.record.unfreeze_refused_declarations();
4314        }
4315    }
4316
4317    fn build_hello_ack(
4318        &self,
4319        frame: &Frame,
4320        negotiated_ver: u8,
4321        module_id: &str,
4322    ) -> Result<Frame, RouterError> {
4323        let ack = ModuleHelloAckBody {
4324            negotiated_ver,
4325            subc_ops: module_subc_ops(),
4326            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4327            storage: self
4328                .storage_config
4329                .as_ref()
4330                .map(|cfg| cfg.descriptor_for(module_id)),
4331            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4332        };
4333        let body = serde_json::to_vec(&ack).map_err(|err| {
4334            RouterError::backend(
4335                0,
4336                frame.header.corr,
4337                format!("failed to encode HELLO_ACK: {err}"),
4338            )
4339        })?;
4340
4341        Frame::build_with_version(
4342            negotiated_ver,
4343            FrameType::HelloAck,
4344            control_flags(),
4345            0,
4346            0,
4347            frame.header.corr,
4348            body,
4349        )
4350        .map_err(RouterError::FrameBuild)
4351    }
4352
4353    async fn handle_client_control_request(
4354        &self,
4355        ctx: &RouteCtx,
4356        frame: Frame,
4357        request: ClientControlRequest,
4358        route_open_timings: &mut Option<RouteOpenTimings>,
4359    ) -> Result<Vec<Frame>, RouterError> {
4360        if let Some(owner) = &self.config_runtime {
4361            let module = match &request {
4362                ClientControlRequest::SupervisorRestart { module_id, .. }
4363                | ClientControlRequest::SupervisorReload { module_id }
4364                | ClientControlRequest::SupervisorSwap { module_id, .. }
4365                | ClientControlRequest::SupervisorSetEnabled {
4366                    module_id,
4367                    enabled: true,
4368                } => Some(module_id.as_str()),
4369                _ => None,
4370            };
4371            let rescan = matches!(
4372                &request,
4373                ClientControlRequest::SupervisorRescan { preview: false }
4374                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4375            );
4376            let held = if module.is_some() || rescan {
4377                let module = module.map(str::to_owned);
4378                owner
4379                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4380                    .await
4381            } else {
4382                Ok(())
4383            };
4384            if let Err(error) = held {
4385                if error.code != "config_delivery_deferred" {
4386                    let code = if error.code == "store_tampered" {
4387                        "store_tampered"
4388                    } else {
4389                        "config_gated"
4390                    };
4391                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4392                }
4393            }
4394        }
4395        if let Some(operation) = privileged_operation(&request) {
4396            let caller = self.resolve_caller(ctx.connection_id).await;
4397            let op = client_control_request_op(&request);
4398            let text = prompt_text(operation, &caller);
4399            match self.privileged_operator_prompt {
4400                PrivilegedOperatorPrompt::Log => {
4401                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4402                        target = ?operation, caller = %caller.description(), summary = %text,
4403                        "privileged request would prompt the operator");
4404                }
4405                PrivilegedOperatorPrompt::Enforce => {
4406                    let key =
4407                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4408                    let shortcut =
4409                        self.operator_shortcut_stamp(ctx.connection_id)
4410                            .await
4411                            .map(|stamp| {
4412                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
4413                            });
4414                    let outcome = self
4415                        .forwarding
4416                        .operator_confirms()
4417                        .approve_privileged_with_shortcut(
4418                            ctx,
4419                            &frame,
4420                            op,
4421                            text,
4422                            caller.description(),
4423                            key,
4424                            shortcut,
4425                        )
4426                        .await;
4427                    if outcome.code != "confirmed" {
4428                        return Ok(vec![outcome.frame(&frame)]);
4429                    }
4430                }
4431            }
4432        }
4433        match request {
4434            ClientControlRequest::DaemonShutdownIntent { intent } => {
4435                if intent.as_str() != Some("restart") {
4436                    return Ok(vec![control_error_frame(
4437                        &frame,
4438                        "invalid_params",
4439                        "intent must be 'restart'",
4440                    )?]);
4441                }
4442                // A stamped daemon boots a newer approved generation only from a
4443                // durable restart intent, written here before the daemon exits.
4444                // Failing to write it never blocks the restart: the next start
4445                // then boots the last active generation and the newer one waits.
4446                if let Some(owner) = &self.config_runtime {
4447                    match owner
4448                        .on_blocking(|owner| owner.assign_daemon_restart())
4449                        .await
4450                    {
4451                        Ok(Some(generation)) => {
4452                            info!(
4453                                generation,
4454                                "daemon restart will warm up approved generation"
4455                            )
4456                        }
4457                        Ok(None) => {}
4458                        Err(error) => warn!(
4459                            %error,
4460                            "daemon restart intent not recorded; the next start boots the last active generation"
4461                        ),
4462                    }
4463                }
4464                let response = ClientControlResponse::DaemonShutdownIntent {
4465                    intent: "restart".to_owned(),
4466                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4467                };
4468                Ok(vec![control_response_body_frame(
4469                    &frame,
4470                    &response,
4471                    "ClientControlResponse::DaemonShutdownIntent",
4472                )?])
4473            }
4474            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4475            ClientControlRequest::CatalogList { module_id } => {
4476                self.handle_catalog_list(frame, module_id)
4477            }
4478            ClientControlRequest::RouteOpen {
4479                target,
4480                identity,
4481                consumer_identity,
4482                consumer_capabilities,
4483                role_versions,
4484                busy_refusals,
4485                admission_facts,
4486                scope,
4487                ..
4488            } => {
4489                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4490                    &frame.body,
4491                ) {
4492                    Ok(extensions) => extensions,
4493                    Err(err) => {
4494                        return Ok(vec![control_error_frame(
4495                            &frame,
4496                            "invalid_control_body",
4497                            format!("malformed route.open extensions: {err}"),
4498                        )?]);
4499                    }
4500                };
4501                self.handle_route_open(
4502                    ctx,
4503                    frame,
4504                    RouteOpenRequest {
4505                        target,
4506                        identity,
4507                        consumer_identity,
4508                        consumer_capabilities,
4509                        role_versions,
4510                        busy_refusals,
4511                        admission_facts,
4512                        scope,
4513                        accepts_close_reasons: extensions.accepts_close_reasons,
4514                    },
4515                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4516                )
4517                .await
4518            }
4519            ClientControlRequest::RoutePoll {
4520                route_channel,
4521                route_epoch,
4522                kind,
4523            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4524            ClientControlRequest::SupervisorList {} => {
4525                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4526                    self.agent_declarations.refuse(
4527                        self,
4528                        ctx,
4529                        control_error_frame(
4530                            &frame,
4531                            "busy",
4532                            "supervisor list work is at capacity; retry",
4533                        )?,
4534                    );
4535                    return Ok(Vec::new());
4536                };
4537                // Filesystem-backed diagnostics must not hold up this connection's reader.
4538                let handler = self.clone();
4539                let sink = ctx.egress.clone();
4540                tokio::spawn(
4541                    async move {
4542                        let _permit = permit;
4543                        let result = handler.handle_supervisor_list(frame.clone()).await;
4544                        let replies = match result {
4545                            Ok(replies) => replies,
4546                            Err(error) => {
4547                                control_error_frame(&frame, "backend_error", error.to_string())
4548                                    .into_iter()
4549                                    .collect()
4550                            }
4551                        };
4552                        for reply in replies {
4553                            if !matches!(
4554                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4555                                    .await,
4556                                Ok(Ok(()))
4557                            ) {
4558                                break;
4559                            }
4560                        }
4561                    }
4562                    .with_current_subscriber(),
4563                );
4564                Ok(Vec::new())
4565            }
4566            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4567                self.handle_supervisor_spawn_snapshot(frame)
4568            }
4569            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4570                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4571            }
4572            ClientControlRequest::SupervisorRestart {
4573                module_id,
4574                drain_timeout_ms,
4575            } => {
4576                self.log_supervisor_request_received(
4577                    ctx,
4578                    frame.header.corr,
4579                    ops::SUPERVISOR_RESTART,
4580                    Some(&module_id),
4581                    None,
4582                )?;
4583                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4584                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4585                    .await
4586            }
4587            ClientControlRequest::SupervisorSwap {
4588                module_id,
4589                ready_timeout_ms,
4590            } => {
4591                self.log_supervisor_request_received(
4592                    ctx,
4593                    frame.header.corr,
4594                    ops::SUPERVISOR_SWAP,
4595                    Some(&module_id),
4596                    None,
4597                )?;
4598                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4599                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4600                    .await
4601            }
4602            ClientControlRequest::SupervisorReload { module_id } => {
4603                self.log_supervisor_request_received(
4604                    ctx,
4605                    frame.header.corr,
4606                    ops::SUPERVISOR_RELOAD,
4607                    Some(&module_id),
4608                    None,
4609                )?;
4610                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4611                self.handle_supervisor_reload(frame, module_id, requester)
4612                    .await
4613            }
4614            ClientControlRequest::SupervisorRescan { preview } => {
4615                if !preview {
4616                    self.log_supervisor_request_received(
4617                        ctx,
4618                        frame.header.corr,
4619                        ops::SUPERVISOR_RESCAN,
4620                        None,
4621                        None,
4622                    )?;
4623                }
4624                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4625                let operation = self.handle_supervisor_rescan(
4626                    frame,
4627                    if preview {
4628                        RescanMode::Preview
4629                    } else {
4630                        RescanMode::Execute
4631                    },
4632                    requester,
4633                );
4634                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4635                    .await
4636            }
4637            ClientControlRequest::SupervisorRescanChecked {
4638                preview,
4639                candidate,
4640                expect,
4641            } => {
4642                self.observe_control_wait(
4643                    ctx,
4644                    None,
4645                    ops::SUPERVISOR_RESCAN,
4646                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4647                )
4648                .await
4649            }
4650            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4651                self.log_supervisor_request_received(
4652                    ctx,
4653                    frame.header.corr,
4654                    ops::SUPERVISOR_RELEASE_RESERVED,
4655                    Some(&module_id),
4656                    None,
4657                )?;
4658                self.handle_supervisor_release_reserved(frame, module_id)
4659                    .await
4660            }
4661            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4662                self.log_supervisor_request_received(
4663                    ctx,
4664                    frame.header.corr,
4665                    ops::SUPERVISOR_SET_ENABLED,
4666                    Some(&module_id),
4667                    Some(enabled),
4668                )?;
4669                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4670                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4671                    .await
4672            }
4673            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4674                self.handle_supervisor_health_probe(ctx, frame, module_id)
4675                    .await
4676            }
4677            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4678            ClientControlRequest::SupervisorRoutes { module_id } => {
4679                self.handle_supervisor_routes(frame, module_id)
4680            }
4681            ClientControlRequest::SupervisorProvenance { module_id } => {
4682                self.handle_supervisor_provenance(ctx, frame, module_id)
4683                    .await
4684            }
4685            ClientControlRequest::SupervisorStderrTail {
4686                module_id,
4687                max_lines,
4688                max_bytes,
4689            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4690            ClientControlRequest::SupervisorTerminals { module_id } => {
4691                self.handle_supervisor_terminals(ctx, frame, module_id)
4692                    .await
4693            }
4694        }
4695    }
4696
4697    fn log_supervisor_request_received(
4698        &self,
4699        ctx: &RouteCtx,
4700        corr: u64,
4701        op: &'static str,
4702        module_id: Option<&str>,
4703        enabled: Option<bool>,
4704    ) -> Result<(), RouterError> {
4705        let caller = self.supervisor_requester(ctx, corr)?;
4706        let caller = principal_label(&caller);
4707        // `Option` fields are recorded only when present, so a request with no
4708        // module id (rescan) or no enabled flag simply omits that field.
4709        info!(
4710            target: "control",
4711            op,
4712            module_id,
4713            enabled,
4714            connection_id = ctx.connection_id.get(),
4715            caller = %caller,
4716            "supervisor request received"
4717        );
4718        Ok(())
4719    }
4720
4721    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4722        Ok(self
4723            .registry
4724            .get_module_by_connection(ctx.connection_id)
4725            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4726            .map(|registration| Principal::Reserved {
4727                module_id: registration.manifest.module_id,
4728            })
4729            .unwrap_or(Principal::Direct))
4730    }
4731
4732    fn handle_module_control_request(
4733        &self,
4734        connection_id: ConnectionId,
4735        frame: Frame,
4736        request: ModuleControlRequestFromModule,
4737    ) -> Result<Vec<Frame>, RouterError> {
4738        match request {
4739            ModuleControlRequestFromModule::RouteAuthorize {
4740                principal,
4741                scope,
4742                target,
4743                expected,
4744            } => self.handle_route_authorize(
4745                connection_id,
4746                frame,
4747                principal,
4748                scope,
4749                target,
4750                expected,
4751            ),
4752            ModuleControlRequestFromModule::CatalogUpdate {
4753                provides,
4754                capabilities,
4755                ready,
4756            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4757            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4758                self.handle_catalog_update_role_declarations(
4759                    connection_id,
4760                    frame,
4761                    role_declarations,
4762                )
4763            }
4764            ModuleControlRequestFromModule::LiveRoots {} => {
4765                let registered = self
4766                    .registry
4767                    .get_module_by_connection(connection_id)
4768                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4769                let Some(registration) = registered else {
4770                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4771                };
4772                let response = self
4773                    .forwarding
4774                    .live_roots(&registration.manifest.module_id)
4775                    .map_err(RouterError::Forwarding)?;
4776                Ok(vec![control_response_body_frame(
4777                    &frame,
4778                    &response,
4779                    "ModuleControlResponseToModule::LiveRoots",
4780                )?])
4781            }
4782            ModuleControlRequestFromModule::AgentCommands {
4783                started,
4784                finished,
4785                known,
4786            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4787            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4788                self.handle_scope_sync(connection_id, frame, generation, scopes)
4789            }
4790            ModuleControlRequestFromModule::ScopeApply {
4791                generation,
4792                upsert,
4793                end,
4794            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4795            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4796                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4797            }
4798            _ => Ok(vec![control_error_frame(
4799                &frame,
4800                "unsupported_control_frame",
4801                "unsupported module control operation",
4802            )?]),
4803        }
4804    }
4805
4806    fn handle_scope_served_by(
4807        &self,
4808        connection_id: ConnectionId,
4809        frame: Frame,
4810    ) -> Result<Vec<Frame>, RouterError> {
4811        let registered = self
4812            .registry
4813            .get_module_by_connection(connection_id)
4814            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4815        let Some(registered) = registered else {
4816            return Ok(vec![control_error_frame(
4817                &frame,
4818                "not_registered",
4819                "scope.served_by requires an active module registration owned by this connection",
4820            )?]);
4821        };
4822        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4823        {
4824            Ok(request) => request,
4825            Err(err) => {
4826                return Ok(vec![control_error_frame(
4827                    &frame,
4828                    "invalid_control_body",
4829                    format!("malformed scope.served_by body: {err}"),
4830                )?])
4831            }
4832        };
4833        let answer = self
4834            .scopes
4835            .read()
4836            .unwrap_or_else(|poisoned| poisoned.into_inner())
4837            .served_by(
4838                &registered.manifest.module_id,
4839                &request.scope_ref,
4840                request.scope_epoch,
4841                &request.module_id,
4842            );
4843        let reply = subc_control::ScopeServedByReply::new(
4844            answer,
4845            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4846        );
4847        Ok(vec![control_response_body_frame(
4848            &frame,
4849            &reply,
4850            "ScopeServedByReply",
4851        )?])
4852    }
4853
4854    /// Explicit test-only phone policy; daemon configuration cannot select it.
4855    #[cfg(any(test, feature = "test-support"))]
4856    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
4857        self.operator_app_policy.phone_enabled = enabled;
4858        self
4859    }
4860
4861    /// Resolve folders before taking the scope-table lock: a slow filesystem
4862    /// must not hold up admissions for unrelated scoped routes.
4863    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
4864        let mut scopes = ScopeRecords::from(scopes);
4865        for (index, record) in scopes.records.iter_mut().enumerate() {
4866            if let Some(refusal) = Self::canonicalize_workdir(record) {
4867                scopes.refusals.insert(index, refusal);
4868            }
4869        }
4870        scopes
4871    }
4872
4873    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
4874        let workdir = record.workdir.as_mut()?;
4875        let path = std::path::Path::new(workdir);
4876        if !path.is_absolute() {
4877            return Some((
4878                error_codes::INVALID_WORKDIR,
4879                "workdir must be absolute".to_string(),
4880            ));
4881        }
4882        match ProjectRootId::from_path_allowing_missing(path) {
4883            Ok(root) => match root.as_path().to_str() {
4884                Some(canonical) => {
4885                    *workdir = canonical.to_string();
4886                    None
4887                }
4888                None => Some((
4889                    error_codes::INVALID_WORKDIR,
4890                    "canonical workdir is not UTF-8".to_string(),
4891                )),
4892            },
4893            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
4894        }
4895    }
4896
4897    /// `scope.sync`: the owner is the module registered on this connection.
4898    /// A connection with no registration (every client connection, `direct`
4899    /// included) is refused `not_registered` before the table is consulted.
4900    fn handle_scope_sync(
4901        &self,
4902        connection_id: ConnectionId,
4903        frame: Frame,
4904        generation: u64,
4905        scopes: Vec<ScopeRecord>,
4906    ) -> Result<Vec<Frame>, RouterError> {
4907        self.handle_scope_change(connection_id, frame, generation, scopes, None)
4908    }
4909
4910    fn handle_scope_change(
4911        &self,
4912        connection_id: ConnectionId,
4913        frame: Frame,
4914        generation: u64,
4915        scopes: Vec<ScopeRecord>,
4916        end: Option<Vec<ScopeEnd>>,
4917    ) -> Result<Vec<Frame>, RouterError> {
4918        let is_apply = end.is_some();
4919        let Some(registration) = self
4920            .registry
4921            .get_module_by_connection(connection_id)
4922            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4923        else {
4924            return Ok(vec![control_error_frame(
4925                &frame,
4926                "not_registered",
4927                "scope.sync and scope.apply require an active module registration owned by this connection",
4928            )?]);
4929        };
4930        let owner = registration.manifest.module_id;
4931        let scopes = Self::prepare_scope_records(scopes);
4932        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
4933        let is_current_launch = |connection: ConnectionId| {
4934            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
4935        };
4936        // Lock order is the scope table, then the forwarding table: the new
4937        // tags are published, and the routes the change closes are selected,
4938        // while the scope table is still write-locked, so no admission can read
4939        // a record whose tag is not yet published.
4940        let mut table = self
4941            .scopes
4942            .write()
4943            .unwrap_or_else(|poisoned| poisoned.into_inner());
4944        let outcome = match end {
4945            Some(end) => table.apply(
4946                &owner,
4947                connection_id,
4948                is_current_launch,
4949                generation,
4950                scopes,
4951                end,
4952            ),
4953            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
4954        };
4955        let drained = match &outcome {
4956            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
4957            Err(_) => Vec::new(),
4958        };
4959        let has_deadlines = outcome.is_ok() && table.has_deadlines();
4960        drop(table);
4961        if has_deadlines {
4962            self.scope_deadline_added.notify_one();
4963        }
4964        match outcome {
4965            Ok(applied) => {
4966                let counts = ScopeOutcomeCounts::of(&applied.results);
4967                info!(
4968                    owner = %owner,
4969                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4970                    generation,
4971                    records = applied.results.len(),
4972                    created = counts.created,
4973                    replaced = counts.replaced,
4974                    updated = counts.updated,
4975                    unchanged = counts.unchanged,
4976                    refused = counts.refused,
4977                    ended = applied.ended.len(),
4978                    tag_changes = applied.tag_changes.len(),
4979                    routes_closed = drained.len(),
4980                    "scope change accepted"
4981                );
4982                // An accepted scope change can still refuse individual records, and the
4983                // owner is the only party that sees the reply. Name them here so
4984                // an operator can tell a refused session from a missing one
4985                // without the owner's logs. Capped so a call that refuses
4986                // thousands cannot flood the log; the count above is complete.
4987                for refused in applied
4988                    .results
4989                    .iter()
4990                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
4991                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
4992                {
4993                    warn!(
4994                        owner = %owner,
4995                        generation,
4996                        scope_ref = %refused.scope_ref,
4997                        scope_epoch = refused.scope_epoch,
4998                        code = refused.code.as_deref().unwrap_or(""),
4999                        "scope record refused"
5000                    );
5001                }
5002                self.close_scope_drained_routes(drained);
5003                let response = if is_apply {
5004                    ModuleControlResponseToModule::ScopeApply {
5005                        generation,
5006                        results: applied.results,
5007                        end_results: applied.end_results,
5008                        ended: applied.ended,
5009                    }
5010                } else {
5011                    ModuleControlResponseToModule::ScopeSync {
5012                        generation,
5013                        results: applied.results,
5014                        ended: applied.ended,
5015                    }
5016                };
5017                Ok(vec![control_response_body_frame(
5018                    &frame,
5019                    &response,
5020                    "scope change response",
5021                )?])
5022            }
5023            Err(refusal) => {
5024                info!(
5025                    owner = %owner,
5026                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
5027                    generation,
5028                    code = refusal.code,
5029                    "scope change refused"
5030                );
5031                Ok(vec![control_error_frame(
5032                    &frame,
5033                    refusal.code,
5034                    refusal.message,
5035                )?])
5036            }
5037        }
5038    }
5039
5040    /// Notify both endpoints of routes drained by a scope change.
5041    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
5042        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
5043    }
5044
5045    /// Re-authorize a stored source on a principal the module supplies.
5046    ///
5047    /// That principal carries no spawn or authority epoch, so this reply never
5048    /// conveys a caller attestation or a first-party mark, and a provider must
5049    /// not apply automatic grants on anything it authorizes.
5050    fn handle_route_authorize(
5051        &self,
5052        connection_id: ConnectionId,
5053        frame: Frame,
5054        principal: Principal,
5055        scope: subc_protocol::scope::RouteAuthorizeScope,
5056        target: String,
5057        expected: subc_protocol::scope::RouteAuthorizeExpected,
5058    ) -> Result<Vec<Frame>, RouterError> {
5059        use crate::scopes::admission::{admit_route, AdmissionMode};
5060        use subc_protocol::scope::{
5061            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
5062        };
5063        let registry = self
5064            .registry
5065            .route_admission_snapshot()
5066            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5067        let owner_configured = match &scope.owner {
5068            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5069            _ => false,
5070        };
5071        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
5072        let answer = {
5073            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
5074            let permitted = registry
5075                .iter()
5076                .find(|r| r.connection_id == connection_id)
5077                .is_some_and(|r| {
5078                    scopes.is_federated_owner(&Principal::Reserved {
5079                        module_id: r.module_id.clone(),
5080                    }) && r.capabilities.as_ref().is_some_and(|caps| {
5081                        caps.provides
5082                            .iter()
5083                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
5084                    })
5085                });
5086            if !permitted {
5087                drop(scopes);
5088                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
5089                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
5090            }
5091            admit_route(
5092                &scopes,
5093                &registry,
5094                &principal,
5095                &target,
5096                Some(&selector),
5097                owner_configured,
5098                AdmissionMode::Authorize(&expected),
5099            )
5100        };
5101        let response = match answer {
5102            Ok(admission) => {
5103                let mut response = RouteAuthorizeResponse::new(
5104                    RouteAuthorizeOutcome::Authorized,
5105                    "route admission authorized",
5106                );
5107                response.content_version = admission.content_version;
5108                response
5109            }
5110            Err(refusal) => refusal.response(),
5111        };
5112        Ok(vec![control_response_body_frame(
5113            &frame,
5114            &response,
5115            "RouteAuthorizeResponse",
5116        )?])
5117    }
5118
5119    /// `scope.describe`: any registered module may read any scope, because a
5120    /// provider must read the scope a route it serves is stamped with.
5121    fn handle_scope_describe(
5122        &self,
5123        connection_id: ConnectionId,
5124        frame: Frame,
5125        owner: Principal,
5126        scope_ref: String,
5127    ) -> Result<Vec<Frame>, RouterError> {
5128        let registered = self
5129            .registry
5130            .get_module_by_connection(connection_id)
5131            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5132        let Some(registered) = registered else {
5133            return Ok(vec![control_error_frame(
5134                &frame,
5135                "not_registered",
5136                "scope.describe requires an active module registration owned by this connection",
5137            )?]);
5138        };
5139        let scopes = self
5140            .scopes
5141            .read()
5142            .unwrap_or_else(|poisoned| poisoned.into_inner());
5143        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5144            return Ok(vec![control_error_frame(
5145                &frame,
5146                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5147                "scope.describe of the federated owner requires scope-federated/v1",
5148            )?]);
5149        }
5150        let mut description = scopes.describe(&owner, &scope_ref);
5151        drop(scopes);
5152        if owner
5153            != (Principal::Reserved {
5154                module_id: registered.manifest.module_id.clone(),
5155            })
5156        {
5157            if let Some(facts) = description
5158                .stamp
5159                .as_mut()
5160                .and_then(|stamp| stamp.attributes.federated.as_mut())
5161            {
5162                facts.stamp_required = false;
5163            }
5164        }
5165        // Describe readers also decode strict ScopeAttributes. Attribution is
5166        // safe to omit unless the requesting module declares it understands it.
5167        if !registered
5168            .manifest
5169            .capabilities
5170            .as_ref()
5171            .is_some_and(|caps| {
5172                caps.provides
5173                    .iter()
5174                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5175            })
5176        {
5177            if let Some(stamp) = description.stamp.as_mut() {
5178                stamp.attributes.on_behalf_of_agent = None;
5179            }
5180        }
5181        if !registered
5182            .manifest
5183            .capabilities
5184            .as_ref()
5185            .is_some_and(|caps| {
5186                caps.provides
5187                    .iter()
5188                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5189            })
5190        {
5191            if let Some(stamp) = description.stamp.as_mut() {
5192                stamp.attributes.flow_version = None;
5193                stamp.attributes.flow_code_hash = None;
5194                stamp.attributes.flow_install_id = None;
5195            }
5196        }
5197        let owner_configured = match &owner {
5198            // Ask whether the owner is configured (`is_configured`), not
5199            // whether it is on the roster (`get(..).is_some()`): a supervised
5200            // module's process can register and describe a scope before the
5201            // supervisor has put it on the roster.
5202            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5203            _ => false,
5204        };
5205        let response = ModuleControlResponseToModule::ScopeDescribe {
5206            status: description.status,
5207            scope_epoch: description.scope_epoch,
5208            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5209            owner_synced: description.owner_synced,
5210            owner_configured,
5211            scope: description.stamp,
5212        };
5213        Ok(vec![control_response_body_frame(
5214            &frame,
5215            &response,
5216            "ModuleControlResponseToModule::ScopeDescribe",
5217        )?])
5218    }
5219
5220    fn handle_catalog_update_role_declarations(
5221        &self,
5222        connection_id: ConnectionId,
5223        frame: Frame,
5224        role_declarations: serde_json::Value,
5225    ) -> Result<Vec<Frame>, RouterError> {
5226        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5227            return Ok(vec![control_error_frame(
5228                &frame,
5229                "invalid_role_declarations",
5230                err.to_string(),
5231            )?]);
5232        }
5233        let declarations = serde_json::from_value(role_declarations)
5234            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5235        if self
5236            .registry
5237            .replace_role_declarations_for_connection(connection_id, declarations)
5238            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5239            .is_none()
5240        {
5241            return Ok(vec![control_error_frame(
5242                &frame,
5243                "not_registered",
5244                "catalog.update_role_declarations requires an active module registration owned by this connection",
5245            )?]);
5246        }
5247        control_response_body_frame(
5248            &frame,
5249            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5250            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5251        )
5252        .map(|frame| vec![frame])
5253    }
5254
5255    fn handle_catalog_update(
5256        &self,
5257        connection_id: ConnectionId,
5258        frame: Frame,
5259        provides: Vec<ProviderRole>,
5260        capabilities: Option<CapabilityDeclarations>,
5261        ready: Option<bool>,
5262    ) -> Result<Vec<Frame>, RouterError> {
5263        self.refresh_capability_requirements();
5264        let Some(registration) = self
5265            .registry
5266            .get_module_by_connection(connection_id)
5267            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5268        else {
5269            return Ok(vec![control_error_frame(
5270                &frame,
5271                "not_registered",
5272                "catalog.update requires an active module registration owned by this connection",
5273            )?]);
5274        };
5275
5276        if let Some(message) =
5277            catalog_update_frozen_field_message(&registration.manifest, &provides)
5278        {
5279            return Ok(vec![control_error_frame(
5280                &frame,
5281                "catalog_update_frozen_field",
5282                message,
5283            )?]);
5284        }
5285
5286        let mut candidate = registration.manifest.clone();
5287        candidate.provides = provides.clone();
5288        candidate.capabilities = capabilities
5289            .clone()
5290            .or_else(|| registration.manifest.capabilities.clone());
5291        if let Some(rich_ui) = &candidate.rich_ui {
5292            if let Err(err) = rich_ui.validate() {
5293                return Ok(vec![control_error_frame(
5294                    &frame,
5295                    "invalid_manifest",
5296                    err.to_string(),
5297                )?]);
5298            }
5299        }
5300        if let Err(err) = candidate.validate_capability_grammar() {
5301            return Ok(vec![control_error_frame(
5302                &frame,
5303                "invalid_capability_grammar",
5304                err.to_string(),
5305            )?]);
5306        }
5307
5308        // Updates must honor the same reserved owner as initial registration;
5309        // otherwise an empty HELLO could acquire the claim after admission.
5310        let mut conflicts = self
5311            .capability_evaluator
5312            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5313        if let Some(conflict) = conflicts.first() {
5314            let message = format!(
5315                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5316                conflict.capability, conflict.claimants[0], candidate.module_id
5317            );
5318            for conflict in &mut conflicts {
5319                conflict.source = DuplicateClaimSource::CatalogUpdate;
5320            }
5321            log_duplicate_claim_events(conflicts);
5322            return Ok(vec![control_error_frame(
5323                &frame,
5324                "reserved_capability",
5325                message,
5326            )?]);
5327        }
5328
5329        let updated = match self.registry.replace_catalog_for_connection(
5330            connection_id,
5331            provides,
5332            capabilities,
5333            ready,
5334        ) {
5335            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5336                return Ok(vec![control_error_frame(
5337                    &frame,
5338                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5339                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5340                )?])
5341            }
5342            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5343                return Ok(vec![control_error_frame(
5344                    &frame,
5345                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5346                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5347                )?])
5348            }
5349            result => {
5350                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5351            }
5352        };
5353        if updated.is_none() {
5354            return Ok(vec![control_error_frame(
5355                &frame,
5356                "not_registered",
5357                "catalog.update requires an active module registration owned by this connection",
5358            )?]);
5359        }
5360        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5361            log_duplicate_claim_events(
5362                self.capability_evaluator
5363                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5364            );
5365        }
5366        if capability_census_trigger(
5367            registration.manifest.capabilities.as_ref(),
5368            updated
5369                .as_ref()
5370                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5371        ) {
5372            self.enforce_capability_denies();
5373        }
5374        self.refresh_capability_requirements();
5375
5376        let response = ModuleControlResponseToModule::CatalogUpdate {};
5377        control_response_body_frame(
5378            &frame,
5379            &response,
5380            "ModuleControlResponseToModule::CatalogUpdate",
5381        )
5382        .map(|frame| vec![frame])
5383    }
5384
5385    pub(crate) fn with_activity_ledger_config(
5386        mut self,
5387        run_dir: &Path,
5388        incarnation: String,
5389        config: crate::activity::ActivityConfig,
5390    ) -> Self {
5391        self.activity = Some(crate::activity::ActivityLedger::open_config(
5392            run_dir.join("activity.jsonl"),
5393            incarnation,
5394            config,
5395        ));
5396        self.supervisor.set_activity(self.activity.clone());
5397        self
5398    }
5399
5400    pub(crate) async fn configure_activity(
5401        &self,
5402        config: crate::activity::ActivityConfig,
5403    ) -> Result<(), &'static str> {
5404        match &self.activity {
5405            Some(ledger) => ledger.configure(config).await,
5406            None => Ok(()),
5407        }
5408    }
5409
5410    fn cancel_activity_subscription(
5411        &self,
5412        ctx: &RouteCtx,
5413        frame: &Frame,
5414    ) -> Result<bool, RouterError> {
5415        let task = self
5416            .activity_streams
5417            .lock()
5418            .unwrap_or_else(|p| p.into_inner())
5419            .remove(&(ctx.connection_id, frame.header.corr));
5420        let Some(task) = task else {
5421            return Ok(false);
5422        };
5423        task.abort();
5424        let end = Frame::build_with_version(
5425            response_version(frame),
5426            FrameType::StreamEnd,
5427            control_flags(),
5428            0,
5429            0,
5430            frame.header.corr,
5431            Vec::new(),
5432        )
5433        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5434        let sink = ctx.egress.clone();
5435        tokio::spawn(async move {
5436            let _ = sink.send(end).await;
5437        });
5438        Ok(true)
5439    }
5440
5441    async fn handle_activity_read(
5442        &self,
5443        ctx: &RouteCtx,
5444        frame: Frame,
5445    ) -> Result<Vec<Frame>, RouterError> {
5446        #[cfg(test)]
5447        {
5448            let pause = self
5449                .activity_request_pause
5450                .lock()
5451                .unwrap()
5452                .clone()
5453                .filter(|pause| pause.connection == ctx.connection_id);
5454            if let Some(pause) = pause {
5455                let _cancelled = ActivityRequestCancellation(pause.clone());
5456                pause.started.notify_one();
5457                std::future::pending::<()>().await;
5458            }
5459        }
5460        use subc_control::{
5461            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5462            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5463        };
5464        #[derive(Deserialize)]
5465        struct Identity {
5466            #[serde(default)]
5467            consumer_identity: Option<ConsumerIdentity>,
5468        }
5469        // A registration channel or claim-bound connection carries its module in
5470        // its binding, so no request field can name another principal, and its
5471        // subscription ends when the bound spawn's authority does.
5472        let mut bound_spawn = None;
5473        let legacy = match self.activity_reader(ctx.connection_id) {
5474            channel_operations::ActivityReader::Module { module_id, spawn } => {
5475                bound_spawn = Some(spawn);
5476                Some(Ok(Principal::Reserved { module_id }))
5477            }
5478            // Refused outright: falling back to `direct` would admit it.
5479            channel_operations::ActivityReader::Refused => {
5480                return Ok(vec![control_error_frame(
5481                    &frame,
5482                    ACTIVITY_READ_FORBIDDEN,
5483                    "helper, relay and retired connections cannot read activity",
5484                )?]);
5485            }
5486            channel_operations::ActivityReader::Legacy => None,
5487        };
5488        // A registered module connection already identifies its caller. Ignore
5489        // consumer_identity there so a module cannot borrow a mirror's identity.
5490        // Only separate consumer connections use the Direct/nonce trust boundary.
5491        let principal = match legacy {
5492            Some(principal) => principal,
5493            None => match self
5494                .forwarding
5495                .module_id_for_connection(ctx.connection_id)
5496                .map_err(RouterError::Forwarding)?
5497            {
5498                Some(module_id) => Ok(Principal::Reserved { module_id }),
5499                None => {
5500                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5501                        Ok(identity) => identity,
5502                        Err(_) => {
5503                            return Ok(vec![control_error_frame(
5504                                &frame,
5505                                ACTIVITY_MALFORMED,
5506                                "malformed activity read",
5507                            )?])
5508                        }
5509                    };
5510                    self.route_open_principal(
5511                        ctx.connection_id,
5512                        &frame,
5513                        identity.consumer_identity,
5514                    )?
5515                }
5516            },
5517        };
5518        let admitted = matches!(principal, Ok(Principal::Direct))
5519            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5520        if !admitted {
5521            return Ok(vec![control_error_frame(
5522                &frame,
5523                ACTIVITY_READ_FORBIDDEN,
5524                "activity reads require an operator or trusted mirror principal",
5525            )?]);
5526        }
5527        let Some(ledger) = &self.activity else {
5528            return Ok(vec![control_error_frame(
5529                &frame,
5530                ACTIVITY_UNAVAILABLE,
5531                "activity ledger unavailable",
5532            )?]);
5533        };
5534        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5535            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5536        {
5537            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5538                Ok(request) => ledger.query(request).await,
5539                Err(_) => Err(ACTIVITY_MALFORMED),
5540            };
5541            return match result {
5542                Ok(reply) => Ok(vec![control_response_body_frame(
5543                    &frame,
5544                    &reply,
5545                    ops::ACTIVITY_QUERY,
5546                )?]),
5547                Err(code) => Ok(vec![control_error_frame(
5548                    &frame,
5549                    code,
5550                    "activity query refused",
5551                )?]),
5552            };
5553        }
5554        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5555            Ok(request) => request,
5556            Err(_) => {
5557                return Ok(vec![control_error_frame(
5558                    &frame,
5559                    ACTIVITY_MALFORMED,
5560                    "malformed activity subscription",
5561                )?])
5562            }
5563        };
5564        let mut subscription = match ledger.subscribe(request.since).await {
5565            Ok(subscription) => subscription,
5566            Err(code) => {
5567                return Ok(vec![control_error_frame(
5568                    &frame,
5569                    code,
5570                    "activity subscription refused",
5571                )?])
5572            }
5573        };
5574        let key = (ctx.connection_id, frame.header.corr);
5575        let sink = ctx.egress.clone();
5576        let mut streams = self
5577            .activity_streams
5578            .lock()
5579            .unwrap_or_else(|p| p.into_inner());
5580        streams.retain(|_, task| !task.is_finished());
5581        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5582            return Ok(vec![control_error_frame(
5583                &frame,
5584                "duplicate_subscription",
5585                "activity subscription correlation id already in use",
5586            )?]);
5587        }
5588        let stream = async move {
5589            loop {
5590                let entry = if let Some(entry) = subscription.replay.pop_front() {
5591                    Some(entry)
5592                } else {
5593                    subscription.receiver.recv().await
5594                };
5595                let Some(entry) = entry else {
5596                    break;
5597                };
5598                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5599                    return;
5600                };
5601                let Ok(next) = Frame::build_with_version(
5602                    response_version(&frame),
5603                    FrameType::StreamData,
5604                    control_flags(),
5605                    0,
5606                    0,
5607                    frame.header.corr,
5608                    body,
5609                ) else {
5610                    return;
5611                };
5612                if sink.send(next).await.is_err() {
5613                    return;
5614                }
5615            }
5616            // Dropping a full subscriber's sender drains its accepted entries
5617            // before the terminal error, preserving their order on the wire.
5618            if let Some(code) = subscription.terminal_code() {
5619                if let Ok(end) =
5620                    control_error_frame(&frame, code, "activity subscriber fell behind")
5621                {
5622                    let _ = sink.send(end).await;
5623                }
5624            }
5625        };
5626        // The spawn's retirement revokes this connection's authority. End the
5627        // subscription then, rather than when the connection's close is
5628        // eventually processed or the next entry fails to send.
5629        let task = tokio::spawn(async move {
5630            match bound_spawn {
5631                Some(spawn) => {
5632                    tokio::select! {
5633                        () = stream => {}
5634                        () = spawn.wait_closed() => {}
5635                    }
5636                }
5637                None => stream.await,
5638            }
5639        });
5640        streams.insert(key, task.abort_handle());
5641        Ok(Vec::new())
5642    }
5643
5644    async fn handle_activity_record(
5645        &self,
5646        ctx: &RouteCtx,
5647        frame: Frame,
5648    ) -> Result<Vec<Frame>, RouterError> {
5649        use subc_control::{
5650            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5651            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5652        };
5653        let result = async {
5654            let module = self
5655                .forwarding
5656                .module_id_for_connection(ctx.connection_id)
5657                .ok()
5658                .flatten()
5659                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5660            let request: ActivityRecordRequest =
5661                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5662            crate::activity::validate(&module, &request)?;
5663            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5664            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5665            let at_ms = std::time::SystemTime::now()
5666                .duration_since(std::time::UNIX_EPOCH)
5667                .unwrap_or_default()
5668                .as_millis() as u64;
5669            ledger.record(module, request, actor, at_ms).await
5670        }
5671        .await;
5672        match result {
5673            Ok(entry) => Ok(vec![control_response_body_frame(
5674                &frame,
5675                &ActivityRecordResponse { seq: entry.seq },
5676                "activity.record",
5677            )?]),
5678            Err(code) => Ok(vec![control_error_frame(
5679                &frame,
5680                code,
5681                "activity recording refused",
5682            )?]),
5683        }
5684    }
5685
5686    fn activity_actor(
5687        &self,
5688        connection: ConnectionId,
5689        module: &str,
5690        on: Option<&subc_control::ActivityOn>,
5691    ) -> Result<subc_control::ActivityActor, &'static str> {
5692        use crate::forwarding::{DataRoute, DataRouteState};
5693        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5694        let principal = |id: &str| Principal::Reserved {
5695            module_id: id.to_owned(),
5696        };
5697        let mut actor = ActivityActor {
5698            principal: principal(module),
5699            scope_owner: None,
5700            agent_id: None,
5701            run_id: None,
5702            flow_id: None,
5703            project_root: None,
5704            workdir: None,
5705            project_id: None,
5706        };
5707        let scope = match on {
5708            None => return Ok(actor),
5709            Some(ActivityOn::Scope(scope)) => {
5710                let selector = subc_protocol::scope::ScopeSelector::new(
5711                    principal(module),
5712                    scope.scope_ref.clone(),
5713                    Some(scope.epoch),
5714                );
5715                self.scopes
5716                    .read()
5717                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5718                    .attribute(&principal(module), module, &selector, true)
5719                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5720            }
5721            Some(ActivityOn::Route(route)) => {
5722                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5723                    .forwarding
5724                    .lookup_data_route(connection, route.channel, route.epoch)
5725                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5726                else {
5727                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5728                };
5729                if binding.module_id != module {
5730                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5731                }
5732                actor.principal = binding.principal.clone();
5733                actor.project_root = binding
5734                    .project_root
5735                    .as_ref()
5736                    .map(|root| root.as_path().to_path_buf());
5737                let Some(bound) = &binding.scope else {
5738                    return Ok(actor);
5739                };
5740                let owner = principal(&bound.owner);
5741                let selector = subc_protocol::scope::ScopeSelector::new(
5742                    owner.clone(),
5743                    bound.scope_ref.clone(),
5744                    Some(bound.tag.scope_epoch),
5745                );
5746                let admitted = self
5747                    .scopes
5748                    .read()
5749                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5750                    .attribute(&owner, module, &selector, true)
5751                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5752                if admitted.tag != bound.tag {
5753                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5754                }
5755                admitted
5756            }
5757        };
5758        actor.scope_owner = Some(scope.stamp.owner);
5759        actor.agent_id = scope.stamp.attributes.agent_id;
5760        actor.run_id = scope.stamp.attributes.run_id;
5761        actor.flow_id = scope.stamp.attributes.flow_id;
5762        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5763        actor.project_id = scope.stamp.project_id;
5764        Ok(actor)
5765    }
5766
5767    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5768        let module_id = self
5769            .claims
5770            .binding(connection)
5771            .filter(|binding| {
5772                binding.consumer_live(connection) && binding.registration.authority.alive()
5773            })
5774            .map(|binding| binding.registration.module_id.clone())
5775            .or_else(|| {
5776                self.registry
5777                    .module_id_for_connection(connection)
5778                    .ok()
5779                    .flatten()
5780            });
5781        let principal = module_id
5782            .map(|module_id| format!("reserved:{module_id}"))
5783            .unwrap_or_else(|| "direct".to_owned());
5784        self.control_usage
5785            .lock()
5786            .unwrap_or_else(|poisoned| poisoned.into_inner())
5787            .record(op, &principal);
5788    }
5789
5790    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5791        self.refresh_capability_requirements();
5792        // A bare connection count is ambiguous between many clients holding a
5793        // route each and one client accumulating hundreds, so publish the
5794        // concentration alongside it. Route state is best-effort here: a
5795        // diagnostic endpoint must still answer if the forwarding lock is
5796        // contended.
5797        let mut counters = self.counters.snapshot();
5798        if let Some(obj) = counters.as_object_mut() {
5799            obj.insert(
5800                "control_usage".into(),
5801                self.control_usage
5802                    .lock()
5803                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5804                    .snapshot(),
5805            );
5806        }
5807        let losses = self.resource_tracker.loss_diagnostics();
5808        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5809            if let Some(obj) = counters.as_object_mut() {
5810                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5811            }
5812        }
5813        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5814            obj.insert(
5815                "activity_unparseable_lines".into(),
5816                ledger.read_errors().into(),
5817            );
5818            obj.insert(
5819                "activity_lifecycle_append_failures".into(),
5820                ledger.lifecycle_failures().into(),
5821            );
5822            obj.insert(
5823                "activity_started_digest_skips".into(),
5824                ledger.lifecycle_digest_skips().into(),
5825            );
5826        }
5827        if let (Ok((connections_with_routes, max)), Some(obj)) = (
5828            self.forwarding.client_route_concentration(),
5829            counters.as_object_mut(),
5830        ) {
5831            obj.insert(
5832                "client_connections_with_routes".into(),
5833                connections_with_routes.into(),
5834            );
5835            obj.insert("max_routes_on_one_connection".into(), max.into());
5836        }
5837        // A module that is being fast-refused and a module that is fine look
5838        // identical from a client that retries and succeeds, so name the open
5839        // breakers here. This rides the existing free-form counters object
5840        // rather than a new wire field, so no sibling that deserializes
5841        // `ServerDescribe` has to be rebuilt to keep reading it.
5842        if let (Some(open_breakers), Some(obj)) = (
5843            self.route_bind_breakers.open_snapshot(),
5844            counters.as_object_mut(),
5845        ) {
5846            obj.insert("route_bind_breakers_open".into(), open_breakers);
5847        }
5848        // A daemon whose local endpoint could not be bound keeps serving TCP,
5849        // and the connection file names no endpoint. Name the reason here, in
5850        // the free-form counters object, so an operator reading daemon facts
5851        // sees it without searching the log, and no wire field changes.
5852        if let (Some(reason), Some(obj)) = (
5853            self.local_endpoint_unavailable.clone(),
5854            counters.as_object_mut(),
5855        ) {
5856            obj.insert("local_endpoint_unavailable".into(), reason.into());
5857        }
5858        let response = ClientControlResponse::ServerDescribe {
5859            protocol_ver: PROTOCOL_VERSION,
5860            subc_ops: subc_ops(),
5861            capabilities: self.describe_capabilities(),
5862            connected_clients: self.connected_clients.count(),
5863            counters: Some(counters),
5864            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
5865            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
5866            capability_requirements: self.capability_requirement_statuses(),
5867            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
5868            config_path: self
5869                .rescan
5870                .as_ref()
5871                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
5872        };
5873        Ok(vec![control_response_body_frame(
5874            &frame,
5875            &response,
5876            "ClientControlResponse::ServerDescribe",
5877        )?])
5878    }
5879
5880    fn handle_catalog_list(
5881        &self,
5882        frame: Frame,
5883        module_id: Option<String>,
5884    ) -> Result<Vec<Frame>, RouterError> {
5885        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
5886        Ok(vec![Frame::build_with_version(
5887            response_version(&frame),
5888            FrameType::Response,
5889            control_flags(),
5890            0,
5891            0,
5892            frame.header.corr,
5893            body,
5894        )
5895        .map_err(RouterError::FrameBuild)?])
5896    }
5897
5898    #[cfg(test)]
5899    fn uncached_catalog_list(
5900        &self,
5901        corr: u64,
5902        module_id: Option<&str>,
5903    ) -> Result<ClientControlResponse, RouterError> {
5904        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
5905    }
5906
5907    fn catalog_list_snapshot(
5908        &self,
5909        corr: u64,
5910        module_id: Option<&str>,
5911        include_declarations: bool,
5912    ) -> Result<ClientControlResponse, RouterError> {
5913        let (generation, modules) = self
5914            .registry
5915            .list_modules_with_nonce_verification()
5916            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
5917        let entries = modules
5918            .into_iter()
5919            .filter(|(registration, _)| {
5920                module_id
5921                    .map(|wanted| registration.manifest.module_id == wanted)
5922                    .unwrap_or(true)
5923            })
5924            .map(|(registration, nonce_verified)| {
5925                let entry = self
5926                    .catalog_discovery_entry(&registration, include_declarations)
5927                    .map_err(|err| RouterError::backend(0, corr, err))?;
5928                let not_ready = self.not_ready_reason(&registration);
5929                let mut entry = entry;
5930                entry.roles = registration.manifest.provides;
5931                entry.control_ops = registration.control_ops;
5932                Ok(entry
5933                    .with_ready(not_ready.is_none())
5934                    .with_display_name(registration.manifest.display_name)
5935                    .with_not_ready(not_ready)
5936                    .with_module_version(Some(registration.manifest.module_version))
5937                    .with_provenance(registration.manifest.provenance)
5938                    .with_capabilities(registration.manifest.capabilities)
5939                    .with_self_signals(registration.manifest.self_signals)
5940                    .with_events(registration.manifest.events)
5941                    .with_operation_delivery(registration.manifest.operation_delivery)
5942                    .with_operation_payload(registration.manifest.operation_payload)
5943                    .with_flow_operations(registration.manifest.flow_operations)
5944                    .with_operation_deferral(registration.manifest.operation_deferral)
5945                    .with_confirm_operations(registration.manifest.confirm_operations)
5946                    .with_rich_ui(registration.manifest.rich_ui)
5947                    .with_role_declarations(registration.manifest.role_declarations)
5948                    .with_nonce_verified(nonce_verified))
5949            })
5950            .collect::<Result<Vec<_>, RouterError>>()?;
5951        Ok(ClientControlResponse::CatalogList {
5952            generation,
5953            modules: entries,
5954            subc_ops: subc_ops(),
5955        })
5956    }
5957
5958    /// The caller fields for a refusal that only has the raw request frame,
5959    /// such as the connection-level admission refusal sent before the request
5960    /// reaches [`Self::handle_route_open`].
5961    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
5962        let Ok(ClientControlRequest::RouteOpen {
5963            identity,
5964            consumer_identity,
5965            scope,
5966            ..
5967        }) = parse_client_control_request(&frame.body)
5968        else {
5969            return RouteOpenCaller::unknown();
5970        };
5971        let principal = self
5972            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
5973            .map(|attested| attested.principal);
5974        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
5975    }
5976
5977    fn route_open_principal(
5978        &self,
5979        connection_id: ConnectionId,
5980        frame: &Frame,
5981        consumer_identity: Option<ConsumerIdentity>,
5982    ) -> Result<Result<Principal, Frame>, RouterError> {
5983        let attested = self
5984            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
5985            .map(|attested| attested.principal);
5986        self.route_open_principal_attested(frame, consumer_identity, attested)
5987    }
5988
5989    /// [`Self::route_open_principal`] with `attested` already taken by
5990    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
5991    /// claim or launch nonce once.
5992    fn route_open_principal_attested(
5993        &self,
5994        frame: &Frame,
5995        consumer_identity: Option<ConsumerIdentity>,
5996        attested: Option<Principal>,
5997    ) -> Result<Result<Principal, Frame>, RouterError> {
5998        if let Some(principal) = attested {
5999            return Ok(Ok(principal));
6000        }
6001        Ok(Err(control_error_frame(
6002            frame,
6003            "bad_consumer_identity",
6004            consumer_identity.map_or_else(
6005                || "connection claim is no longer authorized for routes".to_string(),
6006                |identity| format!(
6007                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
6008                    identity.module_id
6009                ),
6010            ),
6011        )?))
6012    }
6013
6014    /// Ordinary `route.open` refusals go through here; admission and breaker
6015    /// refusals log separately with their capacity or breaker state. The daemon can
6016    /// attest which code it sent: without the event, a client's "the daemon
6017    /// refused me" and the daemon's own view could only be reconciled by
6018    /// argument. Malformed input (`invalid_project_root`) does not come here;
6019    /// rejecting a request that was never a valid open is not a refusal of one.
6020    #[allow(clippy::too_many_arguments)]
6021    fn route_open_refusal_frame(
6022        &self,
6023        ctx: &RouteCtx,
6024        caller: &RouteOpenCaller,
6025        frame: &Frame,
6026        module_id: &str,
6027        reason: &'static str,
6028        code: &'static str,
6029        message: impl Into<String>,
6030    ) -> Result<Frame, RouterError> {
6031        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
6032        let detail = if matches!(
6033            reason,
6034            "registration_not_active"
6035                | "supervisor_not_live"
6036                | "no_forwarding_connection"
6037                | "reloading"
6038        ) {
6039            // A planned restart, reload or swap is already replacing the
6040            // process; it does not need a slot in the crash-restart budget.
6041            let expected_back = (reason == "reloading").then_some(true);
6042            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
6043        } else {
6044            None
6045        };
6046        control_error_body_frame(
6047            frame,
6048            ErrorBody {
6049                code: code.to_string(),
6050                message: message.into(),
6051                detail,
6052            },
6053        )
6054    }
6055
6056    fn route_open_recovery_detail(
6057        &self,
6058        module_id: &str,
6059        corr: u64,
6060        detail: Option<serde_json::Value>,
6061        expected_back: Option<bool>,
6062    ) -> Result<Option<serde_json::Value>, RouterError> {
6063        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
6064            return Ok(detail);
6065        };
6066        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
6067        detail["state"] = serde_json::json!(status.state.to_string());
6068        if let Some(expected_back) = expected_back {
6069            detail["expected_back"] = serde_json::json!(expected_back);
6070        } else if let Some(module) = self.supervisor.get(module_id) {
6071            match module.will_recover_after_connection_loss() {
6072                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
6073                Err(err) => warn!(
6074                    %module_id,
6075                    error = %err,
6076                    "failed to read route.open recovery verdict; omitting expected_back"
6077                ),
6078            }
6079        }
6080        Ok(Some(detail))
6081    }
6082
6083    /// Answer a waiting `route.open` whose relayed bind was refused.
6084    ///
6085    /// `daemon_authored` is provenance, not a code match: the daemon
6086    /// synthesized the refusal itself (a drain, a late reply, a scope that
6087    /// ended mid-bind) or the module refused the bind with its own body. A
6088    /// daemon refusal carries the daemon-origin bit; a module's own
6089    /// rejection is relayed with the bit clear, so a module that refuses
6090    /// with `module_reloading` still cannot mint a daemon refusal.
6091    #[allow(clippy::too_many_arguments)]
6092    fn route_bind_rejection(
6093        &self,
6094        ctx: &RouteCtx,
6095        caller: &RouteOpenCaller,
6096        frame: &Frame,
6097        target_module_id: &str,
6098        body: ErrorBody,
6099        daemon_authored: bool,
6100    ) -> Result<Vec<Frame>, RouterError> {
6101        // The daemon's own commit re-check refused the bind because the
6102        // scope ended or changed after admission. The module accepted;
6103        // counting it as a module rejection would blame the module. This
6104        // branch only runs for daemon-synthesized bodies: a module that
6105        // refuses with a scope code is answered as a module rejection below.
6106        if daemon_authored {
6107            let scope_code = match body.code.as_str() {
6108                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
6109                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
6110                _ => None,
6111            };
6112            if let Some(code) = scope_code {
6113                self.observe_route_open_refusal(
6114                    ctx,
6115                    caller,
6116                    target_module_id,
6117                    "scope_changed_before_commit",
6118                    code,
6119                );
6120                return Ok(vec![control_error_body_frame(frame, body)?]);
6121            }
6122        }
6123        self.counters
6124            .increment_route_open_refused("module_rejected");
6125        info!(
6126            target: "control",
6127            code = "module_rejected",
6128            module_code = ?body.code,
6129            module_id = ?target_module_id,
6130            connection_id = ctx.connection_id.get(),
6131            principal = %caller.principal,
6132            scope = %caller.scope,
6133            harness = %caller.harness,
6134            "route.open refused"
6135        );
6136        let refusal = if daemon_authored {
6137            control_error_body_frame(frame, body)?
6138        } else {
6139            control_relayed_error_body_frame(frame, body)?
6140        };
6141        Ok(vec![refusal])
6142    }
6143
6144    /// Refuse a `route.open` because the target module's bind-relay breaker is
6145    /// open, without attempting the relay.
6146    ///
6147    /// The wire code is `module_timeout`, which is the truth (the module has
6148    /// not been answering binds) and which both SDKs already classify as
6149    /// retryable with capped backoff. Reusing it is what keeps this change out
6150    /// of both SDKs; the daemon-side distinction lives in the counter key
6151    /// instead.
6152    ///
6153    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6154    /// While a breaker is open this fires on every open to that module, and the
6155    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6156    /// produced 261 lines about a single module inside 3000 lines of daemon
6157    /// log. The rare transitions are logged at warn/info instead and the volume
6158    /// is carried by the counter, so the evidence survives without the flood.
6159    /// The debug line keeps a per-refusal record reachable for whoever turns
6160    /// the level up.
6161    #[allow(clippy::too_many_arguments)]
6162    fn route_open_breaker_refusal_frame(
6163        &self,
6164        ctx: &RouteCtx,
6165        caller: &RouteOpenCaller,
6166        frame: &Frame,
6167        module_id: &str,
6168        consecutive_timeouts: u32,
6169        retry_in: Duration,
6170        probe_in_flight: bool,
6171    ) -> Result<Frame, RouterError> {
6172        self.counters
6173            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6174        debug!(
6175            target: "control",
6176            code = "module_timeout",
6177            module_id = ?module_id,
6178            connection_id = ctx.connection_id.get(),
6179            principal = %caller.principal,
6180            scope = %caller.scope,
6181            harness = %caller.harness,
6182            consecutive_timeouts,
6183            retry_in_ms = retry_in.as_millis() as u64,
6184            probe_in_flight,
6185            "route.open refused by open bind-relay breaker"
6186        );
6187        // Say what a caller can act on. An open bind-relay breaker means the
6188        // module timed out accepting several new routes in a row. The module
6189        // is still running and its established routes keep working; only new
6190        // route.open requests are refused until the cooldown ends and one
6191        // test route (the probe) gets through. A message that only counts
6192        // failed relays reads as "the module is down" to a worker that sees it.
6193        let detail = if probe_in_flight {
6194            "one test route is already being tried; retry once it settles".to_string()
6195        } else {
6196            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6197        };
6198        control_error_frame(
6199            frame,
6200            "module_timeout",
6201            format!(
6202                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6203                 timed out in a row); {detail}; its established routes are unaffected"
6204            ),
6205        )
6206    }
6207
6208    /// `code` is daemon vocabulary and prints plainly; `module_id` is the
6209    /// requester's bytes (an unknown target is whatever the client sent) and
6210    /// is Debug-formatted so control characters land in the log escaped
6211    /// rather than as terminal sequences for whoever tails it.
6212    ///
6213    /// `reason` names the check that refused, because one wire code has
6214    /// several senders: after a module registers, `target_unavailable` can
6215    /// come from a missing role, an inactive registration, a supervisor that
6216    /// has not marked the process live, a missing forwarding connection, or a
6217    /// failed relay, and a log that records only the code cannot say which of
6218    /// them fired. It is a static, daemon-chosen label per branch, so it is
6219    /// safe to print plainly and stays a closed set.
6220    fn observe_route_open_refusal(
6221        &self,
6222        ctx: &RouteCtx,
6223        caller: &RouteOpenCaller,
6224        module_id: &str,
6225        reason: &'static str,
6226        code: &'static str,
6227    ) {
6228        self.counters.increment_route_open_refused(code);
6229        info!(
6230            target: "control",
6231            code,
6232            reason,
6233            module_id = ?module_id,
6234            connection_id = ctx.connection_id.get(),
6235            principal = %caller.principal,
6236            scope = %caller.scope,
6237            harness = %caller.harness,
6238            "route.open refused"
6239        );
6240        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6241            self.route_outages.record_not_serving(module_id, reason);
6242        }
6243    }
6244
6245    /// Record an ACCEPTED route.open.
6246    ///
6247    /// Refusals have been logged and counted since the attestation work; accepts
6248    /// were invisible, so the daemon knew every principal it stamped and wrote
6249    /// none of them down. The party that attests the identity was the only party
6250    /// not recording it, which left a credential vault unable to name the sender
6251    /// of a call that reached it (claustrum #43) and left the launch-nonce
6252    /// concurrency question unanswerable from the outside.
6253    ///
6254    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6255    /// `code`/`module_id`/`connection_id` returns both directions of the same
6256    /// decision rather than two shapes a reader has to join by hand.
6257    ///
6258    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6259    /// and the difference carries information rather than being an
6260    /// inconsistency. This line is only reachable after a successful bind to a
6261    /// REGISTERED module, so the value has already passed HELLO validation
6262    /// including the path-hazard refusal and cannot contain control bytes. A
6263    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6264    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6265    ///
6266    /// Bare is also what every other daemon line already emits (`module
6267    /// registered`, `configured module supervised`). Shipping `?module_id` here
6268    /// made this instrument the only one in the file whose ids did not answer
6269    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6270    /// line whose whole purpose is being grepped beside its sibling.
6271    ///
6272    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6273    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6274    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6275    /// one are recorded identically. A test written against that harness passes
6276    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6277    /// green assertion that cannot fail. The same limit applies to the escaping
6278    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6279    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6280    /// Fencing either needs the real formatter, not the capture layer.
6281    ///
6282    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6283    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6284    /// to record. The ephemeral port would decay within minutes and answer only a
6285    /// live question. The identity question is instead answered by counting
6286    /// distinct live connections presenting one module's `consumer_identity` --
6287    /// "is anyone else holding this secret" rather than "is this the right
6288    /// process".
6289    fn observe_route_open_accept(
6290        &self,
6291        ctx: &RouteCtx,
6292        module_id: &str,
6293        principal: &str,
6294        scope: &str,
6295    ) {
6296        self.route_outages.record_accepted(module_id);
6297        self.counters.increment_route_open_accepted(principal);
6298        debug!(
6299            target: "control",
6300            principal,
6301            module_id,
6302            connection_id = ctx.connection_id.get(),
6303            scope = %scope,
6304            "route.open accepted"
6305        );
6306    }
6307
6308    fn supervised_absent_route_open_refusal_frame(
6309        &self,
6310        ctx: &RouteCtx,
6311        caller: &RouteOpenCaller,
6312        frame: &Frame,
6313        module_id: &str,
6314        code: &'static str,
6315        status: &crate::supervise::ModuleStatus,
6316    ) -> Result<Frame, RouterError> {
6317        self.counters.increment_route_open_refused(code);
6318        info!(
6319            target: "control",
6320            code,
6321            reason = "supervised_not_registered",
6322            module_id = ?module_id,
6323            connection_id = ctx.connection_id.get(),
6324            principal = %caller.principal,
6325            scope = %caller.scope,
6326            harness = %caller.harness,
6327            state = %status.state,
6328            enabled = status.enabled,
6329            live = status.live,
6330            "route.open refused"
6331        );
6332        // A supervised module whose process has not registered is not
6333        // serving, whatever the reason; the supervisor knows this id, so it is
6334        // safe to track.
6335        self.route_outages
6336            .record_not_serving(module_id, "supervised_not_registered");
6337        let message = if let Some(pid) = status.waiting_for_previous_pid {
6338            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6339                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6340            })
6341        } else {
6342            format!(
6343                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6344                status.state, status.enabled, status.live
6345            )
6346        };
6347        // `module_warming` here means the process is starting, running or
6348        // being restarted and has not registered yet. Nothing has to be
6349        // restarted for it to serve, so the crash budget does not decide it.
6350        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6351        control_error_body_frame(
6352            frame,
6353            ErrorBody {
6354                code: code.to_string(),
6355                message,
6356                detail: self.route_open_recovery_detail(
6357                    module_id,
6358                    frame.header.corr,
6359                    None,
6360                    expected_back,
6361                )?,
6362            },
6363        )
6364    }
6365
6366    async fn handle_route_open(
6367        &self,
6368        ctx: &RouteCtx,
6369        frame: Frame,
6370        request: RouteOpenRequest,
6371        timings: &mut RouteOpenTimings,
6372    ) -> Result<Vec<Frame>, RouterError> {
6373        let RouteOpenRequest {
6374            target,
6375            mut identity,
6376            consumer_identity,
6377            consumer_capabilities,
6378            role_versions,
6379            busy_refusals,
6380            admission_facts,
6381            scope,
6382            accepts_close_reasons,
6383        } = request;
6384        let target_module_id = target_module_id(&target).to_string();
6385        timings.module_id.clone_from(&target_module_id);
6386        if self
6387            .registry
6388            .get_module_by_connection(ctx.connection_id)
6389            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6390            .is_some()
6391        {
6392            return Ok(vec![control_error_frame(
6393                &frame,
6394                "invalid_request",
6395                "module connections cannot open client routes",
6396            )?]);
6397        }
6398        debug!(
6399            connection_id = ctx.connection_id.get(),
6400            corr = frame.header.corr,
6401            module_id = %target_module_id,
6402            "handling route.open"
6403        );
6404
6405        // The caller's attested principal, requested scope and harness, for
6406        // every `route.open refused` line below. The connection's claim
6407        // binding or launch nonce is checked here, once, and the answer is
6408        // reused where the principal is enforced further down, so the order
6409        // of refusals is unchanged.
6410        let attested =
6411            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6412        let mut caller = RouteOpenCaller::new(
6413            attested.as_ref().map(|attested| &attested.principal),
6414            scope.as_ref(),
6415            &identity,
6416        );
6417
6418        // A malformed declaration is refused first, before anything about the
6419        // target is looked up: the same body would be refused against any
6420        // module, so the caller learns nothing by retrying or waiting. An empty
6421        // map declares nothing and travels as no field at all, so a provider
6422        // only ever sees a missing field or a non-empty one.
6423        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6424        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6425            self.observe_route_open_refusal(
6426                ctx,
6427                &caller,
6428                &target_module_id,
6429                "invalid_role_versions",
6430                error_codes::INVALID_REQUEST,
6431            );
6432            return Ok(vec![control_error_body_frame(
6433                &frame,
6434                ErrorBody {
6435                    code: error_codes::INVALID_REQUEST.to_string(),
6436                    message: error.to_string(),
6437                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6438                },
6439            )?]);
6440        }
6441
6442        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6443            if status.waiting_for_previous_pid.is_some() {
6444                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6445                    ctx,
6446                    &caller,
6447                    &frame,
6448                    &target_module_id,
6449                    "module_warming",
6450                    &status,
6451                )?]);
6452            }
6453        }
6454
6455        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6456        // opposite. Below, a caller learns whether a module is unregistered,
6457        // supervised-but-down (with state/enabled/live), or registered without the
6458        // requested role. Elsewhere that is an enumeration leak: a probe learning
6459        // the shape of a fleet it cannot otherwise see.
6460        //
6461        // It is not one here, and the reason is the ACCESS MODEL rather than
6462        // anything about these errors. Reaching route.open requires the
6463        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6464        // connection file, so any caller who completes it already runs as this
6465        // user -- and can read subc.jsonc for the module list and `ck module
6466        // status` for live state. The reply discloses nothing the caller cannot
6467        // read more easily from disk, while the precision is load-bearing:
6468        // `unknown_module` is retryable and a missing role is not.
6469        //
6470        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6471        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6472        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6473        let admission_registry = self
6474            .registry
6475            .route_admission_snapshot()
6476            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6477        let Some(registration) =
6478            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6479        else {
6480            if let Some((status, warming)) =
6481                self.supervisor_status(&target_module_id, frame.header.corr)?
6482            {
6483                // BEFORE the two availability codes below, because for a module
6484                // that speaks no subc wire both of them are false comfort: they
6485                // say "not right now" and are retried, and this module will
6486                // never register no matter how long the caller waits. The
6487                // absence here is the declaration being honoured, not a module
6488                // that is late.
6489                if status.protocol == ModuleProtocol::None {
6490                    return Ok(vec![self.route_open_refusal_frame(
6491                        ctx,
6492                        &caller,
6493                        &frame,
6494                        &target_module_id,
6495                        "protocol_none",
6496                        error_codes::MODULE_NO_PROTOCOL,
6497                        format!(
6498                            "module_id '{target_module_id}' is declared protocol: none; \
6499                             it speaks no subc wire and serves no routes"
6500                        ),
6501                    )?]);
6502                }
6503                let code = if warming {
6504                    "module_warming"
6505                } else {
6506                    "target_unavailable"
6507                };
6508                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6509                    ctx,
6510                    &caller,
6511                    &frame,
6512                    &target_module_id,
6513                    code,
6514                    &status,
6515                )?]);
6516            }
6517            if let Some(removed_ago_ms) =
6518                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6519            {
6520                return Ok(vec![self.route_open_refusal_frame(
6521                    ctx,
6522                    &caller,
6523                    &frame,
6524                    &target_module_id,
6525                    "removed",
6526                    error_codes::MODULE_REMOVED,
6527                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6528                )?]);
6529            }
6530            return Ok(vec![self.route_open_refusal_frame(
6531                ctx,
6532                &caller,
6533                &frame,
6534                &target_module_id,
6535                "not_registered",
6536                error_codes::UNKNOWN_MODULE,
6537                format!("module_id '{target_module_id}' is not registered"),
6538            )?]);
6539        };
6540
6541        // Best-effort only: registry readiness and forwarding reservation use
6542        // different locks, so a module can flip readiness between this read and
6543        // the relay. Modules must still tolerate an `on_bind` while not ready.
6544        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6545            .is_err()
6546        {
6547            self.counters
6548                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6549            info!(
6550                target: "control",
6551                code = error_codes::MODULE_WARMING,
6552                module_id = ?target_module_id,
6553                connection_id = ctx.connection_id.get(),
6554                principal = %caller.principal,
6555                scope = %caller.scope,
6556                harness = %caller.harness,
6557                reason = "declared_not_ready",
6558                "route.open refused"
6559            );
6560            // The module is registered but says it cannot take work, which is
6561            // an outage from the caller's side even though its process is up.
6562            self.route_outages
6563                .record_not_serving(&target_module_id, "declared_not_ready");
6564            // The registered process can declare itself ready without a
6565            // restart, so an exhausted crash budget does not prevent serving.
6566            return Ok(vec![control_error_body_frame(
6567                &frame,
6568                ErrorBody {
6569                    code: error_codes::MODULE_WARMING.to_string(),
6570                    message: format!(
6571                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6572                    ),
6573                    detail: self.route_open_recovery_detail(
6574                        &target_module_id,
6575                        frame.header.corr,
6576                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6577                        Some(true),
6578                    )?,
6579                },
6580            )?]);
6581        }
6582
6583        // Effective readiness, second half: a module that declares a capability
6584        // `need: required` is not routable while that capability has no
6585        // registered provider. It is enforced HERE, as a retryable routing
6586        // refusal, and deliberately not as spawn ordering or a boot block. The
6587        // module is still started and registered and can make its own calls;
6588        // spawn ordering is a promise that cannot be kept once a provider
6589        // crashes at runtime, and refusing to boot would stop the whole
6590        // machine, including the tools needed to fix its configuration.
6591        //
6592        // "Provided" is the evaluator's verdict, which counts a provider as
6593        // soon as it has REGISTERED, not once it is ready. Two modules that
6594        // require each other's capabilities are therefore both routable once
6595        // both register; counting readiness instead would deadlock them.
6596        //
6597        // Only new opens are refused. Routes already bound when a provider
6598        // goes away stay bound: nothing here tears them down, and the module
6599        // answers them as it can. Like the readiness read above this is
6600        // best-effort against a provider registering or leaving concurrently.
6601        if let Some(capability) = self.first_unprovided_required_capability_for(
6602            &registration.module_id,
6603            registration.capabilities.as_ref(),
6604        ) {
6605            self.counters
6606                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6607            info!(
6608                target: "control",
6609                code = error_codes::MODULE_WARMING,
6610                module_id = ?target_module_id,
6611                connection_id = ctx.connection_id.get(),
6612                principal = %caller.principal,
6613                scope = %caller.scope,
6614                harness = %caller.harness,
6615                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6616                capability = %capability,
6617                "route.open refused"
6618            );
6619            return Ok(vec![control_error_body_frame(
6620                &frame,
6621                ErrorBody {
6622                    code: error_codes::MODULE_WARMING.to_string(),
6623                    message: format!(
6624                        "module_id '{target_module_id}' requires capability '{capability}', \
6625                         which no registered module provides; retry"
6626                    ),
6627                    detail: Some(serde_json::json!({
6628                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6629                        "capability": capability,
6630                    })),
6631                },
6632            )?]);
6633        }
6634
6635        if !target_has_required_role(&target, &registration.roles) {
6636            return Ok(vec![self.route_open_refusal_frame(
6637                ctx,
6638                &caller,
6639                &frame,
6640                &target_module_id,
6641                "role_not_provided",
6642                "target_unavailable",
6643                format!("module_id '{target_module_id}' does not provide the requested target"),
6644            )?]);
6645        }
6646
6647        if registration.state != ChannelState::Active {
6648            return Ok(vec![self.route_open_refusal_frame(
6649                ctx,
6650                &caller,
6651                &frame,
6652                &target_module_id,
6653                "registration_not_active",
6654                "target_unavailable",
6655                format!("module_id '{target_module_id}' is not active"),
6656            )?]);
6657        }
6658
6659        if self
6660            .forwarding
6661            .module_is_draining(&target_module_id)
6662            .map_err(RouterError::Forwarding)?
6663        {
6664            return Ok(vec![self.route_open_refusal_frame(
6665                ctx,
6666                &caller,
6667                &frame,
6668                &target_module_id,
6669                "reloading",
6670                "module_reloading",
6671                format!("module_id '{target_module_id}' is reloading"),
6672            )?]);
6673        }
6674
6675        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6676            process_liveness.process_live(&target_module_id) == Some(false)
6677        }) {
6678            // A module the supervisor is restarting or reloading can still hold
6679            // a registration: the old process before its connection closes, or
6680            // a new one that registered while the supervisor was draining. The
6681            // forwarding table does not see that as draining, but the consumer
6682            // should still be told to retry soon, exactly as for the drain
6683            // above, rather than that the target is unavailable.
6684            if process_liveness.process_replacing(&target_module_id) {
6685                return Ok(vec![self.route_open_refusal_frame(
6686                    ctx,
6687                    &caller,
6688                    &frame,
6689                    &target_module_id,
6690                    "reloading",
6691                    "module_reloading",
6692                    format!("module_id '{target_module_id}' is reloading"),
6693                )?]);
6694            }
6695            return Ok(vec![self.route_open_refusal_frame(
6696                ctx,
6697                &caller,
6698                &frame,
6699                &target_module_id,
6700                "supervisor_not_live",
6701                "target_unavailable",
6702                format!("module_id '{target_module_id}' is not live"),
6703            )?]);
6704        }
6705
6706        if !self
6707            .forwarding
6708            .has_live_module_connection(&target_module_id)
6709            .map_err(RouterError::Forwarding)?
6710        {
6711            return Ok(vec![self.route_open_refusal_frame(
6712                ctx,
6713                &caller,
6714                &frame,
6715                &target_module_id,
6716                "no_forwarding_connection",
6717                "target_unavailable",
6718                format!("module_id '{target_module_id}' has no live forwarding connection"),
6719            )?]);
6720        }
6721
6722        if let Some(error) =
6723            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6724        {
6725            self.observe_route_open_refusal(
6726                ctx,
6727                &caller,
6728                &target_module_id,
6729                "op_not_allowed",
6730                "op_not_allowed",
6731            );
6732            return Ok(vec![error]);
6733        }
6734
6735        let principal = match (&attested, consumer_identity.is_some()) {
6736            // A claim-bound connection whose launch ended attests nothing,
6737            // and it must never fall back to opening as `direct`.
6738            (None, false) => {
6739                self.observe_route_open_refusal(
6740                    ctx,
6741                    &caller,
6742                    &target_module_id,
6743                    "registration_channel_closed",
6744                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6745                );
6746                return Ok(vec![control_error_frame(
6747                    &frame,
6748                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6749                    "the claim binding's launch has ended",
6750                )?]);
6751            }
6752            _ => match self.route_open_principal_attested(
6753                &frame,
6754                consumer_identity,
6755                attested.as_ref().map(|attested| attested.principal.clone()),
6756            )? {
6757                Ok(principal) => principal,
6758                Err(error) => {
6759                    self.observe_route_open_refusal(
6760                        ctx,
6761                        &caller,
6762                        &target_module_id,
6763                        "bad_consumer_identity",
6764                        "bad_consumer_identity",
6765                    );
6766                    return Ok(vec![error]);
6767                }
6768            },
6769        };
6770        let attested = attested.expect("an attested principal was resolved above");
6771        timings.principal = principal_label(&principal);
6772
6773        // The opener's spawn authority, read once here and carried with the
6774        // relay; nothing below reads its record again.
6775        let Ok(mut caller_capture) = attested.capture() else {
6776            self.observe_route_open_refusal(
6777                ctx,
6778                &caller,
6779                &target_module_id,
6780                "registration_channel_closed",
6781                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6782            );
6783            return Ok(vec![control_error_frame(
6784                &frame,
6785                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6786                "the opener's launch has ended",
6787            )?]);
6788        };
6789        // The caller-side checks below read the opener's own spawn: its
6790        // module from its record and its manifest from its own registration,
6791        // never another launch's active registration under the same id.
6792        let caller_module_id = match &attested.spawn {
6793            Some((record, _)) => Some(record.module_id().to_owned()),
6794            None => match &principal {
6795                Principal::Reserved { module_id } => Some(module_id.clone()),
6796                _ => None,
6797            },
6798        };
6799
6800        // Only Callosum can attest a production phone build. Consume the raw
6801        // claim here; opted-in targets receive only the honoured peer fact.
6802        let build_class = identity.build_class.take().filter(|build_class| {
6803            if caller_module_id.as_deref() == Some("callosum") {
6804                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6805            } else {
6806                if self
6807                    .build_class_warned
6808                    .lock()
6809                    .unwrap_or_else(|p| p.into_inner())
6810                    .insert(ctx.connection_id)
6811                {
6812                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6813                        "ignoring build_class from a non-Callosum opener");
6814                }
6815                false
6816            }
6817        });
6818
6819        // This is attested, control-plane policy for supervised module origins.
6820        // Keep it before route reservation and out of the opaque forwarding hot
6821        // path: data frames must never acquire a per-frame capability check.
6822        if let Some(opening_registration) = self.caller_registration(&attested, &admission_registry)
6823        {
6824            let opening_module_id = opening_registration.module_id.as_str();
6825            if let Some(capability) = denied_capability(
6826                opening_registration.capabilities.as_ref(),
6827                registration.capabilities.as_ref(),
6828            ) {
6829                warn!(
6830                    opening_module_id,
6831                    target_module_id,
6832                    capability,
6833                    "refusing route.open because an attested capability deny edge matches"
6834                );
6835                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6836                    &frame,
6837                    &target_module_id,
6838                    "capability_deny_edge",
6839                    "capability_forbidden",
6840                    format!(
6841                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
6842                    ),
6843                )?]);
6844            }
6845        }
6846
6847        if admission_facts.is_some() {
6848            let carrier_matches = caller_module_id.is_some()
6849                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
6850            if !carrier_matches {
6851                return Ok(vec![self.route_open_refusal_frame(
6852                    ctx,
6853                    &caller,
6854                    &frame,
6855                    &target_module_id,
6856                    "admission_facts_carrier_not_permitted",
6857                    "admission_facts_not_permitted",
6858                    "admission facts may only be carried by the configured reserved module",
6859                )?]);
6860            }
6861
6862            let target_allowed = self
6863                .admission_facts_targets
6864                .as_ref()
6865                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
6866            if !target_allowed {
6867                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6868                    &frame,
6869                    &target_module_id,
6870                    "admission_facts_target_not_listed",
6871                    "admission_facts_target_not_allowed",
6872                    format!(
6873                        "admission facts are not permitted for target module_id '{target_module_id}'"
6874                    ),
6875                )?]);
6876            }
6877
6878            // Keep the value opaque to subc. The downstream admission validator owns
6879            // schema and semantic checks; this daemon only enforces carrier authority
6880            // and the configured destination allowlist.
6881        }
6882
6883        // Scope admission, on the attested principal above and never on the
6884        // request body. The tag read here travels with the pending bind and is
6885        // compared with the published one at commit, so a sync between here
6886        // and the module's ack refuses the open instead of binding a stamp
6887        // that is no longer true.
6888        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
6889            None => (None, None, false),
6890            Some(selector) => {
6891                let owner_configured = match &selector.owner {
6892                    // A reserved owner counts as configured from before its
6893                    // process is spawned (see `SupervisorHandle::is_configured`).
6894                    // So an owner that has not synced its scopes yet is refused
6895                    // as retryable (`scope_not_synced`), not as one that will
6896                    // never sync.
6897                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
6898                    _ => false,
6899                };
6900                let mut scopes = self
6901                    .scopes
6902                    .write()
6903                    .unwrap_or_else(|poisoned| poisoned.into_inner());
6904                let admitted = crate::scopes::admission::admit_route(
6905                    &scopes,
6906                    &admission_registry,
6907                    &principal,
6908                    &target_module_id,
6909                    Some(selector),
6910                    owner_configured,
6911                    crate::scopes::admission::AdmissionMode::Open,
6912                )
6913                .map(|route| {
6914                    let admission = route.scope.expect("scoped admission");
6915                    let bound = scopes.reserve_bind(
6916                        &admission,
6917                        &principal,
6918                        ctx.connection_id,
6919                        selector.hold_presence,
6920                    );
6921                    (admission, bound)
6922                });
6923                match admitted {
6924                    Ok((admission, bound)) => {
6925                        (Some(bound), Some(admission.stamp), admission.stamp_required)
6926                    }
6927                    Err(refusal) => {
6928                        return Ok(vec![self.route_open_refusal_frame(
6929                            ctx,
6930                            &caller,
6931                            &frame,
6932                            &target_module_id,
6933                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6934                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6935                            refusal.message,
6936                        )?]);
6937                    }
6938                }
6939            }
6940        };
6941        // From here on a refusal names the scope by the stamp admission
6942        // issued, exactly as the `route.open accepted` line does.
6943        if let Some(stamp) = &scope_stamp {
6944            caller.scope = route_open_scope_label(stamp);
6945        }
6946        // Decided from the admitted stamp, before any field of it is stripped
6947        // for a target that lacks the capability to read it.
6948        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
6949            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
6950        }
6951
6952        // Allow resolvable missing-tail paths so a vanished directory does not
6953        // prevent reopening an existing session for cleanup. Binding does not
6954        // authorize creation of durable provider state.
6955        //
6956        // Resolve real paths rather than lexical cleanup: canonicalize the
6957        // longest existing ancestor and append the missing tail, retaining the
6958        // path's real existing ancestry even when a leaf is missing.
6959        timings.enter(RouteOpenPhase::ProjectRoot);
6960        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
6961            Ok(project) => project,
6962            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
6963        };
6964        timings.enter(RouteOpenPhase::Admission);
6965        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
6966            Ok(root) => root,
6967            Err(err) => {
6968                return Ok(vec![control_error_frame(
6969                    &frame,
6970                    "invalid_project_root",
6971                    err.to_string(),
6972                )?])
6973            }
6974        };
6975        // Compute compatibility project fields before stripping optional stamp
6976        // members. Preserve the canonical opener root and its project ID,
6977        // including absence. For rootless openers, use stamp workdir or `/`, and
6978        // opener ID, else stamp ID, else no ID. Emit these identity fields only
6979        // to targets without bind-no-project/v1.
6980        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
6981
6982        // Last gate before any relay work, and deliberately after the cheap
6983        // registry and availability checks above: those name a more precise
6984        // condition (unknown, removed, reloading) and a caller is better served
6985        // by the precise code than by this one.
6986        //
6987        // Everything below this point costs an egress permit, a reserved handle
6988        // pair and, if the module does not answer, the whole relay budget. The
6989        // reader no longer waits for that budget, so cap each target explicitly;
6990        // serial dispatch used to provide the accidental cap of one relay per
6991        // connection. Admission is a mutex-protected count and never waits.
6992        let _concurrency_guard = match self
6993            .route_bind_concurrency
6994            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
6995        {
6996            Ok(guard) => guard,
6997            Err(in_flight) => {
6998                return Ok(vec![self.route_open_target_capacity_refusal(
6999                    ctx,
7000                    &caller,
7001                    &frame,
7002                    &target_module_id,
7003                    in_flight,
7004                )?]);
7005            }
7006        };
7007
7008        // A module that has already burned the whole budget `threshold` times
7009        // in a row does not get to charge it again until a probe says it recovered.
7010        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
7011            RouteBindAdmission::Admitted { guard, probe } => {
7012                if probe {
7013                    info!(
7014                        module_id = %target_module_id,
7015                        connection_id = ctx.connection_id.get(),
7016                        "route.bind breaker half-open: admitting one probe"
7017                    );
7018                }
7019                guard
7020            }
7021            RouteBindAdmission::Refused {
7022                consecutive_timeouts,
7023                retry_in,
7024                probe_in_flight,
7025            } => {
7026                return Ok(vec![self.route_open_breaker_refusal_frame(
7027                    ctx,
7028                    &caller,
7029                    &frame,
7030                    &target_module_id,
7031                    consecutive_timeouts,
7032                    retry_in,
7033                    probe_in_flight,
7034                )?]);
7035            }
7036        };
7037
7038        let operator_app = self
7039            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
7040            .await;
7041        // Resolve the per-module budget here so the wait matches the operator's
7042        // intent for this specific target. A per-module override in
7043        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
7044        // daemons) wins over the daemon-wide default.
7045        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
7046        let relay_deadline = Instant::now() + route_bind_relay_timeout;
7047        let production_peer_build =
7048            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
7049        timings.enter(RouteOpenPhase::EgressReservation);
7050        let pending = match self
7051            .forwarding
7052            .begin_route_bind_relay_for(
7053                ctx.connection_id,
7054                ctx.egress.clone(),
7055                response_version(&frame),
7056                frame.header.corr,
7057                &target_module_id,
7058                principal.clone(),
7059                bound_scope,
7060                project_root,
7061                identity.harness.clone(),
7062                build_class,
7063                operator_app.clone(),
7064                crate::forwarding::RouteAuthority {
7065                    incarnation: self.supervisor.daemon_incarnation(),
7066                    caller: caller_capture
7067                        .as_ref()
7068                        .map(|caller| caller.authority.pair()),
7069                },
7070                relay_deadline,
7071                busy_refusals == Some(true),
7072                accepts_close_reasons,
7073            )
7074            .await
7075        {
7076            Ok(pending) => pending,
7077            Err(err) => {
7078                return Ok(vec![self.route_open_refusal_frame(
7079                    ctx,
7080                    &caller,
7081                    &frame,
7082                    &target_module_id,
7083                    "relay_reservation_failed",
7084                    forwarding_error_code(&err),
7085                    err.to_string(),
7086                )?])
7087            }
7088        };
7089        timings.enter(RouteOpenPhase::Admission);
7090        let crate::forwarding::PendingRouteBindRelay {
7091            endpoint,
7092            module_sink,
7093            negotiated_ver,
7094            client_channel,
7095            client_epoch,
7096            module_channel,
7097            module_epoch,
7098            corr: relay_corr,
7099            receiver,
7100        } = pending;
7101        let mut reservation =
7102            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
7103
7104        // Reserving egress can wait while a module reconnects or a swap cuts
7105        // over. Check the relay's captured connection, not the earlier by-id
7106        // lookup: the original module's flow/run capabilities cannot authorize
7107        // its replacement. The captured sink stays bound to that connection.
7108        let relay_registration = self
7109            .registry
7110            .route_registration_by_connection(endpoint.connection_id)
7111            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7112        let relay_capabilities = relay_registration
7113            .as_ref()
7114            .and_then(|registration| registration.capabilities.as_ref());
7115        if let Some(selector) = &scope {
7116            // Egress reservation may wait across a scope update. Recheck the
7117            // proof against the current record before sending the captured bind.
7118            if let Err(refusal) = self
7119                .scopes
7120                .read()
7121                .unwrap_or_else(|poisoned| poisoned.into_inner())
7122                .check_bind_proof(&principal, selector)
7123            {
7124                reservation.release_and_disarm();
7125                return Ok(vec![self.route_open_refusal_frame(
7126                    ctx,
7127                    &caller,
7128                    &frame,
7129                    &target_module_id,
7130                    refusal.code,
7131                    refusal.code,
7132                    refusal.message,
7133                )?]);
7134            }
7135        }
7136        if let Some(stamp) = scope_stamp.as_ref() {
7137            if let Err(refusal) = crate::scopes::check_target_required_stamp(
7138                stamp_required,
7139                &target_module_id,
7140                relay_capabilities,
7141            )
7142            .and_then(|()| {
7143                crate::scopes::check_target_flow_support(
7144                    stamp,
7145                    &target_module_id,
7146                    relay_capabilities,
7147                )
7148            })
7149            .and_then(|()| {
7150                crate::scopes::check_target_agent_run_support(
7151                    stamp,
7152                    &target_module_id,
7153                    relay_capabilities,
7154                )
7155            }) {
7156                reservation.release_and_disarm();
7157                return Ok(vec![self.route_open_refusal_frame(
7158                    ctx,
7159                    &caller,
7160                    &frame,
7161                    &target_module_id,
7162                    refusal.code,
7163                    refusal.code,
7164                    refusal.message,
7165                )?]);
7166            }
7167        }
7168
7169        // Older readers may reject unknown fields. Select optional fields from
7170        // the captured endpoint's declaration, including on unscoped binds.
7171        if scope_stamp
7172            .as_ref()
7173            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7174            && !crate::scopes::target_supports_federated(relay_capabilities)
7175        {
7176            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7177            scope_stamp = None;
7178        }
7179        if !relay_capabilities.is_some_and(|caps| {
7180            caps.provides
7181                .iter()
7182                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7183        }) {
7184            if let Some(stamp) = scope_stamp.as_mut() {
7185                stamp.workdir = None;
7186                stamp.project_id = None;
7187            }
7188        }
7189        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7190        // attribution. The run gate above has already required the target to
7191        // declare `worker-runs/v1`, which promises to read both
7192        // `on_behalf_of_agent` and `call_mode`.
7193        let worker_run = scope_stamp
7194            .as_ref()
7195            .is_some_and(crate::scopes::is_worker_run)
7196            && relay_capabilities.is_some_and(|caps| {
7197                caps.provides
7198                    .iter()
7199                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7200            });
7201        if !worker_run
7202            && !relay_capabilities.is_some_and(|caps| {
7203                caps.provides
7204                    .iter()
7205                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7206            })
7207        {
7208            if let Some(stamp) = scope_stamp.as_mut() {
7209                stamp.attributes.on_behalf_of_agent = None;
7210            }
7211        }
7212        if !relay_capabilities.is_some_and(|caps| {
7213            caps.provides
7214                .iter()
7215                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7216        }) {
7217            if let Some(stamp) = scope_stamp.as_mut() {
7218                stamp.attributes.flow_version = None;
7219                stamp.attributes.flow_code_hash = None;
7220                stamp.attributes.flow_install_id = None;
7221            }
7222        }
7223        let call_mode = if worker_run
7224            || relay_capabilities
7225                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7226        {
7227            Some(derive_call_mode(scope_stamp.as_ref()))
7228        } else {
7229            if let Some(stamp) = scope_stamp.as_mut() {
7230                stamp.expires_at_ms = None;
7231            }
7232            None
7233        };
7234
7235        debug!(
7236            connection_id = ctx.connection_id.get(),
7237            client_channel,
7238            client_epoch,
7239            module_channel,
7240            module_epoch,
7241            "reserved route handle pair"
7242        );
7243        // Rendered BEFORE the move into the relay, because the accept arm below
7244        // is where it is logged and the principal is gone by then.
7245        let route_principal_label = principal_label(&principal);
7246        let relay = ModuleControlRequest::RouteBind {
7247            route_channel: module_channel,
7248            epoch: module_epoch,
7249            target,
7250            identity,
7251            principal: Some(principal),
7252            consumer_capabilities,
7253            role_versions,
7254            admission_facts,
7255            scope: scope_stamp,
7256            call_mode,
7257        };
7258        let peer = RouteBindPeer::new()
7259            .with_observed_peer(
7260                relay_capabilities
7261                    .is_some_and(|caps| {
7262                        caps.provides
7263                            .iter()
7264                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7265                    })
7266                    .then(|| {
7267                        self.observed_peers
7268                            .lock()
7269                            .unwrap_or_else(|p| p.into_inner())
7270                            .get(&ctx.connection_id)
7271                            .cloned()
7272                            .unwrap_or_else(ObservedPeer::unobserved)
7273                    }),
7274            )
7275            .with_operator_app(
7276                self.connection_operator_app(operator_app.as_ref())
7277                    .filter(|_| {
7278                        relay_capabilities.is_some_and(|caps| {
7279                            caps.provides
7280                                .iter()
7281                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7282                        })
7283                    }),
7284            )
7285            .with_caller(caller_for_target(
7286                caller_capture.as_ref(),
7287                relay_capabilities,
7288                &target_module_id,
7289            ))
7290            .with_peer_build(
7291                (production_peer_build
7292                    && relay_capabilities.is_some_and(|caps| {
7293                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7294                    }))
7295                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7296            );
7297        let relay_body = crate::bind_compat::encode_bind(
7298            &relay,
7299            &peer,
7300            &legacy_bind_project,
7301            relay_capabilities,
7302        )
7303        .map_err(|err| {
7304            RouterError::backend(
7305                0,
7306                frame.header.corr,
7307                format!("failed to encode route.bind request: {err}"),
7308            )
7309        })?;
7310        let relay_frame = Frame::build_with_version(
7311            negotiated_ver,
7312            FrameType::Request,
7313            control_flags(),
7314            0,
7315            0,
7316            relay_corr,
7317            relay_body,
7318        )
7319        .map_err(RouterError::FrameBuild)?;
7320
7321        timings.enter(RouteOpenPhase::BindSend);
7322        let sent = module_sink.send(relay_frame).await;
7323        timings.enter(RouteOpenPhase::Admission);
7324        if let Err(err) = sent {
7325            reservation.release_and_disarm();
7326            return Ok(vec![self.route_open_refusal_frame(
7327                ctx,
7328                &caller,
7329                &frame,
7330                &target_module_id,
7331                "relay_send_failed",
7332                "target_unavailable",
7333                err.to_string(),
7334            )?]);
7335        }
7336
7337        #[cfg(test)]
7338        if let Some(hold) = &self.route_bind_relay_sent_hold {
7339            // First wait: tell the test the bind is queued. Second wait: stay
7340            // here until the test has driven whatever it wants to happen
7341            // between queueing the bind and marking it enqueued.
7342            hold.wait().await;
7343            hold.wait().await;
7344        }
7345
7346        // A missing relay is not by itself an abandoned bind: the module may
7347        // already have acked it and the route may be committed. Only a relay
7348        // dropped without any module reply needs this GOODBYE; one a reply
7349        // settled has already had its GOODBYE decided by the reply path.
7350        if self
7351            .forwarding
7352            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7353            .map_err(RouterError::Forwarding)?
7354            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7355        {
7356            self.send_abandoned_route_bind_goodbye(
7357                &module_sink,
7358                negotiated_ver,
7359                module_channel,
7360                module_epoch,
7361            );
7362        }
7363
7364        timings.enter(RouteOpenPhase::BindAckWait);
7365        let outcome = timeout_at(relay_deadline, receiver).await;
7366        timings.enter(RouteOpenPhase::Admission);
7367        match outcome {
7368            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7369                reservation.disarm();
7370                if breaker.record_accepted() {
7371                    info!(
7372                        module_id = %target_module_id,
7373                        "route.bind breaker closed: the probe was accepted"
7374                    );
7375                }
7376                self.observe_route_open_accept(
7377                    ctx,
7378                    &target_module_id,
7379                    &route_principal_label,
7380                    &caller.scope,
7381                );
7382                Ok(Vec::new())
7383            }
7384            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7385                reservation.release_and_disarm();
7386                // A module that says no in microseconds is healthy. Rejection
7387                // is a different condition with its own refusal and must not
7388                // move the breaker.
7389                breaker.record_inconclusive();
7390                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7391            }
7392            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7393                reservation.release_and_disarm();
7394                breaker.record_inconclusive();
7395                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7396            }
7397            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7398                reservation.release_and_disarm();
7399                breaker.record_inconclusive();
7400                // Fires when the module's connection closes while a relayed
7401                // bind is pending -- typically a caller racing a module restart
7402                // whose bind was relayed BEFORE the drain mark went up. Logged
7403                // because the caller sees only its own error and the fleet has
7404                // already spent one diagnosis round unable to tell this arm
7405                // from a relay timeout without daemon-side evidence.
7406                tracing::warn!(
7407                    module_id = %target_module_id,
7408                    "route.bind relay abandoned: {message}"
7409                );
7410                Ok(vec![self.route_open_refusal_frame(
7411                    ctx,
7412                    &caller,
7413                    &frame,
7414                    &target_module_id,
7415                    "relay_abandoned",
7416                    "target_unavailable",
7417                    message,
7418                )?])
7419            }
7420            Ok(Err(_)) => {
7421                reservation.release_and_disarm();
7422                breaker.record_inconclusive();
7423                Ok(vec![self.route_open_refusal_frame(
7424                    ctx,
7425                    &caller,
7426                    &frame,
7427                    &target_module_id,
7428                    "relay_waiter_canceled",
7429                    "target_unavailable",
7430                    "route.bind relay waiter was canceled before the module responded",
7431                )?])
7432            }
7433            Err(_) => {
7434                reservation.release_and_disarm();
7435                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7436                // answer at all is the one condition a fast refusal can
7437                // usefully stand in for; every other arm already answered.
7438                if let Some(opened) = breaker.record_timeout(
7439                    self.route_bind_breaker_threshold,
7440                    self.route_bind_breaker_cooldown,
7441                ) {
7442                    warn!(
7443                        module_id = %target_module_id,
7444                        consecutive_timeouts = opened.consecutive_timeouts,
7445                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7446                        reopened_after_probe = opened.reopened_after_probe,
7447                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7448                    );
7449                }
7450                // The generous budget just burned to no answer: the module is
7451                // registered and its connection is up, but its bind handler sat
7452                // on the ack for the full budget (warm-on-bind, cold configure,
7453                // or a wedged handler). Every earlier unavailability shape
7454                // fast-refuses BEFORE the relay, so this arm firing means the
7455                // slowness is module-side -- log it so the per-module timeline
7456                // is reconstructable without client audit rows.
7457                tracing::warn!(
7458                    module_id = %target_module_id,
7459                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7460                    "route.bind relay timed out: module did not ack within budget"
7461                );
7462                Ok(vec![self.route_open_refusal_frame(
7463                    ctx,
7464                    &caller,
7465                    &frame,
7466                    &target_module_id,
7467                    "relay_timed_out",
7468                    "module_timeout",
7469                    format!(
7470                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7471                        route_bind_relay_timeout
7472                    ),
7473                )?])
7474            }
7475        }
7476    }
7477
7478    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7479        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7480            snapshot: self.supervisor.spawn_snapshot(),
7481        };
7482        Ok(vec![control_response_body_frame(
7483            &frame,
7484            &response,
7485            "ClientControlResponse::SupervisorSpawnSnapshot",
7486        )?])
7487    }
7488
7489    fn handle_supervisor_spawn_subscribe(
7490        &self,
7491        ctx: &RouteCtx,
7492        frame: Frame,
7493        since: Option<SpawnCursor>,
7494    ) -> Result<Vec<Frame>, RouterError> {
7495        match self.supervisor.subscribe_spawns(
7496            ctx.connection_id,
7497            frame.header.corr,
7498            response_version(&frame),
7499            since,
7500            ctx.egress.clone(),
7501        ) {
7502            Ok(()) => Ok(Vec::new()),
7503            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7504                Ok(vec![control_error_body_frame(
7505                    &frame,
7506                    ErrorBody {
7507                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7508                        message: "spawn cursor belongs to a different daemon incarnation"
7509                            .to_string(),
7510                        detail: Some(serde_json::json!({
7511                            "current_daemon_incarnation": current
7512                        })),
7513                    },
7514                )?])
7515            }
7516            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7517                &frame,
7518                ErrorBody {
7519                    code: "spawn_cursor_too_old".to_string(),
7520                    message: "spawn cursor predates the retained event ring".to_string(),
7521                    detail: Some(serde_json::json!({
7522                        "oldest_retained_cursor": oldest
7523                    })),
7524                },
7525            )?]),
7526            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7527                0,
7528                frame.header.corr,
7529                format!("failed to open supervisor spawn subscription: {error}"),
7530            )),
7531        }
7532    }
7533
7534    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7535        // Status/configuration snapshots may wait on synchronous supervisor
7536        // locks. Keep that work off the connection's async runtime thread.
7537        let handler = self.clone();
7538        let runtime = tokio::runtime::Handle::current();
7539        // The blocking pool does not inherit the control request's tracing
7540        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7541        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7542        let corr = frame.header.corr;
7543        tokio::task::spawn_blocking(move || {
7544            runtime.block_on(
7545                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7546                    .with_subscriber(subscriber),
7547            )
7548        })
7549        .await
7550        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7551    }
7552
7553    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7554        use crate::config_gate::runtime::ApprovedDaemonView;
7555        let publication = self
7556            .config_runtime
7557            .as_ref()
7558            .and_then(|owner| owner.polled_snapshot().ok());
7559        let approved = publication
7560            .as_ref()
7561            .map(|view| view.approved_daemon.clone())
7562            .unwrap_or_else(|| {
7563                if self.config_runtime.is_some() {
7564                    ApprovedDaemonView::Unavailable
7565                } else {
7566                    ApprovedDaemonView::NotStamped
7567                }
7568            });
7569        let generation = self
7570            .registry
7571            .generation()
7572            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7573        let supervised = self.supervisor.list();
7574        let mut statuses = BTreeMap::new();
7575        let mut not_running = BTreeSet::new();
7576        for module in &supervised {
7577            let status = module.status_for_control("list").map_err(|err| {
7578                RouterError::backend(
7579                    0,
7580                    frame.header.corr,
7581                    format!("failed to read supervisor status: {err}"),
7582                )
7583            })?;
7584            if !status.enabled || !status.process_alive {
7585                not_running.insert(module.module_id().to_owned());
7586            }
7587            statuses.insert(module.module_id().to_owned(), status);
7588        }
7589        // Legacy per-process diagnostics keep their shared optional budget.
7590        // The cached tree and accounting export below does not spend it.
7591        let mut process_resources = BTreeMap::new();
7592        for module in &supervised {
7593            process_resources.insert(
7594                module.module_id().to_owned(),
7595                crate::subtree_resources::read_process(module.clone()).await,
7596            );
7597        }
7598        // Image evidence uses the same optional deadline, but an exhausted
7599        // budget must not suppress the committed resource view.
7600        let mut image_readings = BTreeMap::new();
7601        for module in &supervised {
7602            image_readings.insert(
7603                module.module_id().to_owned(),
7604                module.running_image_agreement().await,
7605            );
7606        }
7607        let readings = self.resource_tracker.list(supervised.clone());
7608        let mut modules = Vec::new();
7609        for module in supervised {
7610            let status = statuses
7611                .remove(module.module_id())
7612                .expect("each supervised module has a status snapshot");
7613            let (configured, _) = module.configuration().map_err(|err| {
7614                RouterError::backend(
7615                    0,
7616                    frame.header.corr,
7617                    format!("failed to read module configuration: {err}"),
7618                )
7619            })?;
7620            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7621                RouterError::backend(
7622                    0,
7623                    frame.header.corr,
7624                    format!("failed to read retry time: {err}"),
7625                )
7626            })?;
7627            let image = image_readings
7628                .remove(module.module_id())
7629                .expect("each supervised module has an image snapshot");
7630            let resources = process_resources.remove(module.module_id());
7631            let mut verdict =
7632                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7633            verdict.spec = Some(launch_spec_agreement(
7634                &configured,
7635                status.process_alive,
7636                status.launch_spec_digest.as_ref(),
7637            ));
7638            let pending_reload = Some(verdict);
7639            let pending_entry = match &approved {
7640                ApprovedDaemonView::Approved { config, .. } => config
7641                    .modules
7642                    .iter()
7643                    .find(|m| m.module_id == module.module_id()),
7644                _ => None,
7645            };
7646            let pending = self
7647                .pending_module_fields(
7648                    &module,
7649                    pending_entry,
7650                    false,
7651                    Self::registration_channel_in_force(
7652                        publication
7653                            .as_ref()
7654                            .and_then(|view| view.registration_declaration(module.module_id()))
7655                            .as_deref(),
7656                        pending_entry.map(|entry| entry.registration_channel),
7657                    ),
7658                )
7659                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7660            let script = configured.script.as_ref().map(|entry| {
7661                let approved = self
7662                    .config_runtime
7663                    .as_ref()
7664                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7665                crate::supervise::script::status(entry, approved.as_ref())
7666            });
7667            let configured_enabled = match &approved {
7668                ApprovedDaemonView::Approved {
7669                    config: approved, ..
7670                } => approved
7671                    .modules
7672                    .iter()
7673                    .find(|module| module.module_id == status.module_id)
7674                    .map(|module| module.enabled),
7675                ApprovedDaemonView::NotStamped => self
7676                    .capability_evaluator
7677                    .configured_enabled(&status.module_id),
7678                ApprovedDaemonView::Unavailable => None,
7679            };
7680            let admission_refused = status
7681                .admission_refused
7682                .clone()
7683                .filter(|_| status.enabled && !status.process_alive)
7684                .filter(|_| {
7685                    publication
7686                        .as_ref()
7687                        .and_then(|view| view.registration_declaration(&status.module_id))
7688                        .as_deref()
7689                        == Some("undeclared")
7690                });
7691            // Keep the retired policy field on the wire for one release so
7692            // existing status consumers still receive the platform policy.
7693            let mut entry = SupervisorEntry::new(
7694                status.module_id,
7695                status.state.to_string(),
7696                status.enabled,
7697                status.live,
7698                status.health.status,
7699            )
7700            .with_configured_enabled(configured_enabled)
7701            .with_script(script)
7702            .with_admission_refused(admission_refused)
7703            .with_next_retry_at_ms(next_retry_at_ms)
7704            .with_launch_nonce_env(Some(!cfg!(unix)))
7705            .with_launch_nonce_source(status.launch_nonce_source)
7706            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7707            .with_protocol(status.protocol)
7708            .with_pending_reload(pending_reload)
7709            .with_last_probe_ms(status.health.last_probe_ms)
7710            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7711            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7712            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7713            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7714            .with_restart_count(Some(status.restart_count))
7715            .with_max_restarts(Some(status.max_restarts))
7716            .with_lifetime_restarts(Some(status.lifetime_restarts))
7717            .with_spawn_generation(Some(status.spawn_generation))
7718            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7719            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7720            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7721            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7722            .with_resources(resources);
7723            entry.pending = pending;
7724            modules.push(entry);
7725        }
7726        for module in &mut modules {
7727            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7728                module.tree = tree.clone();
7729                module.cpu_last_hour = hour.clone();
7730            }
7731            module.tree_unavailable = readings
7732                .reasons
7733                .get(&module.module_id)
7734                .map(|reason| (*reason).to_owned());
7735            if module.tree.is_none() {
7736                module.tree_unavailable = Some(
7737                    if not_running.contains(&module.module_id) {
7738                        "not_running"
7739                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7740                        reason
7741                    } else {
7742                        "not_yet_measured"
7743                    }
7744                    .to_owned(),
7745                );
7746            }
7747        }
7748        let response = ClientControlResponse::SupervisorList {
7749            generation,
7750            modules,
7751            daemon: readings.daemon,
7752            agent_commands: readings.agent_commands,
7753        };
7754        Ok(vec![control_response_body_frame(
7755            &frame,
7756            &response,
7757            "ClientControlResponse::SupervisorList",
7758        )?])
7759    }
7760
7761    fn handle_supervisor_stderr_tail(
7762        &self,
7763        frame: Frame,
7764        module_id: String,
7765        max_lines: Option<u32>,
7766        max_bytes: Option<u32>,
7767    ) -> Result<Vec<Frame>, RouterError> {
7768        let Some(module) = self.supervisor.get(&module_id) else {
7769            return Ok(vec![control_error_frame(
7770                &frame,
7771                "unknown_module",
7772                format!("module_id '{module_id}' is not supervised"),
7773            )?]);
7774        };
7775
7776        let snapshot = module.stderr_tail(
7777            max_lines.map(|value| value as usize),
7778            max_bytes.map(|value| value as usize),
7779        );
7780
7781        let response = ClientControlResponse::SupervisorStderrTail {
7782            module_id,
7783            tail: StderrTail {
7784                capture: match snapshot.capture {
7785                    CaptureState::Captured => StderrCaptureState::Captured,
7786                    CaptureState::Incomplete { reason } => {
7787                        StderrCaptureState::Incomplete { reason }
7788                    }
7789                    CaptureState::NotCaptured { reason } => {
7790                        StderrCaptureState::NotCaptured { reason }
7791                    }
7792                },
7793                entries: snapshot
7794                    .entries
7795                    .into_iter()
7796                    .map(|entry| match entry {
7797                        TailEntry::Line {
7798                            text,
7799                            truncated,
7800                            at_ms,
7801                        } => StderrTailEntry::Line {
7802                            text,
7803                            truncated,
7804                            at_ms,
7805                        },
7806                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7807                    })
7808                    .collect(),
7809                dropped_lines: snapshot.dropped_lines,
7810            },
7811        };
7812        Ok(vec![control_response_body_frame(
7813            &frame,
7814            &response,
7815            "ClientControlResponse::SupervisorStderrTail",
7816        )?])
7817    }
7818
7819    async fn observe_control_wait<F: std::future::Future>(
7820        &self,
7821        ctx: &RouteCtx,
7822        target: Option<&str>,
7823        kind: &'static str,
7824        future: F,
7825    ) -> F::Output {
7826        self.counters
7827            .observe_reader_wait(
7828                || {
7829                    let module = self
7830                        .forwarding
7831                        .module_id_for_connection(ctx.connection_id)
7832                        .ok()
7833                        .flatten();
7834                    let principal = if module.is_some() { "module" } else { "direct" };
7835                    (
7836                        self.resolve_reader_wait_target(kind, target)
7837                            .or(module)
7838                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7839                        principal.into(),
7840                    )
7841                },
7842                kind,
7843                future,
7844            )
7845            .await
7846    }
7847
7848    /// Resolve the reader-wait module ID only from supervisor or registry
7849    /// records; never attribute a wait from the request selector alone.
7850    pub(crate) fn resolve_reader_wait_target(
7851        &self,
7852        op: &str,
7853        selector: Option<&str>,
7854    ) -> Option<String> {
7855        let selector = selector?;
7856        match op {
7857            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7858                .supervisor
7859                .get(selector)
7860                .map(|module| module.module_id().to_owned()),
7861            ops::SUPERVISOR_HEALTH_PROBE => self
7862                .registry
7863                .get_module(selector)
7864                .ok()
7865                .flatten()
7866                .map(|registration| registration.manifest.module_id),
7867            _ => None,
7868        }
7869    }
7870
7871    async fn handle_supervisor_terminals(
7872        &self,
7873        ctx: &RouteCtx,
7874        frame: Frame,
7875        module_id: String,
7876    ) -> Result<Vec<Frame>, RouterError> {
7877        let Some(module) = self.supervisor.get(&module_id) else {
7878            return Ok(vec![control_error_frame(
7879                &frame,
7880                "unknown_module",
7881                format!("module_id '{module_id}' is not supervised"),
7882            )?]);
7883        };
7884
7885        // The journal read runs on a blocking thread: it can be megabytes of
7886        // file I/O and must not occupy a runtime worker.
7887        let terminals = self
7888            .observe_control_wait(
7889                ctx,
7890                Some(module.module_id()),
7891                ops::SUPERVISOR_TERMINALS,
7892                module.read_durable_terminal_history(),
7893            )
7894            .await
7895            .map_err(|error| {
7896                RouterError::backend(
7897                    0,
7898                    frame.header.corr,
7899                    format!("failed to read terminal history: {error}"),
7900                )
7901            })?;
7902        let response = ClientControlResponse::SupervisorTerminals {
7903            module_id,
7904            terminals,
7905        };
7906        Ok(vec![control_response_body_frame(
7907            &frame,
7908            &response,
7909            "ClientControlResponse::SupervisorTerminals",
7910        )?])
7911    }
7912
7913    fn handle_supervisor_routes(
7914        &self,
7915        frame: Frame,
7916        module_id: Option<String>,
7917    ) -> Result<Vec<Frame>, RouterError> {
7918        let modules = self
7919            .forwarding
7920            .route_census(module_id.as_deref())
7921            .map_err(RouterError::Forwarding)?
7922            .into_iter()
7923            .map(|(module_id, routes)| SupervisorRouteModule {
7924                module_id,
7925                routes: routes
7926                    .into_iter()
7927                    .map(|route| SupervisorRoute {
7928                        consumer: match route.principal {
7929                            Principal::Reserved { module_id } => {
7930                                SupervisorRouteConsumer::Reserved { module_id }
7931                            }
7932                            Principal::Direct | Principal::Unverified => {
7933                                SupervisorRouteConsumer::Direct {
7934                                    connection_id: route.goodbye_target.connection_id.get(),
7935                                }
7936                            }
7937                        },
7938                        age_ms: Instant::now()
7939                            .saturating_duration_since(route.bound_at)
7940                            .as_millis()
7941                            .try_into()
7942                            .unwrap_or(u64::MAX),
7943                        draining: route.draining,
7944                        drain_reason: route.drain_reason,
7945                    })
7946                    .collect(),
7947            })
7948            .collect();
7949        let response = ClientControlResponse::SupervisorRoutes { modules };
7950        Ok(vec![control_response_body_frame(
7951            &frame,
7952            &response,
7953            "ClientControlResponse::SupervisorRoutes",
7954        )?])
7955    }
7956
7957    fn running_registration_method(
7958        &self,
7959        module: &str,
7960    ) -> Option<subc_control::RegistrationMethod> {
7961        let registration = self.registry.get_module(module).ok()??;
7962        let connection = registration.connection_id;
7963        let channel = self.supervisor.registration_spawn(connection).is_some();
7964        let nonce = if channel {
7965            None
7966        } else {
7967            self.hello_launch_nonces
7968                .lock()
7969                .ok()?
7970                .nonce(connection)
7971                .map(str::to_owned)
7972        };
7973        if !channel && nonce.is_none() {
7974            return None;
7975        }
7976        self.supervisor
7977            .registration_snapshot_is_current_live(
7978                &self.registry,
7979                module,
7980                connection,
7981                nonce.as_deref(),
7982            )
7983            .then_some(if channel {
7984                subc_control::RegistrationMethod::Channel
7985            } else {
7986                subc_control::RegistrationMethod::Nonce
7987            })
7988    }
7989
7990    async fn handle_supervisor_provenance(
7991        &self,
7992        ctx: &RouteCtx,
7993        frame: Frame,
7994        module_id: Option<String>,
7995    ) -> Result<Vec<Frame>, RouterError> {
7996        let targeted = module_id.is_some();
7997        let selected = if let Some(module_id) = module_id {
7998            let Some(module) = self.supervisor.get(&module_id) else {
7999                return Ok(vec![control_error_frame(
8000                    &frame,
8001                    "unknown_module",
8002                    format!("module_id '{module_id}' is not supervised"),
8003                )?]);
8004            };
8005            vec![module]
8006        } else {
8007            self.supervisor.list()
8008        };
8009
8010        let target = targeted.then(|| selected[0].module_id());
8011        let declarations = if let Some(owner) = &self.config_runtime {
8012            owner
8013                .on_blocking(|owner| owner.registration_declarations())
8014                .await
8015                .ok()
8016        } else {
8017            None
8018        };
8019        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
8020            let mut modules = Vec::with_capacity(selected.len());
8021            let mut extensions = Vec::with_capacity(selected.len());
8022            for module in &selected {
8023                let (status, observed_image) = module
8024                    .status_and_running_image_agreement()
8025                    .await
8026                    .map_err(|err| {
8027                        RouterError::backend(
8028                            0,
8029                            frame.header.corr,
8030                            format!("failed to read supervisor status: {err}"),
8031                        )
8032                    })?;
8033                let module_declared = self
8034                    .registry
8035                    .get_module(&status.module_id)
8036                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8037                    .and_then(|registration| registration.manifest.provenance)
8038                    .map(|build| ModuleDeclaredProvenance::Reported { build })
8039                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
8040                #[cfg(test)]
8041                let running_image = match &self.provenance_probe_override {
8042                    Some(result) => result.clone(),
8043                    None => observed_image,
8044                };
8045                #[cfg(not(test))]
8046                let running_image = observed_image;
8047                let registration = self.running_registration_method(&status.module_id);
8048                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
8049                    .with_registration(registration);
8050                extension.registration_declaration = declarations
8051                    .as_ref()
8052                    .and_then(|entries| entries.get(&status.module_id))
8053                    .cloned();
8054                if status.process_alive && status.registration_declaration.is_some() {
8055                    extension.registration_declaration = status.registration_declaration.clone();
8056                }
8057                extensions.push(extension);
8058                modules.push(SupervisorModuleProvenance {
8059                    module_id: status.module_id,
8060                    module_declared,
8061                    daemon_observed: SupervisorObservedProcess {
8062                        launch_nonce_source: status.launch_nonce_source,
8063                        pid: status.pid,
8064                        spawned_at_ms: status.spawned_at_ms,
8065                        spawned_from: status.spawned_from,
8066                        running_image,
8067                    },
8068                });
8069            }
8070            let daemon = SupervisorDaemonProvenance {
8071                daemon_build: self.daemon_provenance.build.clone(),
8072                daemon_observed: DaemonObservedProcess {
8073                    pid: self.daemon_provenance.pid,
8074                    started_at_ms: self
8075                        .daemon_provenance
8076                        .start_clock
8077                        .map(|clock| clock.started_at_ms())
8078                        .or(self.daemon_provenance.started_at_ms),
8079                    running_image: self
8080                        .daemon_provenance
8081                        .probe
8082                        .observe(
8083                            self.daemon_provenance.pid,
8084                            self.daemon_provenance.executable_path.as_deref(),
8085                            self.daemon_provenance.executable_identity.clone(),
8086                            self.daemon_provenance.process_start_time,
8087                        )
8088                        .await,
8089                },
8090            };
8091            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
8092            let mut response = serde_json::to_value(response)
8093                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
8094            for (entry, extension) in response["modules"]
8095                .as_array_mut()
8096                .expect("provenance modules are an array")
8097                .iter_mut()
8098                .zip(extensions)
8099            {
8100                extension.write_to(entry).map_err(|error| {
8101                    RouterError::backend(0, frame.header.corr, error.to_string())
8102                })?;
8103            }
8104            Ok(vec![control_response_body_frame(
8105                &frame,
8106                &response,
8107                "ClientControlResponse::SupervisorProvenance",
8108            )?])
8109        })
8110        .await
8111    }
8112
8113    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
8114        self.refresh_capability_requirements();
8115        let publication = self
8116            .config_runtime
8117            .as_ref()
8118            .and_then(|owner| owner.polled_snapshot().ok());
8119        let generation = self
8120            .registry
8121            .generation()
8122            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
8123        let modules = self
8124            .supervisor
8125            .list()
8126            .into_iter()
8127            .map(|module| {
8128                let status = module.status_for_control("health").map_err(|err| {
8129                    RouterError::backend(
8130                        0,
8131                        frame.header.corr,
8132                        format!("failed to read supervisor health: {err}"),
8133                    )
8134                })?;
8135                let module_id = status.module_id;
8136                let capability_detail = self
8137                    .capability_evaluator
8138                    .required_problem_detail(&module_id);
8139                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8140                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8141                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8142                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8143                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8144                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8145                Ok(SupervisorHealthEntry {
8146                    module_id,
8147                    status: status.health.status,
8148                    detail: append_capability_problem_detail(
8149                        status.health.detail,
8150                        capability_detail,
8151                    ),
8152                    metrics: status.health.metrics,
8153                    consecutive_failures: status.health.consecutive_failures,
8154                    late_answer_count: status.health.late_answer_count,
8155                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8156                    last_action: status.health.last_action,
8157                    last_action_ms: status.health.last_action_ms,
8158                    last_probe_ms: status.health.last_probe_ms,
8159                })
8160            })
8161            .collect::<Result<Vec<_>, RouterError>>()?;
8162        let response = ClientControlResponse::SupervisorHealth {
8163            generation,
8164            modules,
8165        };
8166        Ok(vec![control_response_body_frame(
8167            &frame,
8168            &response,
8169            "ClientControlResponse::SupervisorHealth",
8170        )?])
8171    }
8172
8173    async fn handle_supervisor_restart(
8174        &self,
8175        frame: Frame,
8176        module_id: String,
8177        drain_timeout_ms: Option<u64>,
8178        requester: Principal,
8179    ) -> Result<Vec<Frame>, RouterError> {
8180        let operation_lock = self.supervisor.operation_lock();
8181        let _operation_guard = operation_lock.lock().await;
8182        let Some(module) = self.supervisor.get(&module_id) else {
8183            return Ok(vec![control_error_frame(
8184                &frame,
8185                "unknown_module",
8186                format!("module_id '{module_id}' is not supervised"),
8187            )?]);
8188        };
8189
8190        self.route_outages.mark_operator_action(&module_id);
8191        if let Err(err) = module
8192            .restart_requested(drain_timeout_ms, Some(requester))
8193            .await
8194        {
8195            self.route_outages
8196                .operator_action_ended_unrefused(&module_id);
8197            let (code, message) = match err {
8198                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8199                crate::supervise::SuperviseError::Disabled { .. } => {
8200                    ("module_disabled", err.to_string())
8201                }
8202                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8203                    ("swap_in_progress", err.to_string())
8204                }
8205                _ => (
8206                    "target_unavailable",
8207                    format!("failed to restart module_id '{module_id}': {err}"),
8208                ),
8209            };
8210            return Ok(vec![control_error_frame(&frame, code, message)?]);
8211        }
8212
8213        let response = ClientControlResponse::SupervisorAck {
8214            module_id,
8215            applied: true,
8216        };
8217        Ok(vec![control_response_body_frame(
8218            &frame,
8219            &response,
8220            "ClientControlResponse::SupervisorAck",
8221        )?])
8222    }
8223
8224    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8225    /// when the old process has finished draining: a caller whose own lane
8226    /// rides the old process must get its reply before that drain waits on it.
8227    async fn handle_supervisor_swap(
8228        &self,
8229        frame: Frame,
8230        module_id: String,
8231        ready_timeout_ms: Option<u64>,
8232        requester: Principal,
8233    ) -> Result<Vec<Frame>, RouterError> {
8234        // The daemon-wide operation lock is held only to resolve the handle,
8235        // not across the swap. The swap can take its whole readiness budget,
8236        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8237        // holding it here would park an operator's stop behind the swap it is
8238        // meant to abort. A rescan or stop that reaches the module during the
8239        // swap is served by the swap itself (see `supervise_swap`).
8240        let module = {
8241            let operation_lock = self.supervisor.operation_lock();
8242            let _operation_guard = operation_lock.lock().await;
8243            self.supervisor.get(&module_id)
8244        };
8245        let Some(module) = module else {
8246            return Ok(vec![control_error_frame(
8247                &frame,
8248                "unknown_module",
8249                format!("module_id '{module_id}' is not supervised"),
8250            )?]);
8251        };
8252
8253        self.route_outages.mark_operator_action(&module_id);
8254        if let Err(err) = module
8255            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8256            .await
8257        {
8258            self.route_outages
8259                .operator_action_ended_unrefused(&module_id);
8260            use crate::supervise::SuperviseError;
8261            let message = err.to_string();
8262            let error = match err {
8263                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8264                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8265                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8266                    code: "swap_refused".to_string(),
8267                    message,
8268                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8269                },
8270                SuperviseError::SwapFailed {
8271                    arm,
8272                    candidate_exit,
8273                    ..
8274                } => ErrorBody {
8275                    code: "swap_failed".to_string(),
8276                    message,
8277                    detail: Some(serde_json::json!({
8278                        "arm": arm.as_str(),
8279                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8280                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8281                    })),
8282                },
8283                _ => ErrorBody::new(
8284                    "target_unavailable",
8285                    format!("failed to swap module_id '{module_id}': {message}"),
8286                ),
8287            };
8288            return Ok(vec![control_error_body_frame(&frame, error)?]);
8289        }
8290        // A completed swap kept the incumbent serving until cutover, so it
8291        // usually opened no outage; a mark left behind would make the next,
8292        // unrelated outage read as requested.
8293        self.route_outages
8294            .operator_action_ended_unrefused(&module_id);
8295
8296        let response = ClientControlResponse::SupervisorAck {
8297            module_id,
8298            applied: true,
8299        };
8300        Ok(vec![control_response_body_frame(
8301            &frame,
8302            &response,
8303            "ClientControlResponse::SupervisorAck",
8304        )?])
8305    }
8306
8307    async fn handle_supervisor_reload(
8308        &self,
8309        frame: Frame,
8310        module_id: String,
8311        requester: Principal,
8312    ) -> Result<Vec<Frame>, RouterError> {
8313        let operation_lock = self.supervisor.operation_lock();
8314        let _operation_guard = operation_lock.lock().await;
8315        let Some(module) = self.supervisor.get(&module_id) else {
8316            return Ok(vec![control_error_frame(
8317                &frame,
8318                "unknown_module",
8319                format!("module_id '{module_id}' is not supervised"),
8320            )?]);
8321        };
8322
8323        self.route_outages.mark_operator_action(&module_id);
8324        if let Err(err) = module.reload_requested(Some(requester)).await {
8325            self.route_outages
8326                .operator_action_ended_unrefused(&module_id);
8327            let (code, message) = match err {
8328                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8329                crate::supervise::SuperviseError::Disabled { .. } => {
8330                    ("module_disabled", err.to_string())
8331                }
8332                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8333                    ("swap_in_progress", err.to_string())
8334                }
8335                _ => (
8336                    "reload_failed",
8337                    format!("failed to reload module_id '{module_id}': {err}"),
8338                ),
8339            };
8340            return Ok(vec![control_error_frame(&frame, code, message)?]);
8341        }
8342
8343        let response = ClientControlResponse::SupervisorAck {
8344            module_id,
8345            applied: true,
8346        };
8347        Ok(vec![control_response_body_frame(
8348            &frame,
8349            &response,
8350            "ClientControlResponse::SupervisorAck",
8351        )?])
8352    }
8353
8354    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8355    /// the configuration comes from and whether to apply it; every mode then
8356    /// runs the same comparison, so a preview describes the apply it previews.
8357    async fn handle_supervisor_rescan(
8358        &self,
8359        frame: Frame,
8360        mode: RescanMode,
8361        requester: Principal,
8362    ) -> Result<Vec<Frame>, RouterError> {
8363        let preview = mode.previews();
8364        let mut approved_preview = None;
8365        if matches!(mode, RescanMode::Preview) {
8366            if let Some(owner) = &self.config_runtime {
8367                match owner
8368                    .on_blocking(|owner| {
8369                        owner.observe_file_proposal()?;
8370                        owner.approved_daemon_configuration()
8371                    })
8372                    .await
8373                {
8374                    Ok(config) => approved_preview = config,
8375                    Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8376                }
8377            }
8378        }
8379        let Some(context) = self.rescan.clone() else {
8380            return Ok(vec![control_error_frame(
8381                &frame,
8382                "rescan_unavailable",
8383                "the daemon was not started with a reloadable config path".to_string(),
8384            )?]);
8385        };
8386
8387        let operation_lock = self.supervisor.operation_lock();
8388        let _operation_guard = operation_lock.lock().await;
8389        // Loaded under the operation lock, so no other rescan can change the
8390        // staged configuration between a checked apply's comparison and the
8391        // apply itself.
8392        let loaded = match self.load_rescan_config(&mode, &context) {
8393            Ok(config) => config,
8394            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
8395        };
8396        // `load` reports a missing file as Ok(None), which is correct at boot
8397        // (no config, nothing to supervise) and catastrophic here: rescan treats
8398        // "not in the config" as "remove it", so an absent file would read as an
8399        // empty module list and retire the entire running fleet. An editor
8400        // writing via write-new-then-rename, or a half-finished edit, is enough
8401        // to open that window. Refuse instead: a config that cannot be read
8402        // carries no instruction to remove anything.
8403        let Some((config, activity_config)) = loaded else {
8404            return Ok(vec![control_error_frame(
8405                &frame,
8406                "invalid_daemon_config",
8407                format!(
8408                    "daemon config not found at {}; refusing to rescan (an absent config would \
8409                     retire every supervised module)",
8410                    context.config_path.display()
8411                ),
8412            )?]);
8413        };
8414        let (
8415            configured_port,
8416            storage_config,
8417            admission_facts_carrier_module_id,
8418            admission_facts_targets,
8419            scope_authority_owners,
8420            federated_scope_owner,
8421            privileged_operator_prompt,
8422            modules,
8423            reserved_capabilities,
8424        ) = (
8425            config.port,
8426            config.storage,
8427            config.admission_facts_carrier_module_id,
8428            config.admission_facts_targets,
8429            config.scope_authority_owners,
8430            config.federated_scope_owner,
8431            config.privileged_operator_prompt,
8432            config.modules,
8433            config.reserved_capabilities,
8434        );
8435
8436        // Collect the sections rescan cannot apply, so the REPLY carries them.
8437        //
8438        // The warning below has always been correct and has always gone only to
8439        // the journal -- addressed to whoever reads logs, while the person who
8440        // just edited the config is looking at the CLI. Naming each section
8441        // individually rather than setting a flag: "something outside modules
8442        // changed" sends the operator back to diffing their own file, which is
8443        // the work this is meant to save.
8444        let mut restart_required = Vec::new();
8445        for section in RestartRequiredSection::ALL {
8446            let changed = match section {
8447                RestartRequiredSection::Port => configured_port != context.configured_port,
8448                RestartRequiredSection::Storage => storage_config != context.storage_config,
8449                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8450                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8451                }
8452                RestartRequiredSection::AdmissionFactsTargets => {
8453                    admission_facts_targets != context.admission_facts_targets
8454                }
8455                RestartRequiredSection::ScopeAuthorityOwners => {
8456                    scope_authority_owners != context.scope_authority_owners
8457                }
8458                RestartRequiredSection::FederatedScopeOwner => {
8459                    federated_scope_owner != context.federated_scope_owner
8460                }
8461                RestartRequiredSection::PrivilegedOperatorPrompt => {
8462                    privileged_operator_prompt != context.privileged_operator_prompt
8463                }
8464            };
8465            if changed {
8466                restart_required.push(section.label().to_string());
8467            }
8468        }
8469        if !restart_required.is_empty() {
8470            warn!(
8471                config_path = %context.config_path.display(),
8472                sections = %restart_required.join(", "),
8473                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8474            );
8475        }
8476
8477        for configured in &modules {
8478            if let Err(err) = validate_spec(&configured.module_spec()) {
8479                return Ok(vec![control_error_frame(
8480                    &frame,
8481                    "invalid_daemon_config",
8482                    format!("supervisor rescan rejected daemon config: {err}"),
8483                )?]);
8484            }
8485        }
8486
8487        let configured_capabilities = modules
8488            .iter()
8489            .map(|module| (module.module_id.clone(), module.enabled))
8490            .collect::<Vec<_>>();
8491        let preview_capability_warnings = if preview {
8492            let (_, registrations) = self.runtime_capability_snapshot()?;
8493            let current_modules = self
8494                .supervisor
8495                .list()
8496                .into_iter()
8497                .map(|module| module.module_id().to_string())
8498                .collect::<BTreeSet<_>>();
8499            let resulting_modules = configured_capabilities.clone();
8500            let removed = current_modules
8501                .into_iter()
8502                .filter(|module_id| {
8503                    !resulting_modules
8504                        .iter()
8505                        .any(|(configured_id, _)| configured_id == module_id)
8506                })
8507                .collect::<Vec<_>>();
8508            // A candidate preview also names providers the candidate disables.
8509            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8510            let disabled = match &mode {
8511                RescanMode::Candidate(_) => resulting_modules
8512                    .iter()
8513                    .filter(|(_, enabled)| !enabled)
8514                    .map(|(module_id, _)| module_id.clone())
8515                    .collect::<Vec<_>>(),
8516                _ => Vec::new(),
8517            };
8518            self.capability_evaluator.preview_warnings(
8519                resulting_modules,
8520                &removed,
8521                &disabled,
8522                &registrations,
8523            )
8524        } else {
8525            Vec::new()
8526        };
8527        let reconciled = match (&mode, approved_preview.as_ref()) {
8528            (RescanMode::Preview, Some(approved)) => Ok((
8529                config_gate::preview_approved_daemon(approved, &modules),
8530                Vec::new(),
8531            )),
8532            (RescanMode::Candidate(candidate), _) => self
8533                .preview_candidate(&context, modules, candidate)
8534                .map(|result| (result, Vec::new())),
8535            _ => {
8536                self.reconcile_supervised_modules(
8537                    &context.supervisor,
8538                    modules,
8539                    preview,
8540                    requester.clone(),
8541                )
8542                .await
8543            }
8544        };
8545        let (result, changed) = match reconciled {
8546            Ok(result) => result,
8547            Err(message) => {
8548                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8549            }
8550        };
8551        if !preview {
8552            if let Some(ledger) = &self.activity {
8553                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8554                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8555            }
8556            if let Err(code) = self.configure_activity(activity_config).await {
8557                warn!(
8558                    code,
8559                    "activity retention could not be applied during rescan"
8560                );
8561            }
8562            self.capability_evaluator
8563                .configure(configured_capabilities, reserved_capabilities);
8564            self.capability_evaluator.wake_deadline_loop();
8565            self.refresh_capability_requirements();
8566        }
8567        let mut result = result;
8568        result.restart_required = restart_required;
8569        result.capability_warnings = preview_capability_warnings;
8570        let response = ClientControlResponse::SupervisorRescan { result };
8571        Ok(vec![control_response_body_frame(
8572            &frame,
8573            &response,
8574            "ClientControlResponse::SupervisorRescan",
8575        )?])
8576    }
8577
8578    async fn handle_supervisor_release_reserved(
8579        &self,
8580        frame: Frame,
8581        module_id: String,
8582    ) -> Result<Vec<Frame>, RouterError> {
8583        let Some(context) = self.rescan.clone() else {
8584            return Ok(vec![control_error_frame(
8585                &frame,
8586                "release_unavailable",
8587                "reserved-id release requires a daemon started with a reloadable config path",
8588            )?]);
8589        };
8590        let operation_lock = self.supervisor.operation_lock();
8591        let _operation_guard = operation_lock.lock().await;
8592        let approved = if let Some(owner) = &self.config_runtime {
8593            // Observe the file as a proposal, but decide membership solely from
8594            // approved bytes. A proposed re-add must not retain a removed id.
8595            match owner
8596                .on_blocking(|owner| {
8597                    owner.observe_file_proposal()?;
8598                    owner.approved_daemon_configuration()
8599                })
8600                .await
8601            {
8602                Ok(config) => config,
8603                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8604            }
8605        } else {
8606            None
8607        };
8608        let loaded = if let Some(approved) = approved {
8609            Ok(Some(approved))
8610        } else {
8611            crate::daemon_config::load(&context.config_path)
8612        };
8613        let loaded = match loaded {
8614            Ok(Some(config)) => config,
8615            Ok(None) => {
8616                return Ok(vec![control_error_frame(
8617                    &frame,
8618                    "invalid_daemon_config",
8619                    format!(
8620                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8621                        context.config_path.display()
8622                    ),
8623                )?])
8624            }
8625            Err(err) => {
8626                return Ok(vec![control_error_frame(
8627                    &frame,
8628                    "invalid_daemon_config",
8629                    format!("unable to verify reserved-id release against daemon config: {err}"),
8630                )?])
8631            }
8632        };
8633        if loaded
8634            .modules
8635            .iter()
8636            .any(|configured| configured.module_id == module_id)
8637        {
8638            return Ok(vec![control_error_frame(
8639                &frame,
8640                "reserved_module_configured",
8641                format!(
8642                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8643                ),
8644            )?]);
8645        }
8646        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8647            return Ok(vec![control_error_frame(
8648                &frame,
8649                "reserved_gate_not_retained",
8650                format!(
8651                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8652                ),
8653            )?]);
8654        }
8655
8656        let response = ClientControlResponse::SupervisorAck {
8657            module_id,
8658            applied: true,
8659        };
8660        Ok(vec![control_response_body_frame(
8661            &frame,
8662            &response,
8663            "ClientControlResponse::SupervisorAck",
8664        )?])
8665    }
8666
8667    /// Compare the configured module set with the supervised one, changing
8668    /// nothing. The staged spec each supervised module holds is what the
8669    /// configured entry is compared with.
8670    fn plan_rescan(
8671        &self,
8672        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8673    ) -> Result<RescanPlan, String> {
8674        let mut current = BTreeMap::new();
8675        for module in self.supervisor.list() {
8676            let (spec, health) = module.configuration().map_err(|err| {
8677                format!(
8678                    "failed to read configuration for module_id '{}': {err}",
8679                    module.module_id()
8680                )
8681            })?;
8682            let enabled = module
8683                .status()
8684                .map_err(|err| {
8685                    format!(
8686                        "failed to read status for module_id '{}': {err}",
8687                        module.module_id()
8688                    )
8689                })?
8690                .enabled;
8691            current.insert(
8692                module.module_id().to_string(),
8693                (module, spec, health, enabled),
8694            );
8695        }
8696        let configured = configured_modules
8697            .into_iter()
8698            .map(|module| (module.module_id.clone(), module))
8699            .collect::<BTreeMap<_, _>>();
8700
8701        let added = configured
8702            .keys()
8703            .filter(|module_id| !current.contains_key(*module_id))
8704            .cloned()
8705            .collect::<Vec<_>>();
8706        let removed = current
8707            .keys()
8708            .filter(|module_id| !configured.contains_key(*module_id))
8709            .cloned()
8710            .collect::<Vec<_>>();
8711        let mut changed_pending_reload = Vec::new();
8712        let mut changed_pending = Vec::new();
8713        let mut configuration_changes = BTreeSet::new();
8714        let mut enabled_changes = BTreeSet::new();
8715        let mut unchanged = 0_u32;
8716        let publication = self
8717            .config_runtime
8718            .as_ref()
8719            .and_then(|owner| owner.polled_snapshot().ok());
8720
8721        for (module_id, configured_module) in &configured {
8722            let Some((module, current_spec, current_health, current_enabled)) =
8723                current.get(module_id)
8724            else {
8725                continue;
8726            };
8727            // Compare the whole launch spec so a future launch field cannot
8728            // accidentally become a live-only policy change. Health is stored
8729            // separately and applies live without replacing the process.
8730            let launch_changed = *current_spec != configured_module.module_spec();
8731            let configuration_changed =
8732                launch_changed || *current_health != configured_module.health;
8733            let pending = self.pending_module_fields(
8734                module,
8735                Some(configured_module),
8736                configuration_changed,
8737                Self::registration_channel_in_force(
8738                    publication
8739                        .as_ref()
8740                        .and_then(|view| view.registration_declaration(module_id))
8741                        .as_deref(),
8742                    publication
8743                        .as_ref()
8744                        .and_then(|view| match &view.approved_daemon {
8745                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8746                                config,
8747                                ..
8748                            } => config
8749                                .modules
8750                                .iter()
8751                                .find(|entry| entry.module_id == *module_id)
8752                                .map(|entry| entry.registration_channel),
8753                            _ => None,
8754                        }),
8755                ),
8756            )?;
8757            let has_pending = !pending.is_empty();
8758            if has_pending {
8759                changed_pending.push(subc_control::SupervisorPendingModule {
8760                    module_id: module_id.clone(),
8761                    fields: pending
8762                        .into_iter()
8763                        .map(|mut field| {
8764                            field.value = None;
8765                            field
8766                        })
8767                        .collect(),
8768                });
8769            }
8770            // Applying a rescan also replaces the recorded config value, even
8771            // when an operator already put the runtime in the requested state.
8772            let enabled_changed = *current_enabled != configured_module.enabled
8773                || self
8774                    .capability_evaluator
8775                    .configured_enabled(module_id)
8776                    .is_some_and(|enabled| enabled != configured_module.enabled);
8777            if configuration_changed {
8778                configuration_changes.insert(module_id.clone());
8779            }
8780            if launch_changed {
8781                changed_pending_reload.push(module_id.clone());
8782            }
8783            if enabled_changed {
8784                enabled_changes.insert(module_id.clone());
8785            }
8786            if !configuration_changed && !enabled_changed && !has_pending {
8787                unchanged = unchanged.saturating_add(1);
8788            }
8789        }
8790        Ok(RescanPlan {
8791            current,
8792            configured,
8793            added,
8794            removed,
8795            changed_pending_reload,
8796            changed_pending,
8797            configuration_changes,
8798            enabled_changes,
8799            unchanged,
8800        })
8801    }
8802
8803    /// Reconcile the running module set against the configured one.
8804    ///
8805    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8806    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8807    /// deliberately shares this function with the executing path rather than
8808    /// computing the same diff somewhere else -- two implementations of one
8809    /// decision agree until they do not, and the whole value of a preview is that
8810    /// it describes the operation that will actually run.
8811    async fn reconcile_supervised_modules(
8812        &self,
8813        supervisor: &Supervisor,
8814        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8815        preview: bool,
8816        requester: Principal,
8817    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8818        let plan = self.plan_rescan(configured_modules)?;
8819
8820        // Everything above this point is pure computation over two snapshots.
8821        // Everything below MUTATES. The preview returns here so the boundary is a
8822        // single early return rather than a condition repeated at each mutation
8823        // site, where one missed guard would apply part of a change the caller was
8824        // told would not happen.
8825        if preview {
8826            return Ok((plan.preview_result(), Vec::new()));
8827        }
8828        let changed = plan
8829            .configuration_changes
8830            .union(&plan.enabled_changes)
8831            .cloned()
8832            .collect::<Vec<_>>();
8833        let RescanPlan {
8834            current,
8835            configured,
8836            added,
8837            removed,
8838            changed_pending_reload,
8839            changed_pending,
8840            configuration_changes,
8841            enabled_changes,
8842            unchanged,
8843        } = plan;
8844        // The staged generation moves before the first change rather than
8845        // after the last, so a rescan that fails partway still invalidates
8846        // every earlier `supervisor.rescan_checked` preview: part of its diff
8847        // may have run.
8848        if !(added.is_empty()
8849            && removed.is_empty()
8850            && configuration_changes.is_empty()
8851            && changed_pending.is_empty()
8852            && enabled_changes.is_empty())
8853        {
8854            if let Some(context) = &self.rescan {
8855                context
8856                    .generation
8857                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8858            }
8859        }
8860
8861        for module_id in &removed {
8862            let module = &current
8863                .get(module_id)
8864                .expect("removed module came from current supervisor state")
8865                .0;
8866            module
8867                .retire_requested(Some(requester.clone()))
8868                .await
8869                .map_err(|err| {
8870                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8871                })?;
8872            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8873            //
8874            // `handle_route_open` resolves an absent module in three steps:
8875            // registry, then supervisor status, then tombstone. Retiring first
8876            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8877            // went with the teardown above, the supervisor entry went with
8878            // `retire`, and the tombstone does not exist yet -- so a route.open
8879            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8880            // it") for a module that was deliberately removed and whose caller
8881            // should get `module_removed` (TERMINAL, carrying a removal age).
8882            //
8883            // Writing the tombstone first closes it: during the window the
8884            // supervisor entry still answers, so the caller gets
8885            // `target_unavailable` -- retryable, and TRUE, because the module
8886            // is mid-teardown. After both statements it is `module_removed`.
8887            // No instant remains where a removed module reads as one that
8888            // never existed.
8889            //
8890            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8891            // the absence of a test beside a fix invites deletion: these are
8892            // two sync statements with no await between them, so reaching the
8893            // window needs a second worker thread to land exactly between them
8894            // and there is no hook to force it. MEASURED: the 25 daemon_config
8895            // tests pass identically with the old order and the new one, so
8896            // the existing suite cannot see this and a green run is not
8897            // evidence either way. What the suite does hold is the
8898            // post-condition -- a removed module answers `module_removed` --
8899            // which this preserves.
8900            //
8901            // Found by an Athena panel reading the shipped tree against a
8902            // design note (2026-09-19), as the one concrete instance of that
8903            // note's class that survived contact with source. Direction is
8904            // benign: retryable where terminal was intended, never the reverse.
8905            self.supervisor.record_rescan_removal(module_id);
8906            self.supervisor.retire(module_id);
8907            self.route_outages.forget(module_id);
8908        }
8909
8910        for module_id in configured.keys() {
8911            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8912                continue;
8913            };
8914            let configured_module = configured
8915                .get(module_id)
8916                .expect("configured module id came from configured map");
8917            if configuration_changes.contains(module_id) {
8918                module
8919                    .update_configuration(
8920                        configured_module.module_spec(),
8921                        configured_module.health.clone(),
8922                        configured_module.drain_timeout_ms,
8923                    )
8924                    .await
8925                    .map_err(|err| {
8926                        format!(
8927                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8928                        )
8929                    })?;
8930            }
8931            // Config-only drift is applied by the evaluator's config update;
8932            // do not turn it into a runtime start or stop.
8933            if *current_enabled != configured_module.enabled {
8934                // A rescan that starts or stops a module applies an operator's
8935                // edit to the config, so the resulting outage was asked for.
8936                self.route_outages.mark_operator_action(module_id);
8937                module
8938                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8939                    .await
8940                    .map_err(|err| {
8941                        self.route_outages.operator_action_ended_unrefused(module_id);
8942                        format!(
8943                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8944                            configured_module.enabled
8945                        )
8946                    })?;
8947            }
8948        }
8949
8950        for module_id in &added {
8951            let configured_module = configured
8952                .get(module_id)
8953                .expect("added module id came from configured map");
8954            supervisor
8955                .supervise_configured_requested_async(
8956                    configured_module.module_spec(),
8957                    configured_module.enabled,
8958                    configured_module.health.clone(),
8959                    configured_module.drain_timeout_ms,
8960                    configured_module.restart,
8961                    configured_module.register_timeout,
8962                    Some(requester.clone()),
8963                )
8964                .await
8965                .map_err(|err| {
8966                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8967                })?;
8968        }
8969
8970        if let Some(context) = &self.rescan {
8971            let mut entries = context
8972                .module_entries
8973                .lock()
8974                .unwrap_or_else(|e| e.into_inner());
8975            entries.record(&configured, &added, &removed);
8976        }
8977
8978        Ok((
8979            SupervisorRescanResult {
8980                added,
8981                removed,
8982                changed_pending_reload,
8983                changed_pending,
8984                enabled_changes: enabled_changes.iter().cloned().collect(),
8985                unchanged,
8986                preview: false,
8987                // Filled by the caller, which is the only layer that can see the
8988                // previous config to diff against.
8989                restart_required: Vec::new(),
8990                capability_warnings: Vec::new(),
8991                module_actions: Vec::new(),
8992                earlier_pending: Vec::new(),
8993                expect: None,
8994            },
8995            changed,
8996        ))
8997    }
8998
8999    async fn handle_supervisor_set_enabled(
9000        &self,
9001        frame: Frame,
9002        module_id: String,
9003        enabled: bool,
9004        requester: Principal,
9005    ) -> Result<Vec<Frame>, RouterError> {
9006        let operation_lock = self.supervisor.operation_lock();
9007        let _operation_guard = operation_lock.lock().await;
9008        let Some(module) = self.supervisor.get(&module_id) else {
9009            return Ok(vec![control_error_frame(
9010                &frame,
9011                "unknown_module",
9012                format!("module_id '{module_id}' is not supervised"),
9013            )?]);
9014        };
9015
9016        // Enabling counts as well as disabling: a module an operator starts
9017        // is refused until it registers, and that wait was asked for.
9018        self.route_outages.mark_operator_action(&module_id);
9019        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
9020            Ok(applied) => applied,
9021            Err(err) => {
9022                self.route_outages
9023                    .operator_action_ended_unrefused(&module_id);
9024                return Ok(vec![control_error_frame(
9025                    &frame,
9026                    if err.is_config_gate_error() {
9027                        "config_gated"
9028                    } else {
9029                        "target_unavailable"
9030                    },
9031                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
9032                )?]);
9033            }
9034        };
9035        if !applied {
9036            // Already in the requested state: nothing was made unavailable,
9037            // so the mark must not outlive this request.
9038            self.route_outages
9039                .operator_action_ended_unrefused(&module_id);
9040        }
9041
9042        self.capability_evaluator.wake_deadline_loop();
9043        self.refresh_capability_requirements();
9044        let response = ClientControlResponse::SupervisorAck { module_id, applied };
9045        Ok(vec![control_response_body_frame(
9046            &frame,
9047            &response,
9048            "ClientControlResponse::SupervisorAck",
9049        )?])
9050    }
9051
9052    async fn handle_supervisor_health_probe(
9053        &self,
9054        ctx: &RouteCtx,
9055        frame: Frame,
9056        module_id: String,
9057    ) -> Result<Vec<Frame>, RouterError> {
9058        self.refresh_capability_requirements();
9059        let Some(registration) = self
9060            .registry
9061            .get_module(&module_id)
9062            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
9063        else {
9064            return Ok(vec![control_error_frame(
9065                &frame,
9066                "unknown_module",
9067                format!("module_id '{module_id}' is not registered"),
9068            )?]);
9069        };
9070
9071        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
9072        // named for it. Making `module_registration_grants_op` return false
9073        // unconditionally reddens five tests, and every one is named for something
9074        // else -- capability relay, probe/bind demultiplexing, supervision-only
9075        // probing. They exercise a successful advertisement check on the way to their
9076        // own subject.
9077        //
9078        // Real protection, fragile in a specific way: narrowing any of those tests to
9079        // focus on its stated subject would silently remove coverage nobody knows
9080        // they are carrying. Recorded here rather than as a sixth test, because the
9081        // useful fact is WHICH tests hold the guard up -- a new test would add
9082        // coverage without telling the next person what the existing ones quietly do.
9083        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
9084        {
9085            return Ok(vec![control_error_frame(
9086                &frame,
9087                "health_not_advertised",
9088                format!("module_id '{module_id}' did not advertise health.check"),
9089            )?]);
9090        }
9091
9092        self.observe_control_wait(
9093            ctx,
9094            Some(&registration.manifest.module_id),
9095            ops::SUPERVISOR_HEALTH_PROBE,
9096            async {
9097                let deadline = Instant::now() + self.health_probe_timeout;
9098                let pending = match self.forwarding.begin_module_control_rpc_for(
9099                    &module_id,
9100                    MODULE_CONTROL_OP_HEALTH_CHECK,
9101                    deadline,
9102                ) {
9103                    Ok(pending) => pending,
9104                    Err(err) => {
9105                        return Ok(vec![control_error_frame(
9106                            &frame,
9107                            forwarding_error_code(&err),
9108                            err.to_string(),
9109                        )?])
9110                    }
9111                };
9112
9113                let PendingModuleControlRpc {
9114                    endpoint,
9115                    module_sink,
9116                    negotiated_ver,
9117                    corr: probe_corr,
9118                    receiver,
9119                } = pending;
9120                let mut guard =
9121                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
9122                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
9123                    .map_err(|err| {
9124                        RouterError::backend(
9125                            0,
9126                            frame.header.corr,
9127                            format!("failed to encode health.check request: {err}"),
9128                        )
9129                    })?;
9130                let probe_frame = Frame::build_with_version(
9131                    negotiated_ver,
9132                    FrameType::Request,
9133                    control_flags(),
9134                    0,
9135                    0,
9136                    probe_corr,
9137                    probe_body,
9138                )
9139                .map_err(RouterError::FrameBuild)?;
9140
9141                // Queue admission and the reply share one deadline, so a module that
9142                // stops reading cannot park the requesting connection's reader forever.
9143                match timeout_at(deadline, module_sink.send(probe_frame)).await {
9144                    Ok(Ok(())) => {}
9145                    Ok(Err(err)) => {
9146                        return Ok(vec![control_error_frame(
9147                            &frame,
9148                            "target_unavailable",
9149                            err.to_string(),
9150                        )?]);
9151                    }
9152                    Err(_) => {
9153                        return Ok(vec![control_error_frame(
9154                            &frame,
9155                            "module_timeout",
9156                            format!(
9157                                "module_id '{module_id}' did not answer health.check within {:?}",
9158                                self.health_probe_timeout
9159                            ),
9160                        )?]);
9161                    }
9162                }
9163
9164                match timeout_at(deadline, receiver).await {
9165                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9166                        Ok(vec![control_error_frame(
9167                            &frame,
9168                            "invalid_control_body",
9169                            "health.check returned an unexpected config response",
9170                        )?])
9171                    }
9172                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9173                        guard.disarm();
9174                        let Some(report) = response.health_report() else {
9175                            return Ok(vec![control_error_frame(
9176                                &frame,
9177                                "invalid_control_body",
9178                                "health.check RPC returned a non-health response",
9179                            )?]);
9180                        };
9181                        // Metrics go out whole here. The supervisor's cached snapshot
9182                        // caps this blob (see truncate_health_metrics), and this path
9183                        // exists precisely to answer without that cap -- so applying it
9184                        // here would leave no way to see what the cached view drops.
9185                        let HealthReport {
9186                            status,
9187                            detail,
9188                            metrics,
9189                        } = report;
9190                        let capability_detail = self
9191                            .capability_evaluator
9192                            .required_problem_detail(&module_id);
9193                        let response = ClientControlResponse::SupervisorHealthProbe {
9194                            module_id,
9195                            status,
9196                            detail: append_capability_problem_detail(detail, capability_detail),
9197                            metrics,
9198                        };
9199                        Ok(vec![control_response_body_frame(
9200                            &frame,
9201                            &response,
9202                            "ClientControlResponse::SupervisorHealthProbe",
9203                        )?])
9204                    }
9205                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9206                        guard.disarm();
9207                        // The module refused the health probe with its own body, so
9208                        // the refusal is relayed without the daemon-origin flag
9209                        // (bit 6): a client must not read it as the daemon's own
9210                        // refusal, which it may treat as never forwarded.
9211                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9212                    }
9213                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9214                        guard.disarm();
9215                        Ok(vec![control_error_frame(
9216                            &frame,
9217                            "target_unavailable",
9218                            message,
9219                        )?])
9220                    }
9221                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9222                        guard.disarm();
9223                        Ok(vec![control_error_frame(
9224                            &frame,
9225                            "invalid_control_body",
9226                            message,
9227                        )?])
9228                    }
9229                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9230                        guard.disarm();
9231                        Ok(vec![control_error_frame(
9232                            &frame,
9233                            "invalid_control_body",
9234                            format!("expected module-control op '{expected}', got '{actual}'"),
9235                        )?])
9236                    }
9237                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9238                        guard.disarm();
9239                        Ok(vec![control_error_frame(
9240                            &frame,
9241                            "module_timeout",
9242                            format!(
9243                                "module_id '{module_id}' answered health.check after {:?}",
9244                                self.health_probe_timeout
9245                            ),
9246                        )?])
9247                    }
9248                    Ok(Err(_)) => Ok(vec![control_error_frame(
9249                        &frame,
9250                        "target_unavailable",
9251                        "health.check waiter was canceled before the module responded",
9252                    )?]),
9253                    Err(_) => Ok(vec![control_error_frame(
9254                        &frame,
9255                        "module_timeout",
9256                        format!(
9257                            "module_id '{module_id}' did not answer health.check within {:?}",
9258                            self.health_probe_timeout
9259                        ),
9260                    )?]),
9261                }
9262            },
9263        )
9264        .await
9265    }
9266
9267    fn supervisor_status(
9268        &self,
9269        module_id: &str,
9270        corr: u64,
9271    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9272        self.supervisor
9273            .get(module_id)
9274            .map(|module| {
9275                let warming = module.is_warming_for_control("status").map_err(|err| {
9276                    RouterError::backend(
9277                        0,
9278                        corr,
9279                        format!(
9280                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9281                        ),
9282                    )
9283                })?;
9284                module.status_for_control("status").map_err(|err| {
9285                    RouterError::backend(
9286                        0,
9287                        corr,
9288                        format!(
9289                            "failed to read supervisor status for module_id '{module_id}': {err}"
9290                        ),
9291                    )
9292                }).map(|status| (status, warming))
9293            })
9294            .transpose()
9295    }
9296
9297    fn guard_module_control_op(
9298        &self,
9299        frame: &Frame,
9300        module_id: &str,
9301        op: &str,
9302    ) -> Result<Option<Frame>, RouterError> {
9303        if self.module_grants_op(module_id, op, frame.header.corr)? {
9304            return Ok(None);
9305        }
9306
9307        Ok(Some(control_error_frame(
9308            frame,
9309            "op_not_allowed",
9310            format!("module_id '{module_id}' did not grant control op '{op}'"),
9311        )?))
9312    }
9313
9314    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9315        self.registry
9316            .grants_control_op(module_id, op)
9317            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9318    }
9319
9320    fn handle_status_update(
9321        &self,
9322        endpoint: ModuleEndpointId,
9323        frame: Frame,
9324    ) -> Result<Vec<Frame>, RouterError> {
9325        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9326            Ok(update) => update,
9327            Err(err) => {
9328                // Forward-compat: a newer module may push a channel-0 op this subc
9329                // version doesn't know. The control contract says unknown push ops
9330                // are IGNORED, never answered with an error. Only a malformed body
9331                // for an op we DO know is a real error worth surfacing.
9332                if is_known_module_push_op(&frame.body) {
9333                    return Ok(vec![control_error_frame(
9334                        &frame,
9335                        "invalid_control_body",
9336                        format!("malformed module control push body: {err}"),
9337                    )?]);
9338                }
9339                return Ok(Vec::new());
9340            }
9341        };
9342
9343        match update {
9344            ModuleControlPush::RouteStatus {
9345                route_channel,
9346                route_epoch,
9347                status,
9348            } => {
9349                self.forwarding
9350                    .cache_status(endpoint, route_channel, route_epoch, status)
9351                    .map_err(RouterError::Forwarding)?;
9352            }
9353        }
9354        Ok(Vec::new())
9355    }
9356
9357    fn handle_route_poll(
9358        &self,
9359        ctx: &RouteCtx,
9360        frame: Frame,
9361        route_channel: u16,
9362        route_epoch: u32,
9363        kind: PollKind,
9364    ) -> Result<Vec<Frame>, RouterError> {
9365        let snapshot = self
9366            .forwarding
9367            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9368            .map_err(RouterError::Forwarding)?;
9369        let response = match (kind, snapshot) {
9370            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9371                ClientControlResponse::RoutePoll {
9372                    route_channel,
9373                    route_epoch,
9374                    status,
9375                    live: None,
9376                }
9377            }
9378            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9379                route_channel,
9380                route_epoch,
9381                status: None,
9382                live: None,
9383            },
9384            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9385                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9386                // is what makes reporting `true` correct rather than a
9387                // confident guess. `process_live` returns None only when the
9388                // module id has no supervisor snapshot at all -- an
9389                // externally-started module the daemon did not spawn -- and
9390                // for those the supervisor has no opinion to offer, ever. It
9391                // is never None for a supervised module in an unknown state:
9392                // a supervised module always has a snapshot, and the answer
9393                // comes from `state == Running && process_alive`.
9394                //
9395                // The route is Bound, so the module completed a HELLO on a
9396                // live connection; "the process this route points at is
9397                // running" is therefore attested by the binding rather than
9398                // assumed. Reporting `false` for an unsupervised module would
9399                // be the actual lie -- it would tell a client its healthy
9400                // route is dead because the daemon does not manage the
9401                // process.
9402                //
9403                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9404                // module whose liveness is genuinely unknown, e.g. a snapshot
9405                // that has not been populated yet -- THIS DEFAULT BECOMES
9406                // WRONG and must split: unsupervised stays true, unknown
9407                // becomes null so the client can tell the two apart. The
9408                // response field is already `Option<bool>`, so the wire can
9409                // carry that distinction today.
9410                let live = self
9411                    .process_liveness
9412                    .as_ref()
9413                    .and_then(|source| source.process_live(&module_id))
9414                    .unwrap_or(true);
9415                ClientControlResponse::RoutePoll {
9416                    route_channel,
9417                    route_epoch,
9418                    status: None,
9419                    live: Some(live),
9420                }
9421            }
9422            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9423                route_channel,
9424                route_epoch,
9425                status: None,
9426                live: Some(false),
9427            },
9428        };
9429
9430        Ok(vec![control_response_body_frame(
9431            &frame,
9432            &response,
9433            "ClientControlResponse::RoutePoll",
9434        )?])
9435    }
9436
9437    pub(crate) fn observe_module_control_completion(
9438        &self,
9439        completion: ModuleControlRpcCompletion,
9440    ) -> bool {
9441        match completion {
9442            ModuleControlRpcCompletion::Unknown => false,
9443            ModuleControlRpcCompletion::Settled => true,
9444            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9445                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9446                info!(
9447                    module_id = %module_id,
9448                    latency_ms,
9449                    "late health.check answer proves the module is alive"
9450                );
9451                match self
9452                    .supervisor
9453                    .record_late_health_answer(&module_id, latency_ms)
9454                {
9455                    Ok(true) => {}
9456                    Ok(false) => debug!(
9457                        module_id = %module_id,
9458                        latency_ms,
9459                        "late health.check answer has no active supervisor snapshot"
9460                    ),
9461                    Err(err) => warn!(
9462                        module_id = %module_id,
9463                        latency_ms,
9464                        error = %err,
9465                        "failed to record late health.check answer"
9466                    ),
9467                }
9468                true
9469            }
9470        }
9471    }
9472
9473    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9474    /// the module connection whose frame is being handled, or to the client that
9475    /// relay was opened for.
9476    ///
9477    /// This runs on the MODULE connection's frame handler, where returning `Err`
9478    /// ends that connection -- and a module connection carries every client's
9479    /// routes to that module, so ending it costs the whole fleet its tools.
9480    /// `ConnectionClosing` carries the id of the connection that is closing, and
9481    /// when that id is a CLIENT's, the condition is entirely about that one
9482    /// client's route.open. A client-scoped condition has no authority over a
9483    /// shared module connection, so it is logged and the single relay is dropped:
9484    /// the client is going away, and `complete_pending_relay` already removed the
9485    /// relay before failing, so there is nothing left to settle. Anything that
9486    /// relay still reserved is released by that client's own connection teardown,
9487    /// which is already under way -- that is what "closing" means.
9488    ///
9489    /// Every other failure is a statement about THIS connection and stays fatal:
9490    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9491    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9492    /// frames correctly.
9493    fn refuse_to_end_module_connection_for_a_client(
9494        &self,
9495        module_connection_id: ConnectionId,
9496        corr: u64,
9497        err: ForwardingError,
9498    ) -> Result<(), RouterError> {
9499        if let ForwardingError::ConnectionClosing { connection_id } = err {
9500            if connection_id != module_connection_id {
9501                warn!(
9502                    module_connection_id = module_connection_id.get(),
9503                    client_connection_id = connection_id.get(),
9504                    corr,
9505                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9506                );
9507                return Ok(());
9508            }
9509        }
9510        Err(RouterError::Forwarding(err))
9511    }
9512
9513    fn handle_module_relay_response(
9514        &self,
9515        connection_id: ConnectionId,
9516        frame: Frame,
9517    ) -> Result<Vec<Frame>, RouterError> {
9518        let mut secondary_error = None;
9519        let outcome = match frame.header.ty {
9520            FrameType::Response => match module_control_response_probe(&frame.body) {
9521                Ok(probe) if probe.op == "route.bind" => {
9522                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9523                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9524                            RouteBindRelayOutcome::Accepted
9525                        }
9526                        Ok(other) => {
9527                            let message =
9528                                format!("route.bind response carried unexpected body: {other:?}");
9529                            secondary_error = Some(control_error_frame(
9530                                &frame,
9531                                "invalid_control_body",
9532                                message.clone(),
9533                            )?);
9534                            RouteBindRelayOutcome::ModuleGone(message)
9535                        }
9536                        Err(err) => {
9537                            let message = format!("malformed route.bind response body: {err}");
9538                            secondary_error = Some(control_error_frame(
9539                                &frame,
9540                                "invalid_control_body",
9541                                message.clone(),
9542                            )?);
9543                            RouteBindRelayOutcome::ModuleGone(message)
9544                        }
9545                    }
9546                }
9547                Ok(probe) => {
9548                    let outcome = if matches!(
9549                        probe.op.as_str(),
9550                        "config.review" | "consent/v1" | "projects.enumerate"
9551                    ) {
9552                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9553                    } else {
9554                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9555                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9556                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9557                                "malformed {} response body: {err}",
9558                                probe.op
9559                            )),
9560                        }
9561                    };
9562                    let completion = self
9563                        .forwarding
9564                        .complete_module_control_rpc(
9565                            connection_id,
9566                            frame.header.corr,
9567                            Some(&probe.op),
9568                            outcome,
9569                        )
9570                        .map_err(RouterError::Forwarding)?;
9571                    if !self.observe_module_control_completion(completion) {
9572                        debug!(
9573                            connection_id = connection_id.get(),
9574                            corr = frame.header.corr,
9575                            op = %probe.op,
9576                            "dropping late or unknown module-control RPC response"
9577                        );
9578                    }
9579                    return Ok(Vec::new());
9580                }
9581                Err(err) => {
9582                    if let Some(expected_op) = self
9583                        .forwarding
9584                        .pending_module_control_op(connection_id, frame.header.corr)
9585                        .map_err(RouterError::Forwarding)?
9586                    {
9587                        let completion = self
9588                            .forwarding
9589                            .complete_module_control_rpc(
9590                                connection_id,
9591                                frame.header.corr,
9592                                None,
9593                                ModuleControlRpcOutcome::MalformedResponse(format!(
9594                                    "malformed {expected_op} response body: {err}"
9595                                )),
9596                            )
9597                            .map_err(RouterError::Forwarding)?;
9598                        if !self.observe_module_control_completion(completion) {
9599                            debug!(
9600                                connection_id = connection_id.get(),
9601                                corr = frame.header.corr,
9602                                "dropping late malformed module-control RPC response"
9603                            );
9604                        }
9605                        return Ok(Vec::new());
9606                    }
9607                    let message = format!("malformed route.bind response body: {err}");
9608                    secondary_error = Some(control_error_frame(
9609                        &frame,
9610                        "invalid_control_body",
9611                        message.clone(),
9612                    )?);
9613                    RouteBindRelayOutcome::ModuleGone(message)
9614                }
9615            },
9616            FrameType::Error => {
9617                if self
9618                    .forwarding
9619                    .pending_module_control_op(connection_id, frame.header.corr)
9620                    .map_err(RouterError::Forwarding)?
9621                    .is_some()
9622                {
9623                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9624                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9625                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9626                            "malformed module-control ERROR body: {err}"
9627                        )),
9628                    };
9629                    let completion = self
9630                        .forwarding
9631                        .complete_module_control_rpc(
9632                            connection_id,
9633                            frame.header.corr,
9634                            None,
9635                            outcome,
9636                        )
9637                        .map_err(RouterError::Forwarding)?;
9638                    if !self.observe_module_control_completion(completion) {
9639                        debug!(
9640                            connection_id = connection_id.get(),
9641                            corr = frame.header.corr,
9642                            "dropping late or unknown module-control RPC error"
9643                        );
9644                    }
9645                    return Ok(Vec::new());
9646                }
9647                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9648                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9649                    Err(err) => {
9650                        let message = format!("malformed route.bind ERROR body: {err}");
9651                        secondary_error = Some(control_error_frame(
9652                            &frame,
9653                            "invalid_control_body",
9654                            message.clone(),
9655                        )?);
9656                        RouteBindRelayOutcome::ModuleGone(message)
9657                    }
9658                }
9659            }
9660            ty => {
9661                return Ok(vec![control_error_frame(
9662                    &frame,
9663                    "unsupported_control_frame",
9664                    format!("unsupported module channel-0 frame {ty:?}"),
9665                )?])
9666            }
9667        };
9668
9669        let settled =
9670            self.forwarding
9671                .complete_pending_relay(connection_id, frame.header.corr, outcome);
9672        let completion = match settled {
9673            Ok(completion) => completion,
9674            Err(err) => {
9675                self.refuse_to_end_module_connection_for_a_client(
9676                    connection_id,
9677                    frame.header.corr,
9678                    err,
9679                )?;
9680                return Ok(secondary_error.into_iter().collect());
9681            }
9682        };
9683        if let Some(target) = completion.abandoned.as_ref() {
9684            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9685        }
9686        if !completion.settled {
9687            debug!(
9688                connection_id = connection_id.get(),
9689                corr = frame.header.corr,
9690                frame_type = ?frame.header.ty,
9691                "dropping late or unknown route.bind relay response"
9692            );
9693        }
9694        Ok(secondary_error.into_iter().collect())
9695    }
9696
9697    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9698        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9699        // GOODBYE ends the connection's logical session even when its socket
9700        // stays open. Use disconnect teardown so verdicts, client notices and
9701        // scope authority are released at the same lifecycle boundary.
9702        self.cleanup_connection_with_end_reason(
9703            connection_id,
9704            RegistrationEndReason::ExplicitGoodbye,
9705        )
9706        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9707        Ok(Vec::new())
9708    }
9709}
9710
9711impl Default for ControlHandler {
9712    fn default() -> Self {
9713        Self::new(Arc::new(Registry::default()))
9714    }
9715}
9716
9717impl crate::supervise::SwapPromotionObserver for ControlHandler {
9718    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9719        self.apply_registration_capabilities(registration);
9720    }
9721}
9722
9723fn capability_requirement_status(status: RequirementStatus) -> CapabilityRequirementStatus {
9724    CapabilityRequirementStatus {
9725        consumer: status.consumer,
9726        capability: status.capability,
9727        need: match status.need {
9728            subc_protocol::manifest::CapabilityNeed::Required => "required".to_string(),
9729            subc_protocol::manifest::CapabilityNeed::Optional => "optional".to_string(),
9730        },
9731        verdict: status.verdict.as_str().to_string(),
9732        episode_seq: status.episode_seq,
9733        config_satisfiable: status.config_satisfiable,
9734        runtime_available: status.runtime_available,
9735        detail: status.detail,
9736    }
9737}
9738
9739fn append_capability_problem_detail(
9740    detail: Option<String>,
9741    capability_detail: Option<String>,
9742) -> Option<String> {
9743    match (detail, capability_detail) {
9744        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9745        (Some(detail), None) => Some(detail),
9746        (None, Some(capability_detail)) => Some(capability_detail),
9747        (None, None) => None,
9748    }
9749}
9750
9751fn subc_ops() -> Vec<String> {
9752    SUBC_CONTROL_OPS
9753        .iter()
9754        .map(|op| (*op).to_string())
9755        .collect()
9756}
9757
9758fn module_subc_ops() -> Vec<String> {
9759    SUBC_CONTROL_OPS
9760        .iter()
9761        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9762        .map(|op| (*op).to_string())
9763        .collect()
9764}
9765
9766#[cfg(test)]
9767fn module_baseline_control_ops() -> Vec<String> {
9768    MODULE_BASELINE_CONTROL_OPS
9769        .iter()
9770        .map(|op| (*op).to_string())
9771        .collect()
9772}
9773
9774fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9775    let mut seen = HashSet::new();
9776    let mut effective = Vec::new();
9777    for op in MODULE_BASELINE_CONTROL_OPS {
9778        if seen.insert((*op).to_string()) {
9779            effective.push((*op).to_string());
9780        }
9781    }
9782    for op in declared.unwrap_or_default() {
9783        if seen.insert(op.clone()) {
9784            effective.push(op);
9785        }
9786    }
9787    effective
9788}
9789
9790fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9791    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9792}
9793
9794fn target_module_id(target: &RouteTarget) -> &str {
9795    match target {
9796        RouteTarget::ToolProvider { module_id }
9797        | RouteTarget::ManagementSurface { module_id }
9798        | RouteTarget::InternalService { module_id, .. } => module_id,
9799    }
9800}
9801
9802fn target_has_required_role(
9803    target: &RouteTarget,
9804    roles: &[crate::registry::AdmissionRole],
9805) -> bool {
9806    use crate::registry::AdmissionRole;
9807    roles.iter().any(|role| match (target, role) {
9808        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9809        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9810        (
9811            RouteTarget::InternalService { service_id, .. },
9812            AdmissionRole::InternalService(provided),
9813        ) => service_id == provided,
9814        _ => false,
9815    })
9816}
9817
9818fn is_routable_role(role: &ProviderRole) -> bool {
9819    matches!(
9820        role,
9821        ProviderRole::ToolProvider { .. }
9822            | ProviderRole::ManagementSurface { .. }
9823            | ProviderRole::InternalService { .. }
9824    )
9825}
9826
9827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9828enum ControlRequestBodyError {
9829    UnknownOp,
9830    InvalidBody,
9831}
9832
9833#[derive(Debug, Deserialize)]
9834struct ControlOpProbe {
9835    op: String,
9836}
9837
9838fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9839    serde_json::from_slice(body).or_else(|original| {
9840        #[derive(Deserialize)]
9841        struct ConsentProbe {
9842            protocol: String,
9843        }
9844        match serde_json::from_slice::<ConsentProbe>(body) {
9845            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9846                Ok(ControlOpProbe { op: probe.protocol })
9847            }
9848            _ => Err(original),
9849        }
9850    })
9851}
9852
9853/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9854/// this set is treated as a forward-compat unknown and ignored rather than errored.
9855const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9856
9857fn is_known_module_push_op(body: &[u8]) -> bool {
9858    serde_json::from_slice::<ControlOpProbe>(body)
9859        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9860        .unwrap_or(false)
9861}
9862
9863fn is_known_module_request_op(body: &[u8]) -> bool {
9864    serde_json::from_slice::<ControlOpProbe>(body)
9865        .map(|probe| is_module_to_subc_op(&probe.op))
9866        .unwrap_or(false)
9867}
9868
9869fn is_module_to_subc_op(op: &str) -> bool {
9870    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9871}
9872
9873fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9874    debug!(
9875        op = %op,
9876        connection_id = connection_id.get(),
9877        corr,
9878        "control dispatch"
9879    );
9880}
9881
9882fn log_slow_control_dispatch(
9883    dispatch_started_at: Option<StdInstant>,
9884    op: &'static str,
9885    connection_id: ConnectionId,
9886    corr: u64,
9887    route_open_timings: Option<&RouteOpenTimings>,
9888) {
9889    let Some(dispatch_started_at) = dispatch_started_at else {
9890        return;
9891    };
9892    // Use the same monotonic clock as the phase timers and relay deadline.
9893    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9894    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9895        if let Some(timings) = route_open_timings {
9896            warn!(
9897                op = %op,
9898                connection_id = connection_id.get(),
9899                corr,
9900                elapsed_ms = elapsed.as_millis() as u64,
9901                module_id = ?timings.module_id,
9902                principal = %timings.principal,
9903                admission_ms = timings.admission.as_millis() as u64,
9904                project_root_ms = timings.project_root.as_millis() as u64,
9905                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9906                bind_send_ms = timings.bind_send.as_millis() as u64,
9907                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9908                "slow control dispatch"
9909            );
9910            return;
9911        }
9912        warn!(
9913            op = %op,
9914            connection_id = connection_id.get(),
9915            corr,
9916            elapsed_ms = elapsed.as_millis() as u64,
9917            "slow control dispatch"
9918        );
9919    }
9920}
9921
9922/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9923#[cfg(test)]
9924type TestCallerLookup =
9925    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9926
9927/// Every new client operation needs an explicit privilege decision here.
9928fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9929    request.privileged_operation()
9930}
9931
9932trait PrivilegedRequest {
9933    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9934}
9935
9936impl PrivilegedRequest for ClientControlRequest {
9937    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9938        let request = self;
9939        match request {
9940        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9941            Some(PrivilegedOperation::Restart { module_id })
9942        }
9943        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9944            Some(PrivilegedOperation::Swap { module_id })
9945        }
9946        ClientControlRequest::SupervisorReload { module_id } => {
9947            Some(PrivilegedOperation::Reload { module_id })
9948        }
9949        ClientControlRequest::SupervisorRescan { preview } => {
9950            if *preview {
9951                None
9952            } else {
9953                Some(PrivilegedOperation::Rescan)
9954            }
9955        }
9956        // Only the well-formed apply asks for approval. A preview changes
9957        // nothing, and any other combination is refused before it touches
9958        // anything, so prompting the operator for it would ask about a request
9959        // that cannot run.
9960        ClientControlRequest::SupervisorRescanChecked {
9961            preview,
9962            candidate,
9963            expect,
9964        } => (!*preview && candidate.is_none() && expect.is_some())
9965            .then_some(PrivilegedOperation::Rescan),
9966        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9967            Some(PrivilegedOperation::SetEnabled {
9968                module_id,
9969                enabled: *enabled,
9970            })
9971        }
9972        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9973            Some(PrivilegedOperation::ReleaseReserved { module_id })
9974        }
9975        ClientControlRequest::ServerDescribe {}
9976        // The announcement uses the same client admission as supervisor.restart,
9977        // but cannot stop anything itself and needs no operator confirmation.
9978        | ClientControlRequest::DaemonShutdownIntent { .. }
9979        | ClientControlRequest::CatalogList { .. }
9980        | ClientControlRequest::RouteOpen { .. }
9981        | ClientControlRequest::RoutePoll { .. }
9982        | ClientControlRequest::SupervisorList {}
9983        | ClientControlRequest::SupervisorHealth {}
9984        | ClientControlRequest::SupervisorHealthProbe { .. }
9985        | ClientControlRequest::SupervisorRoutes { .. }
9986        | ClientControlRequest::SupervisorProvenance { .. }
9987        | ClientControlRequest::SupervisorStderrTail { .. }
9988        | ClientControlRequest::SupervisorTerminals { .. }
9989        | ClientControlRequest::SupervisorSpawnSnapshot {}
9990        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9991    }
9992    }
9993}
9994
9995fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9996    match request {
9997        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9998        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9999        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
10000        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
10001        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
10002        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
10003        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
10004        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
10005        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
10006        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
10007        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
10008        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
10009        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
10010        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
10011        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
10012        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
10013        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
10014        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
10015        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
10016        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
10017        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
10018    }
10019}
10020
10021/// The caller of one `route.open`, as its `route.open refused` line names it.
10022///
10023/// A connection id alone cannot name a caller after the fact: ids restart at
10024/// every daemon restart, so the same number belongs to different modules
10025/// before and after one. These three fields are what the refused line needs
10026/// to be attributable on its own, and they are rendered with the same helpers
10027/// as the `route.open accepted` line so both directions grep alike.
10028struct RouteOpenCaller {
10029    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
10030    /// when the request presented a consumer identity whose launch nonce did
10031    /// not verify. The claimed module id is never printed as a principal.
10032    principal: String,
10033    /// `none` for an unscoped open; the admitted stamp's label once scope
10034    /// admission issued one; before that, the requested selector's label.
10035    scope: String,
10036    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
10037    /// because it is a string the caller chose.
10038    harness: String,
10039}
10040
10041impl RouteOpenCaller {
10042    fn new(
10043        principal: Option<&Principal>,
10044        scope: Option<&ScopeSelector>,
10045        identity: &BindIdentity,
10046    ) -> Self {
10047        Self {
10048            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
10049            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
10050            harness: bounded_log_text(&identity.harness),
10051        }
10052    }
10053
10054    /// For a refusal that has no parsed request at hand: names whatever the
10055    /// frame still says, and `unknown` where it says nothing parseable.
10056    fn unknown() -> Self {
10057        Self {
10058            principal: "unknown".to_string(),
10059            scope: "unknown".to_string(),
10060            harness: "unknown".to_string(),
10061        }
10062    }
10063}
10064
10065/// Longest client-chosen text (a scope ref, a harness) a route.open log line
10066/// prints before cutting it.
10067const MAX_LOGGED_TEXT_CHARS: usize = 64;
10068
10069/// `value` Debug-quoted, so control characters land escaped and cannot forge
10070/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
10071/// `…` inside the quotes so one request cannot flood the line.
10072fn bounded_log_text(value: &str) -> String {
10073    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
10074    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
10075        bounded.push('…');
10076    }
10077    format!("{bounded:?}")
10078}
10079
10080/// The `scope=` field of the `route.open accepted` line, from the stamp that
10081/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
10082/// so a ref holding control characters cannot forge a log line, and cut to 64
10083/// characters with a trailing `…` to bound the line. The bind proof and the
10084/// scope's attributes never appear.
10085fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
10086    use subc_protocol::scope::ScopeKind;
10087    let kind = match stamp.kind {
10088        ScopeKind::Head => "head",
10089        ScopeKind::Worker => "worker",
10090        ScopeKind::Ephemeral => "ephemeral",
10091        ScopeKind::Federated => "federated",
10092        _ => "unknown",
10093    };
10094    format!(
10095        "{kind}/{}/{}@{}",
10096        principal_label(&stamp.owner),
10097        bounded_log_text(&stamp.scope_ref),
10098        stamp.scope_epoch
10099    )
10100}
10101
10102/// The `scope=` field of a `route.open refused` line for an open refused
10103/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
10104/// The kind is not known yet, so the literal `requested` stands in its place.
10105/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
10106/// owner it has not been checked against the configured modules: a quoted
10107/// owner means the value was never validated. The bind proof never appears.
10108fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
10109    let epoch = selector
10110        .scope_epoch
10111        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
10112    format!(
10113        "requested/{}/{}@{epoch}",
10114        bounded_log_text(&principal_label(&selector.owner)),
10115        bounded_log_text(&selector.scope_ref),
10116    )
10117}
10118
10119fn principal_label(principal: &Principal) -> String {
10120    match principal {
10121        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
10122        Principal::Direct => "direct".to_string(),
10123        other => format!("{other:?}"),
10124    }
10125}
10126
10127fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
10128    match request {
10129        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
10130        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
10131            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
10132        }
10133        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
10134        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
10135        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
10136        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
10137        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
10138            subc_protocol::scope::ROUTE_AUTHORIZE_OP
10139        }
10140        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
10141        _ => "unsupported",
10142    }
10143}
10144
10145fn parse_client_control_request(
10146    body: &[u8],
10147) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
10148    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
10149        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10150            Ok(probe)
10151                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
10152                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10153            {
10154                ControlRequestBodyError::InvalidBody
10155            }
10156            Ok(_) => ControlRequestBodyError::UnknownOp,
10157            Err(_) => ControlRequestBodyError::InvalidBody,
10158        };
10159        (err, classification)
10160    })
10161}
10162
10163fn parse_module_control_request_from_module(
10164    body: &[u8],
10165) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10166    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10167        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10168            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10169            Ok(_) => ControlRequestBodyError::UnknownOp,
10170            Err(_) => ControlRequestBodyError::InvalidBody,
10171        };
10172        (err, classification)
10173    })
10174}
10175
10176#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10177enum ProviderRoleKind {
10178    ToolProvider,
10179    PipelineStage,
10180    ManagementSurface,
10181    InternalService,
10182}
10183
10184fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10185    match role {
10186        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10187        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10188        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10189        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10190    }
10191}
10192
10193fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10194    roles.iter().map(provider_role_kind).collect()
10195}
10196
10197/// Most refused scope records named individually in the log per sync; the
10198/// `refused` count on the accepted line is always complete.
10199const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10200
10201/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10202#[derive(Debug, Default, PartialEq, Eq)]
10203struct ScopeOutcomeCounts {
10204    created: usize,
10205    replaced: usize,
10206    updated: usize,
10207    unchanged: usize,
10208    refused: usize,
10209}
10210
10211impl ScopeOutcomeCounts {
10212    fn of(results: &[ScopeRecordResult]) -> Self {
10213        let mut counts = Self::default();
10214        for result in results {
10215            let slot = match result.outcome {
10216                ScopeRecordOutcome::Created => &mut counts.created,
10217                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10218                ScopeRecordOutcome::Updated => &mut counts.updated,
10219                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10220                ScopeRecordOutcome::Refused => &mut counts.refused,
10221            };
10222            *slot += 1;
10223        }
10224        counts
10225    }
10226}
10227
10228#[cfg(test)]
10229mod scope_outcome_count_tests {
10230    use super::*;
10231
10232    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10233        ScopeRecordResult {
10234            scope_ref: "r".to_string(),
10235            scope_epoch: 1,
10236            outcome,
10237            code: None,
10238            message: None,
10239            version: None,
10240            parent_state: None,
10241        }
10242    }
10243
10244    /// Each outcome lands in its own count, so a refused record can never be
10245    /// hidden inside the total the log already printed.
10246    #[test]
10247    fn every_outcome_is_counted_in_its_own_field() {
10248        let results = [
10249            result(ScopeRecordOutcome::Created),
10250            result(ScopeRecordOutcome::Created),
10251            result(ScopeRecordOutcome::Replaced),
10252            result(ScopeRecordOutcome::Updated),
10253            result(ScopeRecordOutcome::Unchanged),
10254            result(ScopeRecordOutcome::Refused),
10255            result(ScopeRecordOutcome::Refused),
10256            result(ScopeRecordOutcome::Refused),
10257        ];
10258        assert_eq!(
10259            ScopeOutcomeCounts::of(&results),
10260            ScopeOutcomeCounts {
10261                created: 2,
10262                replaced: 1,
10263                updated: 1,
10264                unchanged: 1,
10265                refused: 3,
10266            }
10267        );
10268    }
10269}
10270
10271/// Return whether a catalog change can create a newly violating live route.
10272/// Removing an attested claim is intentionally excluded: it makes fewer routes
10273/// forbidden and therefore must leave the existing route census untouched.
10274fn capability_census_trigger(
10275    old: Option<&CapabilityDeclarations>,
10276    new: Option<&CapabilityDeclarations>,
10277) -> bool {
10278    let old_provides = old
10279        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10280        .unwrap_or_default();
10281    let old_denies = old
10282        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10283        .unwrap_or_default();
10284    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10285        provides: Vec::new(),
10286        requires: Vec::new(),
10287        must_never_reach: Vec::new(),
10288    });
10289
10290    new.provides
10291        .iter()
10292        .any(|capability| !old_provides.contains(capability))
10293        || new
10294            .must_never_reach
10295            .iter()
10296            .any(|capability| !old_denies.contains(capability))
10297}
10298
10299fn catalog_update_frozen_field_message(
10300    registered: &ModuleManifest,
10301    provides: &[ProviderRole],
10302) -> Option<String> {
10303    let old_has_provides = !registered.provides.is_empty();
10304    let new_has_provides = !provides.is_empty();
10305    if old_has_provides != new_has_provides {
10306        return Some(format!(
10307            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10308            registered.module_id
10309        ));
10310    }
10311
10312    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10313        return Some(format!(
10314            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10315            registered.module_id
10316        ));
10317    }
10318
10319    let registered_concurrency = manifest_concurrency(registered);
10320    let mut candidate = registered.clone();
10321    candidate.provides = provides.to_vec();
10322    let candidate_concurrency = manifest_concurrency(&candidate);
10323    if candidate_concurrency != registered_concurrency {
10324        return Some(format!(
10325            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10326            registered.module_id, registered_concurrency, candidate_concurrency
10327        ));
10328    }
10329
10330    // control_ops live beside the manifest in the HELLO body, not inside
10331    // ModuleManifest, so a provides-only catalog.update cannot change them.
10332    None
10333}
10334
10335fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10336    manifest.provides.iter().any(is_routable_role)
10337}
10338
10339/// Returns the routable-provider concurrency subc should enforce for this manifest.
10340///
10341/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10342/// InternalService has no role-specific concurrency field, so it retains the
10343/// existing ModuleManaged default for backward compatibility.
10344fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10345    manifest
10346        .provides
10347        .iter()
10348        .find_map(|provider| match provider {
10349            ProviderRole::ToolProvider { concurrency, .. }
10350            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10351            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10352        })
10353        .unwrap_or(Concurrency::ModuleManaged)
10354}
10355
10356/// True when the manifest carries a ManagementSurface role whose concurrency
10357/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10358/// bytes because the typed manifest deliberately erases that distinction: the
10359/// default exists for wire compatibility, and this probe exists so the default
10360/// stays observable. Any parse irregularity returns false -- the caller only
10361/// logs, and a malformed body already failed registration upstream.
10362fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10363    let has_management_surface = manifest
10364        .provides
10365        .iter()
10366        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10367    if !has_management_surface {
10368        return false;
10369    }
10370    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10371        return false;
10372    };
10373    let Some(provides) = raw
10374        .get("manifest")
10375        .and_then(|manifest| manifest.get("provides"))
10376        .and_then(serde_json::Value::as_array)
10377    else {
10378        return false;
10379    };
10380    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10381    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10382    // against the management_surface_manifest_without_concurrency golden, not
10383    // recalled (the externally-tagged guess was this function's first bug).
10384    provides.iter().any(|role| {
10385        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10386            && role.get("concurrency").is_none()
10387    })
10388}
10389
10390fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10391    if peer_version != PROTOCOL_VERSION {
10392        return Err(format!(
10393            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10394        ));
10395    }
10396    Ok(PROTOCOL_VERSION)
10397}
10398
10399fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10400    Frame::build_with_version(
10401        response_version(frame),
10402        FrameType::Pong,
10403        frame.header.flags,
10404        0,
10405        0,
10406        frame.header.corr,
10407        Vec::new(),
10408    )
10409    .map_err(RouterError::FrameBuild)
10410}
10411
10412pub(crate) fn control_error_frame(
10413    frame: &Frame,
10414    code: &'static str,
10415    message: impl Into<String>,
10416) -> Result<Frame, RouterError> {
10417    control_error_body_frame(
10418        frame,
10419        ErrorBody {
10420            code: code.to_string(),
10421            message: message.into(),
10422            detail: None,
10423        },
10424    )
10425}
10426
10427/// A channel-0 ERROR for a refusal the daemon decided itself: every
10428/// route.open refusal, the drain `module_reloading` and scope-change/end
10429/// bodies, spawn-subscription and supervisor refusals. Carries the
10430/// daemon-origin bit, which is what lets a client treat `module_reloading`
10431/// as proof that its request never reached a module. Response, push,
10432/// goodbye and relay-request frames keep the plain control flags in their
10433/// own builders.
10434pub(crate) fn control_error_body_frame(
10435    frame: &Frame,
10436    error: ErrorBody,
10437) -> Result<Frame, RouterError> {
10438    control_error_frame_with_flags(frame, error, daemon_error_flags())
10439}
10440
10441/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10442/// refused route.bind answered as a route.open refusal, or a refused
10443/// module-control RPC. Plain control flags — the code and message are
10444/// module-chosen, so the frame must not claim daemon authorship, even when
10445/// the module picks a daemon code like `module_reloading`.
10446fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10447    control_error_frame_with_flags(frame, error, control_flags())
10448}
10449
10450fn control_error_frame_with_flags(
10451    frame: &Frame,
10452    error: ErrorBody,
10453    flags: Flags,
10454) -> Result<Frame, RouterError> {
10455    let body = serde_json::to_vec(&error).map_err(|err| {
10456        RouterError::backend(
10457            0,
10458            frame.header.corr,
10459            format!("failed to encode control ERROR: {err}"),
10460        )
10461    })?;
10462
10463    Frame::build_with_version(
10464        response_version(frame),
10465        FrameType::Error,
10466        flags,
10467        0,
10468        0,
10469        frame.header.corr,
10470        body,
10471    )
10472    .map_err(RouterError::FrameBuild)
10473}
10474
10475pub(crate) fn control_response_body_frame<T: Serialize>(
10476    frame: &Frame,
10477    reply: &T,
10478    label: &'static str,
10479) -> Result<Frame, RouterError> {
10480    let body = serde_json::to_vec(reply).map_err(|err| {
10481        RouterError::backend(
10482            0,
10483            frame.header.corr,
10484            format!("failed to encode {label}: {err}"),
10485        )
10486    })?;
10487
10488    Frame::build_with_version(
10489        response_version(frame),
10490        FrameType::Response,
10491        control_flags(),
10492        0,
10493        0,
10494        frame.header.corr,
10495        body,
10496    )
10497    .map_err(RouterError::FrameBuild)
10498}
10499
10500/// Map a forwarding failure to the wire code a client sees.
10501///
10502/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10503/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10504/// chosen here decides whether a caller retries or gives up.
10505///
10506/// That makes attribution the load-bearing property, not merely having a code. A
10507/// permanent fault published as a retryable one produces a fleet-wide retry storm
10508/// against something that can never recover; a transient fault published as
10509/// permanent gives up on work that would have succeeded. Both look correct in a
10510/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10511/// the mapping per variant rather than merely asserting that some code exists.
10512///
10513/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10514/// two codes on the same side of the boundary passes it. Measured rather than
10515/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10516/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10517/// a test named for something else that happens to assert the string.
10518///
10519/// That accidental coverage is deliberately left alone rather than promoted to a
10520/// named test, because it guards a property this function does not promise.
10521/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10522/// specific code within a class, so identity is free to change and only the
10523/// partition is a contract. Splitting it out would assert a guarantee nothing
10524/// depends on — and a suite that promises more than the code does is the harder
10525/// thing to correct later, because the next reader cannot tell which assertions
10526/// are load-bearing.
10527///
10528/// Pin identity here the moment a consumer branches on a specific code.
10529/// The spawn a HELLO would register as and the provider declarations it
10530/// requests, carried from the HELLO's checks to the point the registry
10531/// accepts it.
10532struct HelloAuthority {
10533    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10534    requested: ProviderDeclarations,
10535    /// Whether admitting this HELLO froze the spawn's requested declarations,
10536    /// so a refusal after admission undoes that freeze and no other.
10537    froze: std::sync::atomic::AtomicBool,
10538}
10539
10540fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10541    match err {
10542        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10543        ForwardingError::NoModuleConnection => "target_unavailable",
10544        ForwardingError::ModuleReloading { .. } => "module_reloading",
10545        ForwardingError::ClientRouteChannelExhausted { .. }
10546        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10547        ForwardingError::StaleModuleEndpoint
10548        | ForwardingError::UnknownReservation { .. }
10549        | ForwardingError::ConnectionClosing { .. }
10550        | ForwardingError::ClientEgressClosed { .. }
10551        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10552        // Only a swap candidate's registration can produce this, and it means
10553        // exactly what a second active HELLO for a live id means.
10554        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10555        ForwardingError::RelayCorrelationExhausted
10556        | ForwardingError::RouteOpenBuild(_)
10557        | ForwardingError::Poisoned => "forwarding_error",
10558    }
10559}
10560
10561fn response_version(frame: &Frame) -> u8 {
10562    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10563        frame.header.ver
10564    } else {
10565        PROTOCOL_VERSION
10566    }
10567}
10568
10569pub(crate) fn control_flags() -> Flags {
10570    Flags::new(false, Priority::Passive, false)
10571}
10572
10573/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10574/// channel. The target is the module (a client never saw the route), so this
10575/// takes the module path: delivered late rather than dropped when the module's
10576/// queue is momentarily full, and never closing its connection.
10577fn send_goodbye_target_best_effort(
10578    counters: &DaemonCounters,
10579    target: &GoodbyeTarget,
10580    context: &'static str,
10581) {
10582    let Ok(frame) = Frame::build_with_version(
10583        target.negotiated_ver,
10584        FrameType::Goodbye,
10585        control_flags(),
10586        target.channel,
10587        target.epoch,
10588        0,
10589        Vec::new(),
10590    ) else {
10591        return;
10592    };
10593    crate::forwarding::send_module_route_goodbye(
10594        counters,
10595        &target.sink,
10596        frame,
10597        target.module_id.as_deref(),
10598        context,
10599    );
10600}
10601
10602fn route_close_reason_for_opener(
10603    reason: RouteCloseReason,
10604    accepts_close_reasons: Option<&[String]>,
10605) -> RouteCloseReason {
10606    if reason == RouteCloseReason::AuthorityChanged
10607        && !accepts_close_reasons
10608            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10609    {
10610        // Older readers forbid reopening for unknown reasons. Reload already
10611        // permits reopening and, like an authority change, requires a new bind.
10612        RouteCloseReason::Reload
10613    } else {
10614        reason
10615    }
10616}
10617
10618pub(crate) fn send_route_control_pushes(
10619    forwarding: &ForwardingTable,
10620    routes: Vec<EndpointRoute>,
10621    push: ClientControlPush,
10622) {
10623    let reason = match &push {
10624        ClientControlPush::RouteClosing { reason, .. }
10625        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10626    };
10627    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10628    for route in routes {
10629        let recipient_reason =
10630            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10631        let target = route.goodbye_target;
10632        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10633            existing.connection_id == target.connection_id && *reason == recipient_reason
10634        }) {
10635            debug_assert_eq!(
10636                existing.negotiated_ver, target.negotiated_ver,
10637                "one connection cannot negotiate multiple frame versions"
10638            );
10639            if !channels.contains(&target.channel) {
10640                channels.push(target.channel);
10641            }
10642            continue;
10643        }
10644        let channel = target.channel;
10645        targets.push((target, recipient_reason, vec![channel]));
10646    }
10647    for (target, recipient_reason, mut channels) in targets {
10648        channels.sort_unstable();
10649        let mut push = push.clone();
10650        match &mut push {
10651            ClientControlPush::RouteClosing {
10652                channels: covered,
10653                reason,
10654                ..
10655            }
10656            | ClientControlPush::RouteClosed {
10657                channels: covered,
10658                reason,
10659                ..
10660            } => {
10661                *covered = channels;
10662                *reason = recipient_reason;
10663            }
10664        }
10665        let body = match serde_json::to_vec(&push) {
10666            Ok(body) => body,
10667            Err(err) => {
10668                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10669                continue;
10670            }
10671        };
10672        let frame = match Frame::build_with_version(
10673            target.negotiated_ver,
10674            FrameType::Push,
10675            control_flags(),
10676            0,
10677            0,
10678            0,
10679            body.clone(),
10680        ) {
10681            Ok(frame) => frame,
10682            Err(err) => {
10683                warn!(
10684                    route_channel = target.channel,
10685                    error = %err,
10686                    "failed to build route lifecycle control PUSH frame"
10687                );
10688                continue;
10689            }
10690        };
10691        if let Err(err) = target.sink.try_send(frame) {
10692            if target.close_on_delivery_failure() {
10693                warn!(
10694                    target_connection_id = target.connection_id.get(),
10695                    route_channel = target.channel,
10696                    error = %err,
10697                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10698                );
10699                let _ = forwarding.escalate_client_delivery_failure(
10700                    target.connection_id,
10701                    target.channel,
10702                    target.epoch,
10703                    CloseReason::new(
10704                        "route_lifecycle_push_delivery_failed",
10705                        format!(
10706                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10707                            target.channel
10708                        ),
10709                    ),
10710                    crate::forwarding::UndeliveredFrame {
10711                        module_id: target.module_id.as_deref(),
10712                        sink: &target.sink,
10713                    },
10714                );
10715            }
10716        }
10717    }
10718}
10719
10720#[cfg(test)]
10721mod tests {
10722    include!("control/agent_commands_tests.rs");
10723    include!("control/supervisor_health_vectors_tests.rs");
10724    include!("control/resource_revision_tests.rs");
10725    include!("control/route_open_recovery_tests.rs");
10726    #[tokio::test]
10727    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10728        let registry = Arc::new(Registry::default());
10729        let handler = ControlHandler::new(registry);
10730        assert_eq!(
10731            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10732            None
10733        );
10734        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10735        hello_via_sink(
10736            &handler,
10737            &ctx,
10738            &mut rx,
10739            hello_frame("daemon", PROTOCOL_VERSION, 1),
10740        )
10741        .await;
10742        assert_eq!(
10743            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10744            Some("daemon".into())
10745        );
10746        assert_eq!(
10747            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10748            None
10749        );
10750        assert_eq!(
10751            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10752            None,
10753            "a registered module is not necessarily supervised"
10754        );
10755        assert_eq!(
10756            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10757            None,
10758            "aggregate provenance has no single target"
10759        );
10760        assert_eq!(
10761            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10762            None
10763        );
10764    }
10765
10766    mod peer_manifest {
10767        include!("peer_manifest_tests.rs");
10768    }
10769    mod catalog_declarations {
10770        include!("control/catalog_tests.rs");
10771    }
10772    mod activity_read {
10773        include!("activity_read_tests.rs");
10774    }
10775
10776    mod lifecycle_activity {
10777        include!("control_lifecycle_tests.rs");
10778    }
10779    #[cfg(unix)]
10780    #[tokio::test]
10781    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10782        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10783        let path = dir.join("subc.jsonc");
10784        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10785            "program":"/bin/sleep","args":["60"],"protocol":"none",
10786            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10787        }}}).to_string()).unwrap();
10788        let mut configured = crate::daemon_config::load(&path)
10789            .unwrap()
10790            .unwrap()
10791            .modules
10792            .pop()
10793            .unwrap();
10794        let registry = std::sync::Arc::new(crate::Registry::default());
10795        let handle = crate::SupervisorHandle::new();
10796        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10797            .with_handle(handle.clone());
10798        let module = supervisor
10799            .supervise_configured_with_health(
10800                configured.module_spec(),
10801                true,
10802                configured.health.clone(),
10803                None,
10804                configured.restart,
10805            )
10806            .unwrap();
10807        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10808        let before = module.status().unwrap().pid;
10809        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10810        configured.health.cadence = std::time::Duration::from_secs(3600);
10811        let health_only = handler
10812            .reconcile_supervised_modules(
10813                &supervisor,
10814                vec![configured.clone()],
10815                false,
10816                Principal::Direct,
10817            )
10818            .await
10819            .unwrap();
10820        assert!(
10821            health_only.0.changed_pending_reload.is_empty(),
10822            "health policy is already applied live"
10823        );
10824        assert_eq!(module.status().unwrap().pid, before);
10825        assert_eq!(
10826            module.configuration().unwrap().1.http,
10827            configured.health.http
10828        );
10829        configured.args = vec!["61".into()];
10830        let launch = handler
10831            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10832            .await
10833            .unwrap();
10834        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10835        assert_eq!(
10836            module.status().unwrap().pid,
10837            before,
10838            "a launch edit is stored until reload"
10839        );
10840        module.drain().await.unwrap();
10841    }
10842    use cortexkit_test_support::ScratchDir;
10843    use std::{
10844        collections::BTreeMap,
10845        fmt,
10846        path::PathBuf,
10847        sync::{Arc, Mutex},
10848        time::Duration,
10849    };
10850
10851    use serde_json::{json, Value};
10852    use subc_protocol::{
10853        manifest::{
10854            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10855            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10856        },
10857        session::HealthStatus,
10858        FrameType,
10859    };
10860
10861    use super::*;
10862    use crate::{
10863        forwarding::{DataRoute, DataRouteState},
10864        registry::ChannelState,
10865        router::FrameSink,
10866        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10867        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10868        RouteCtx, Router,
10869    };
10870    use tokio::{
10871        sync::mpsc,
10872        time::{sleep, Instant},
10873    };
10874    use tracing::{
10875        field::{Field, Visit},
10876        Event, Subscriber,
10877    };
10878    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10879
10880    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10881    ///
10882    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10883    /// is only populated for `tests/*.rs` integration test binaries -- this file
10884    /// compiles as part of the library target, which gets neither. The binary
10885    /// lives in the profile folder this test was built into,
10886    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10887    /// from the test's own path.
10888    ///
10889    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10890    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10891    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10892    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10893    /// `NotFound`, which reads as a broken test rather than an unbuilt
10894    /// dependency -- so state the cause and the remedy instead. Deliberately a
10895    /// panic and not a silent skip: a test that quietly passes when it could not
10896    /// run is worse than one that fails, because it reports health it never
10897    /// verified.
10898    fn fake_aft_stub_path() -> PathBuf {
10899        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10900        assert!(
10901            path.exists(),
10902            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10903             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10904            path.display()
10905        );
10906        path
10907    }
10908
10909    /// Whether clients retry `code` in place: the predicate itself, never a copy
10910    /// of its set. A copied list breaks silently when a code is added to or
10911    /// removed from the real one, and a stale copy here would let exactly the
10912    /// failure this test exists to catch pass.
10913    fn client_retries(code: &str) -> bool {
10914        subc_protocol::error_codes::is_retryable_route_open(code)
10915    }
10916
10917    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10918    /// of failure is worse than publishing none. A permanent fault dressed as
10919    /// retryable makes every client in the fleet retry forever against something
10920    /// that cannot recover; a transient fault dressed as permanent abandons work
10921    /// that would have succeeded.
10922    ///
10923    /// Asserting "a code exists" cannot catch either, because the string is free
10924    /// to say anything. This enumerates every variant and pins which side of the
10925    /// retry boundary it lands on, so a new variant must be classified here
10926    /// deliberately rather than inheriting whichever arm it was appended to.
10927    #[test]
10928    fn retryability_of_forwarding_codes_matches_the_failure() {
10929        // Transient by nature: the target is booting, reloading, or its endpoint
10930        // was swapped mid-flight. Retrying is how these resolve.
10931        let transient = [
10932            ForwardingError::NoModuleConnection,
10933            ForwardingError::ModuleReloading {
10934                module_id: "m".into(),
10935            },
10936            ForwardingError::StaleModuleEndpoint,
10937            ForwardingError::UnknownReservation {
10938                client_channel: 1,
10939                module_channel: 1,
10940            },
10941            ForwardingError::ConnectionClosing {
10942                connection_id: ConnectionId::new(1),
10943            },
10944            ForwardingError::ClientEgressClosed {
10945                connection_id: ConnectionId::new(1),
10946            },
10947            ForwardingError::ModuleEgressUnavailable {
10948                connection_id: ConnectionId::new(1),
10949            },
10950        ];
10951        for err in transient {
10952            let code = forwarding_error_code(&err);
10953            assert!(
10954                client_retries(code),
10955                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10956            );
10957        }
10958
10959        // Not fixed by retrying. Channel and correlation exhaustion need the
10960        // caller to close routes, and a poisoned lock is a daemon that cannot
10961        // recover at all — the worst thing to advertise as retryable, since every
10962        // client would storm a daemon that will never answer.
10963        let permanent = [
10964            ForwardingError::ConnectionRoleConflict {
10965                connection_id: ConnectionId::new(1),
10966            },
10967            ForwardingError::ClientRouteChannelExhausted {
10968                connection_id: ConnectionId::new(1),
10969            },
10970            ForwardingError::ModuleRouteChannelExhausted {
10971                endpoint: ModuleEndpointId {
10972                    connection_id: ConnectionId::new(1),
10973                    generation: 1,
10974                },
10975            },
10976            ForwardingError::RelayCorrelationExhausted,
10977            ForwardingError::RouteOpenBuild("x".into()),
10978            ForwardingError::Poisoned,
10979        ];
10980        for err in permanent {
10981            let code = forwarding_error_code(&err);
10982            assert!(
10983                !client_retries(code),
10984                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10985            );
10986        }
10987    }
10988
10989    /// The principal is the daemon's answer to "who is calling", and modules
10990    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10991    /// plexus gates connector invocation. So a stamp is an authorization input in
10992    /// another process, not a label — and both possible answers SUCCEED, which is
10993    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10994    /// first-party capability to something that never proved it; a supervised one
10995    /// stamped `Direct` silently strips a module of capability it is entitled to.
10996    ///
10997    /// Neither shows up in a test that only checks the bind succeeded. Before this
10998    /// test the only coverage was accidental —
10999    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
11000    /// stamped principal on its way past, so narrowing that wire-shape test to its
11001    /// stated subject would have deleted the last assertion on this value. It
11002    /// still asserts the stamp, which is now redundancy rather than the only
11003    /// guard: both fail under the same mutation, and this one names the reason.
11004    /// SCOPE: this handler's supervisor has spawned nothing, so
11005    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
11006    /// is unreachable here. Both assertions below are refusals, and a mutant that
11007    /// refuses everything would satisfy them.
11008    ///
11009    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
11010    /// spawns a supervised consumer, reads its live nonce, and asserts the module
11011    /// observed `principal.kind == "reserved"` carrying that module_id — verified
11012    /// at source rather than assumed, since a citation is a claim about another
11013    /// file and ages like one. Recorded because a harness that structurally
11014    /// cannot reach an arm reports "none" for that arm identically to one that
11015    /// covers it and found nothing.
11016    #[tokio::test]
11017    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
11018        let handler = ControlHandler::default();
11019        let frame =
11020            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
11021
11022        // Absent consumer_identity is the ordinary case: a human at a terminal, or
11023        // any process holding the connection file. Nothing was proved, so nothing
11024        // may be granted beyond the unattested floor.
11025        let stamped = handler
11026            .route_open_principal(ConnectionId::new(1), &frame, None)
11027            .unwrap()
11028            .unwrap();
11029        assert_eq!(
11030            stamped,
11031            Principal::Direct,
11032            "a caller that proved nothing must not be stamped as a supervised module"
11033        );
11034
11035        // A claimed module_id with a nonce no supervised child was given is a
11036        // forgery attempt, not a weaker caller: it must be REFUSED rather than
11037        // quietly demoted to Direct, or an impersonation attempt looks identical
11038        // to an ordinary unattested connection.
11039        let forged = handler
11040            .route_open_principal(
11041                ConnectionId::new(1),
11042                &frame,
11043                Some(ConsumerIdentity {
11044                    module_id: "aft".to_string(),
11045                    launch_nonce: "not-a-real-nonce".to_string(),
11046                }),
11047            )
11048            .unwrap();
11049        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
11050        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
11051    }
11052
11053    /// The test above hands `route_open_principal` an identity it built itself,
11054    /// which proves the stamping rule and nothing about where the identity comes
11055    /// from. The real producer is a wire body, and the two are joined by a serde
11056    /// field name that nothing else asserts.
11057    ///
11058    /// That join fails quietly in one specific way: an unrecognised key is simply
11059    /// absent after parsing, so a renamed or misspelled `consumer_identity`
11060    /// yields `None` and every supervised module silently drops to `Direct`.
11061    /// Capability-wise that is the safe direction, but it surfaces far from its
11062    /// cause — as a module mysteriously refused bash — and it would pass every
11063    /// test that builds its own input.
11064    ///
11065    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
11066    /// would break every client the moment the daemon gains a field, trading a
11067    /// quiet demotion for a hard refusal on additive change. Asserting the join
11068    /// instead means a rename breaks a test here rather than the fleet.
11069    #[test]
11070    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
11071        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"}}"#;
11072        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
11073        let ClientControlRequest::RouteOpen {
11074            consumer_identity, ..
11075        } = parsed
11076        else {
11077            panic!("route.open body must parse as RouteOpen");
11078        };
11079        assert_eq!(
11080            consumer_identity,
11081            Some(ConsumerIdentity {
11082                module_id: "aft".to_string(),
11083                launch_nonce: "n".to_string(),
11084            }),
11085            "the wire field name must reach the value route_open_principal reads"
11086        );
11087    }
11088
11089    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
11090        ModuleManifest::builder(module_id, "0.1.0")
11091            .protocol_ver(protocol_ver)
11092            .provides(vec![ProviderRole::ToolProvider {
11093                tools: vec![Tool {
11094                    name: "read".to_string(),
11095                    description: None,
11096                    execution_mode: ExecutionMode::Pure,
11097                    schema: json!({"type": "object"}),
11098                }],
11099                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
11100                concurrency: Concurrency::ModuleManaged,
11101                emits_push: true,
11102                sub_supervises: true,
11103            }])
11104            .build()
11105    }
11106
11107    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
11108        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
11109    }
11110
11111    fn hello_frame_with_control_ops(
11112        module_id: &str,
11113        protocol_ver: u8,
11114        corr: u64,
11115        control_ops: Option<Vec<String>>,
11116    ) -> Frame {
11117        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
11118    }
11119
11120    fn hello_frame_with_nonce(
11121        module_id: &str,
11122        protocol_ver: u8,
11123        corr: u64,
11124        launch_nonce: Option<&str>,
11125    ) -> Frame {
11126        hello_frame_full(
11127            module_id,
11128            protocol_ver,
11129            corr,
11130            None,
11131            launch_nonce.map(ToOwned::to_owned),
11132        )
11133    }
11134
11135    fn hello_frame_full(
11136        module_id: &str,
11137        protocol_ver: u8,
11138        corr: u64,
11139        control_ops: Option<Vec<String>>,
11140        launch_nonce: Option<String>,
11141    ) -> Frame {
11142        let body = serde_json::to_vec(&ModuleHelloBody {
11143            manifest: manifest(module_id, protocol_ver),
11144            protocol_ver,
11145            control_ops,
11146            launch_nonce,
11147        })
11148        .unwrap();
11149        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11150    }
11151
11152    fn hello_frame_with_rich_ui(
11153        module_id: &str,
11154        protocol_ver: u8,
11155        corr: u64,
11156        launch_nonce: Option<&str>,
11157        rich_ui: Value,
11158    ) -> Frame {
11159        let mut body = serde_json::to_value(ModuleHelloBody {
11160            manifest: manifest(module_id, protocol_ver),
11161            protocol_ver,
11162            control_ops: None,
11163            launch_nonce: launch_nonce.map(str::to_string),
11164        })
11165        .unwrap();
11166        body["manifest"]["rich_ui"] = rich_ui;
11167        Frame::build(
11168            FrameType::Hello,
11169            control_flags(),
11170            0,
11171            0,
11172            corr,
11173            serde_json::to_vec(&body).unwrap(),
11174        )
11175        .unwrap()
11176    }
11177
11178    fn non_routable_hello_frame_with_control_ops(
11179        module_id: &str,
11180        corr: u64,
11181        control_ops: Option<Vec<String>>,
11182    ) -> Frame {
11183        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11184        manifest.provides.clear();
11185        let body = serde_json::to_vec(&ModuleHelloBody {
11186            manifest,
11187            protocol_ver: PROTOCOL_VERSION,
11188            control_ops,
11189            launch_nonce: None,
11190        })
11191        .unwrap();
11192        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11193    }
11194
11195    fn capability_grammar_hello_frame(
11196        capabilities: Value,
11197        runtime_computed: Option<Value>,
11198        corr: u64,
11199    ) -> Frame {
11200        let mut body = serde_json::to_value(ModuleHelloBody {
11201            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11202            protocol_ver: PROTOCOL_VERSION,
11203            control_ops: None,
11204            launch_nonce: None,
11205        })
11206        .expect("HELLO body serializes");
11207        body["manifest"]["capabilities"] = capabilities;
11208        if let Some(runtime_computed) = runtime_computed {
11209            body["runtime_computed"] = runtime_computed;
11210        }
11211        Frame::build(
11212            FrameType::Hello,
11213            control_flags(),
11214            0,
11215            0,
11216            corr,
11217            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11218        )
11219        .expect("HELLO frame builds")
11220    }
11221
11222    fn channel_request(channel: u16, corr: u64) -> Frame {
11223        Frame::build(
11224            FrameType::Request,
11225            Flags::new(true, Priority::Interactive, false),
11226            channel,
11227            0,
11228            corr,
11229            b"opaque".to_vec(),
11230        )
11231        .unwrap()
11232    }
11233
11234    fn route_ctx(
11235        connection_id: ConnectionId,
11236    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11237        let (tx, rx) = mpsc::channel(8);
11238        (
11239            RouteCtx {
11240                connection_id,
11241                egress: FrameSink::new(tx),
11242            },
11243            rx,
11244        )
11245    }
11246
11247    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11248        serde_json::from_slice(&frame.body).unwrap()
11249    }
11250
11251    /// Register a module over a connection that has a sink and return the
11252    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11253    /// module's own sink rather than returning it as a reply, so the ack is
11254    /// taken off `rx` here and whatever the test reads next is what followed it.
11255    async fn hello_via_sink(
11256        handler: &ControlHandler,
11257        ctx: &RouteCtx,
11258        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11259        hello: Frame,
11260    ) -> Frame {
11261        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11262        assert!(
11263            replies.is_empty(),
11264            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11265        );
11266        let ack = rx
11267            .try_recv()
11268            .expect("HELLO_ACK is queued on the module sink")
11269            .frame;
11270        assert_eq!(ack.header.ty, FrameType::HelloAck);
11271        ack
11272    }
11273
11274    fn parse_error(frame: &Frame) -> Value {
11275        serde_json::from_slice(&frame.body).unwrap()
11276    }
11277
11278    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11279        serde_json::from_slice(&frame.body).unwrap()
11280    }
11281
11282    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11283        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11284            route_channel,
11285            route_epoch: 0,
11286            kind,
11287        })
11288        .unwrap();
11289        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11290    }
11291
11292    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11293        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11294            module_id: module_id.to_string(),
11295        })
11296        .unwrap();
11297        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11298    }
11299
11300    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11301        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11302    }
11303
11304    // Exercise retired opener fields without putting them back in BindIdentity.
11305    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11306        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11307        let mut frame = route_open_frame(corr, module_id, root);
11308        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11309        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11310        frame.body = serde_json::to_vec(&body).unwrap();
11311        frame
11312    }
11313
11314    fn route_open_frame_with_consumer_capabilities(
11315        corr: u64,
11316        module_id: &str,
11317        _project_root: ScratchDir,
11318        consumer_capabilities: Option<Vec<String>>,
11319    ) -> Frame {
11320        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11321            busy_refusals: None,
11322            target: RouteTarget::ToolProvider {
11323                module_id: module_id.to_string(),
11324            },
11325            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11326            consumer_identity: None,
11327            consumer_capabilities,
11328            role_versions: None,
11329            admission_facts: None,
11330            scope: None,
11331        })
11332        .unwrap();
11333        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11334    }
11335
11336    fn route_open_frame_with_role_versions(
11337        corr: u64,
11338        module_id: &str,
11339        _project_root: ScratchDir,
11340        role_versions: Option<BTreeMap<String, String>>,
11341    ) -> Frame {
11342        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11343            busy_refusals: None,
11344            target: RouteTarget::ToolProvider {
11345                module_id: module_id.to_string(),
11346            },
11347            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11348            consumer_identity: None,
11349            consumer_capabilities: None,
11350            role_versions,
11351            admission_facts: None,
11352            scope: None,
11353        })
11354        .unwrap();
11355        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11356    }
11357
11358    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11359        entries
11360            .iter()
11361            .map(|(role, version)| (role.to_string(), version.to_string()))
11362            .collect()
11363    }
11364
11365    fn route_open_frame_with_admission_facts(
11366        corr: u64,
11367        module_id: &str,
11368        _project_root: ScratchDir,
11369        consumer_identity: Option<subc_control::ConsumerIdentity>,
11370        facts: Option<Value>,
11371    ) -> Frame {
11372        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11373            busy_refusals: None,
11374            target: RouteTarget::ToolProvider {
11375                module_id: module_id.to_string(),
11376            },
11377            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11378            consumer_identity,
11379            consumer_capabilities: None,
11380            role_versions: None,
11381            admission_facts: facts,
11382            scope: None,
11383        })
11384        .unwrap();
11385        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11386    }
11387
11388    #[derive(Clone, Default)]
11389    struct EventCapture {
11390        events: Arc<Mutex<Vec<CapturedEvent>>>,
11391    }
11392
11393    #[derive(Clone, Debug)]
11394    struct CapturedEvent {
11395        target: String,
11396        level: tracing::Level,
11397        fields: BTreeMap<String, String>,
11398    }
11399
11400    impl EventCapture {
11401        fn events(&self) -> Vec<CapturedEvent> {
11402            self.events.lock().unwrap().clone()
11403        }
11404    }
11405
11406    impl<S> Layer<S> for EventCapture
11407    where
11408        S: Subscriber,
11409    {
11410        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11411            let mut visitor = EventFieldVisitor::default();
11412            event.record(&mut visitor);
11413            self.events.lock().unwrap().push(CapturedEvent {
11414                target: event.metadata().target().to_string(),
11415                level: *event.metadata().level(),
11416                fields: visitor.fields,
11417            });
11418        }
11419    }
11420
11421    #[derive(Default)]
11422    struct EventFieldVisitor {
11423        fields: BTreeMap<String, String>,
11424    }
11425
11426    impl Visit for EventFieldVisitor {
11427        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11428            self.fields
11429                .insert(field.name().to_string(), format!("{value:?}"));
11430        }
11431    }
11432
11433    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11434        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11435            status,
11436            detail: Some("warming".to_string()),
11437            metrics: Some(json!({"queue_depth": 3})),
11438        })
11439        .unwrap();
11440        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11441    }
11442
11443    fn route_bind_ack(corr: u64) -> Frame {
11444        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11445        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11446    }
11447
11448    fn unique_project_root(label: &str) -> ScratchDir {
11449        ScratchDir::new(label)
11450    }
11451
11452    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11453        match parse_route_poll(frame) {
11454            ClientControlResponse::RoutePoll {
11455                status: None,
11456                live: Some(live),
11457                ..
11458            } => assert_eq!(live, expected_live),
11459            other => panic!("unexpected route.poll response: {other:?}"),
11460        }
11461    }
11462
11463    fn bind_liveness_route(
11464        registry: &Registry,
11465        forwarding: &ForwardingTable,
11466        module_id: &str,
11467    ) -> (RouteCtx, u16, u32) {
11468        let module_connection = ConnectionId::new(101);
11469        let client_connection = ConnectionId::new(202);
11470        let registration = registry
11471            .register_with_control_ops(
11472                manifest(module_id, PROTOCOL_VERSION),
11473                PROTOCOL_VERSION,
11474                module_connection,
11475                module_baseline_control_ops(),
11476            )
11477            .unwrap();
11478        let (module_tx, _module_rx) = mpsc::channel(8);
11479        let endpoint = forwarding
11480            .register_module_connection(
11481                module_connection,
11482                module_id.to_string(),
11483                PROTOCOL_VERSION,
11484                manifest_concurrency(&registration.manifest),
11485                FrameSink::new(module_tx),
11486            )
11487            .unwrap();
11488        let (client_ctx, _client_rx) = route_ctx(client_connection);
11489        let pending = forwarding
11490            .begin_route_bind_relay_for_test(
11491                client_connection,
11492                client_ctx.egress.clone(),
11493                1,
11494                module_id,
11495            )
11496            .unwrap();
11497        assert_eq!(pending.endpoint, endpoint);
11498        let route_channel = pending.client_channel;
11499        let route_epoch = pending.client_epoch;
11500        forwarding
11501            .complete_pending_relay(
11502                module_connection,
11503                pending.corr,
11504                RouteBindRelayOutcome::Accepted,
11505            )
11506            .unwrap();
11507        (client_ctx, route_channel, route_epoch)
11508    }
11509
11510    struct FakeProcessLiveness {
11511        live: Option<bool>,
11512    }
11513
11514    impl ModuleProcessLiveness for FakeProcessLiveness {
11515        fn process_live(&self, _module_id: &str) -> Option<bool> {
11516            self.live
11517        }
11518    }
11519
11520    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11521    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11522    {
11523        let registry = Arc::new(Registry::default());
11524        let supervisor_handle = SupervisorHandle::new();
11525        let supervisor = Supervisor::new_for_test(
11526            Arc::clone(&registry),
11527            RestartPolicy::new(1, Duration::from_millis(10)),
11528        )
11529        .with_handle(supervisor_handle.clone());
11530        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11531        let module = supervisor
11532            .spawn(ModuleSpec {
11533                script: None,
11534                carry_containment: false,
11535                module_id: "stderr-tail-wire".to_string(),
11536                program: fake_aft_stub_path(),
11537                args: Vec::new(),
11538                env: vec![
11539                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11540                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11541                ],
11542                reserved: false,
11543                reserved_prefixes: Vec::new(),
11544                protocol: ModuleProtocol::Subc,
11545                overlap: Default::default(),
11546            })
11547            .unwrap();
11548
11549        let deadline = Instant::now() + Duration::from_secs(5);
11550        loop {
11551            let tail = module.stderr_tail(None, None);
11552            if tail
11553                .entries
11554                .iter()
11555                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11556                && tail.entries.iter().any(|entry| {
11557                    matches!(
11558                        entry,
11559                        TailEntry::Line {
11560                            truncated: true,
11561                            ..
11562                        }
11563                    )
11564                })
11565            {
11566                break;
11567            }
11568            assert!(
11569                Instant::now() < deadline,
11570                "module did not produce a truncated line and restart boundary: {tail:?}"
11571            );
11572            sleep(Duration::from_millis(10)).await;
11573        }
11574
11575        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11576        let request = ClientControlRequest::SupervisorStderrTail {
11577            module_id: "stderr-tail-wire".to_string(),
11578            max_lines: None,
11579            max_bytes: None,
11580        };
11581        let frame = Frame::build(
11582            FrameType::Request,
11583            control_flags(),
11584            0,
11585            0,
11586            1,
11587            serde_json::to_vec(&request).unwrap(),
11588        )
11589        .unwrap();
11590        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11591        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11592        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11593            serde_json::from_slice(&responses[0].body).unwrap()
11594        else {
11595            panic!("expected supervisor.stderr_tail response");
11596        };
11597
11598        assert!(
11599            tail.entries
11600                .iter()
11601                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11602            "the control response lost the restart boundary"
11603        );
11604        let Some(StderrTailEntry::Line {
11605            text,
11606            truncated,
11607            at_ms,
11608        }) = tail.entries.iter().find(|entry| {
11609            matches!(
11610                entry,
11611                StderrTailEntry::Line {
11612                    truncated: true,
11613                    ..
11614                }
11615            )
11616        })
11617        else {
11618            panic!("the control response lost the truncated line");
11619        };
11620        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11621        assert!(*truncated);
11622        assert!(
11623            at_ms.is_some(),
11624            "the control response lost the line's capture time"
11625        );
11626    }
11627
11628    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11629    /// read done on the worker thread would stall every other task until it
11630    /// finished; the read must run off the worker so this test's own task keeps
11631    /// running while the read is paused.
11632    #[tokio::test(flavor = "current_thread")]
11633    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11634        let dir = ScratchDir::new("terminals-off-worker");
11635        let journal_path = dir.join("terminals.jsonl");
11636        let registry = Arc::new(Registry::default());
11637        let supervisor_handle = SupervisorHandle::new();
11638        let supervisor =
11639            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11640                .with_handle(supervisor_handle.clone())
11641                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11642        let module = supervisor
11643            .spawn(ModuleSpec {
11644                script: None,
11645                carry_containment: false,
11646                module_id: "terminal-off-worker".to_string(),
11647                program: fake_aft_stub_path(),
11648                args: Vec::new(),
11649                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11650                reserved: false,
11651                reserved_prefixes: Vec::new(),
11652                protocol: ModuleProtocol::Subc,
11653                overlap: Default::default(),
11654            })
11655            .unwrap();
11656        let deadline = Instant::now() + Duration::from_secs(5);
11657        while module.terminal_history().entries.len() != 2 {
11658            assert!(Instant::now() < deadline, "module did not record two exits");
11659            sleep(Duration::from_millis(10)).await;
11660        }
11661
11662        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11663        let handler =
11664            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11665        let frame = Frame::build(
11666            FrameType::Request,
11667            control_flags(),
11668            0,
11669            0,
11670            1,
11671            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11672                module_id: "terminal-off-worker".to_string(),
11673            })
11674            .unwrap(),
11675        )
11676        .unwrap();
11677        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11678        let spawned_at = std::time::Instant::now();
11679        let read = tokio::spawn({
11680            let handler = Arc::clone(&handler);
11681            async move { handler.handle_control_frame(&ctx, frame).await }
11682        });
11683        // Waiting for the pause from a blocking thread keeps this task pending,
11684        // so the runtime's single worker is free to run the read task.
11685        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11686            .await
11687            .unwrap()
11688            .expect("the history read reached its pause");
11689        let elapsed = spawned_at.elapsed();
11690        assert!(
11691            elapsed < Duration::from_secs(2) && !read.is_finished(),
11692            "this task could not run while the history read was paused \
11693             (resumed after {elapsed:?}, read finished: {})",
11694            read.is_finished()
11695        );
11696
11697        drop(release);
11698        let responses = read.await.unwrap().unwrap();
11699        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11700        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11701            panic!("expected supervisor.terminals response");
11702        };
11703        assert_eq!(terminals.entries.len(), 2);
11704        assert_eq!(terminals.journal_skipped_lines, 0);
11705        assert_eq!(terminals.journal_read_errors, 0);
11706    }
11707
11708    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11709    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11710        let registry = Arc::new(Registry::default());
11711        let supervisor_handle = SupervisorHandle::new();
11712        let supervisor =
11713            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11714                .with_handle(supervisor_handle.clone());
11715        let module = supervisor
11716            .spawn(ModuleSpec {
11717                script: None,
11718                carry_containment: false,
11719                module_id: "terminal-golden".to_string(),
11720                program: fake_aft_stub_path(),
11721                args: Vec::new(),
11722                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11723                reserved: false,
11724                reserved_prefixes: Vec::new(),
11725                protocol: ModuleProtocol::Subc,
11726                overlap: Default::default(),
11727            })
11728            .unwrap();
11729
11730        let deadline = Instant::now() + Duration::from_secs(5);
11731        while module.terminal_history().entries.len() != 2 {
11732            assert!(
11733                Instant::now() < deadline,
11734                "module did not retain two terminal exits: {:?}",
11735                module.terminal_history()
11736            );
11737            sleep(Duration::from_millis(10)).await;
11738        }
11739
11740        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11741        let request = ClientControlRequest::SupervisorTerminals {
11742            module_id: "terminal-golden".to_string(),
11743        };
11744        let frame = Frame::build(
11745            FrameType::Request,
11746            control_flags(),
11747            0,
11748            0,
11749            1,
11750            serde_json::to_vec(&request).unwrap(),
11751        )
11752        .unwrap();
11753        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11754        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11755        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11756        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11757            panic!("expected supervisor.terminals response");
11758        };
11759        assert_eq!(terminals.entries.len(), 2);
11760        assert_eq!(terminals.dropped, 0);
11761
11762        let mut rendered = serde_json::to_value(response).unwrap();
11763        // Wall-clock fields are the observation contract, but not stable fixture
11764        // bytes; normalize only them after the real handler has shaped the response.
11765        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11766        for (index, entry) in rendered["entries"]
11767            .as_array_mut()
11768            .expect("terminal response entries array")
11769            .iter_mut()
11770            .enumerate()
11771        {
11772            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11773        }
11774
11775        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11776            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11777        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11778        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11779            std::fs::write(&golden_path, &serialized).unwrap();
11780        }
11781        let expected: Value =
11782            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11783        assert_eq!(rendered, expected);
11784    }
11785
11786    #[test]
11787    fn hello_registers_manifest_and_returns_ack() {
11788        let registry = Arc::new(Registry::default());
11789        let handler = ControlHandler::new(Arc::clone(&registry));
11790        let conn = ConnectionId::new(1);
11791
11792        let responses = handler
11793            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11794            .unwrap();
11795
11796        assert_eq!(responses.len(), 1);
11797        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11798        assert_eq!(responses[0].header.channel, 0);
11799        assert_eq!(responses[0].header.corr, 7);
11800        let ack = parse_ack(&responses[0]);
11801        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11802        assert!(ack
11803            .subc_capabilities
11804            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11805        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11806        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11807        assert!(ack
11808            .subc_ops
11809            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11810        assert!(ack
11811            .subc_ops
11812            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11813        assert!(ack
11814            .subc_ops
11815            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11816
11817        let registration = registry.get_module("aft").unwrap().unwrap();
11818        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11819        assert_eq!(registration.state, ChannelState::Active);
11820        assert_eq!(registration.connection_id, conn);
11821        assert_eq!(registration.control_ops, module_baseline_control_ops());
11822        assert!(registration.manifest.display_name.is_none());
11823    }
11824
11825    #[test]
11826    fn hello_display_name_refuses_invalid_manifest_by_field() {
11827        let registry = Arc::new(Registry::default());
11828        let handler = ControlHandler::new(Arc::clone(&registry));
11829        for (index, invalid) in [
11830            json!(""),
11831            json!("a".repeat(41)),
11832            json!(" Routing"),
11833            json!("a\nb"),
11834            json!("a\u{202e}b"),
11835            json!(7),
11836        ]
11837        .into_iter()
11838        .enumerate()
11839        {
11840            let module_id = format!("bad-display-name-{index}");
11841            let mut body = serde_json::to_value(ModuleHelloBody {
11842                manifest: manifest(&module_id, PROTOCOL_VERSION),
11843                protocol_ver: PROTOCOL_VERSION,
11844                control_ops: None,
11845                launch_nonce: None,
11846            })
11847            .unwrap();
11848            body["manifest"]["display_name"] = invalid;
11849            let hello = Frame::build(
11850                FrameType::Hello,
11851                control_flags(),
11852                0,
11853                0,
11854                7,
11855                serde_json::to_vec(&body).unwrap(),
11856            )
11857            .unwrap();
11858            let response = handler
11859                .handle_control(ConnectionId::new(100 + index as u64), hello)
11860                .unwrap();
11861            assert_eq!(response[0].header.ty, FrameType::Error);
11862            let error = parse_error(&response[0]);
11863            assert_eq!(error["code"], "invalid_manifest");
11864            assert!(error["message"].as_str().unwrap().contains("display_name"));
11865            assert!(registry.get_module(&module_id).unwrap().is_none());
11866        }
11867    }
11868
11869    #[test]
11870    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11871        let invalid_identifiers = [
11872            ("case_change", "credentials-Provider/v1"),
11873            ("leading_zero", "credentials-provider/v01"),
11874            ("trailing_hyphen", "credentials-provider-/v1"),
11875            ("consecutive_hyphens", "credentials--provider/v1"),
11876            ("uppercase", "Credentials-provider/v1"),
11877            ("missing_v", "credentials-provider/1"),
11878            ("whitespace", "credentials provider/v1"),
11879            ("zero_version", "credentials-provider/v0"),
11880            ("out_of_range_version", "credentials-provider/v4294967296"),
11881            (
11882                "overlength_name",
11883                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11884            ),
11885        ];
11886        let mut cases = invalid_identifiers
11887            .into_iter()
11888            .map(|(name, identifier)| {
11889                (
11890                    format!("identifier_{name}"),
11891                    "capabilities.provides[0]".to_string(),
11892                    identifier.to_string(),
11893                    json!({ "provides": [identifier] }),
11894                    None,
11895                )
11896            })
11897            .collect::<Vec<_>>();
11898        cases.extend([
11899            (
11900                "unknown_need".to_string(),
11901                "capabilities.requires[0].need".to_string(),
11902                "deferred".to_string(),
11903                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11904                None,
11905            ),
11906            (
11907                "duplicate_provides".to_string(),
11908                "capabilities.provides[1]".to_string(),
11909                "credentials-provider/v1".to_string(),
11910                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11911                None,
11912            ),
11913            (
11914                "duplicate_must_never_reach".to_string(),
11915                "capabilities.must_never_reach[1]".to_string(),
11916                "credentials-provider/v1".to_string(),
11917                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11918                None,
11919            ),
11920            (
11921                "duplicate_requires_same_need".to_string(),
11922                "capabilities.requires[1]".to_string(),
11923                "credentials-provider/v1".to_string(),
11924                json!({ "requires": [
11925                    { "capability": "credentials-provider/v1", "need": "required" },
11926                    { "capability": "credentials-provider/v1", "need": "required" }
11927                ] }),
11928                None,
11929            ),
11930            (
11931                "duplicate_requires_conflicting_need".to_string(),
11932                "capabilities.requires[1]".to_string(),
11933                "credentials-provider/v1".to_string(),
11934                json!({ "requires": [
11935                    { "capability": "credentials-provider/v1", "need": "required" },
11936                    { "capability": "credentials-provider/v1", "need": "optional" }
11937                ] }),
11938                None,
11939            ),
11940            (
11941                "capabilities_root_pointer".to_string(),
11942                "runtime_computed[0]".to_string(),
11943                "/capabilities".to_string(),
11944                json!({}),
11945                Some(json!(["/capabilities"])),
11946            ),
11947            (
11948                "capabilities_descendant_pointer".to_string(),
11949                "runtime_computed[0]".to_string(),
11950                "/capabilities/provides".to_string(),
11951                json!({}),
11952                Some(json!(["/capabilities/provides"])),
11953            ),
11954            (
11955                "malformed_pointer_without_leading_slash".to_string(),
11956                "runtime_computed[0]".to_string(),
11957                "capabilities".to_string(),
11958                json!({}),
11959                Some(json!(["capabilities"])),
11960            ),
11961            (
11962                "malformed_pointer_escape".to_string(),
11963                "runtime_computed[0]".to_string(),
11964                "/roles/~2/tools".to_string(),
11965                json!({}),
11966                Some(json!(["/roles/~2/tools"])),
11967            ),
11968            (
11969                "unknown_capabilities_field".to_string(),
11970                "capabilities.future".to_string(),
11971                "<array>".to_string(),
11972                json!({ "future": [] }),
11973                None,
11974            ),
11975        ]);
11976
11977        for (index, (name, field, value, capabilities, runtime_computed)) in
11978            cases.into_iter().enumerate()
11979        {
11980            let registry = Arc::new(Registry::default());
11981            let handler = ControlHandler::new(Arc::clone(&registry));
11982            let response = handler
11983                .handle_control(
11984                    ConnectionId::new((index + 1) as u64),
11985                    capability_grammar_hello_frame(
11986                        capabilities,
11987                        runtime_computed,
11988                        index as u64 + 1,
11989                    ),
11990                )
11991                .expect("invalid HELLO returns a refusal");
11992
11993            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11994            let error = parse_error(&response[0]);
11995            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11996            let message = error["message"]
11997                .as_str()
11998                .expect("error message is a string");
11999            assert!(
12000                message.contains(&field),
12001                "{name}: field missing from {message}"
12002            );
12003            assert!(
12004                message.contains(&value),
12005                "{name}: value missing from {message}"
12006            );
12007            assert_eq!(
12008                registry
12009                    .active_registration_count()
12010                    .expect("registry reads"),
12011                0,
12012                "{name}: refused HELLO must not create a catalog entry"
12013            );
12014        }
12015    }
12016
12017    #[test]
12018    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
12019        let registry = Arc::new(Registry::default());
12020        let handler = ControlHandler::new(Arc::clone(&registry));
12021        let capabilities = json!({
12022            "provides": ["credentials-provider/v1"],
12023            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
12024            "must_never_reach": ["federation-transport/v1"]
12025        });
12026        let response = handler
12027            .handle_control(
12028                ConnectionId::new(99),
12029                capability_grammar_hello_frame(
12030                    capabilities.clone(),
12031                    Some(json!(["/roles/0/tools"])),
12032                    99,
12033                ),
12034            )
12035            .expect("valid HELLO registers");
12036        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12037
12038        let request = Frame::build(
12039            FrameType::Request,
12040            control_flags(),
12041            0,
12042            0,
12043            100,
12044            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12045                .expect("catalog request serializes"),
12046        )
12047        .expect("catalog request frame builds");
12048        let response = handler
12049            .handle_catalog_list(request, None)
12050            .expect("catalog list succeeds");
12051        let ClientControlResponse::CatalogList { modules, .. } =
12052            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
12053        else {
12054            panic!("catalog request must return catalog.list");
12055        };
12056        assert_eq!(modules.len(), 1);
12057        assert_eq!(
12058            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
12059            capabilities
12060        );
12061    }
12062
12063    #[test]
12064    fn catalog_list_mirrors_management_operation_description() {
12065        let registry = Arc::new(Registry::default());
12066        let handler = ControlHandler::new(Arc::clone(&registry));
12067        let description = "List managed records and return their identifiers and metadata.";
12068        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
12069        manifest.provides = vec![ProviderRole::ManagementSurface {
12070            operations: vec![ManagementOperation {
12071                name: "records.list".to_string(),
12072                kind: ManagementOperationKind::Query,
12073                description: Some(description.to_string()),
12074            }],
12075            config_schema: json!({"type": "object"}),
12076            observability: vec![ObservabilitySurface {
12077                name: "records.stats".to_string(),
12078                kind: ObservabilityKind::Snapshot,
12079            }],
12080            identity_scope: vec![IdentityScope::Project],
12081            concurrency: Concurrency::ModuleManaged,
12082        }];
12083        registry
12084            .register_with_control_ops(
12085                manifest,
12086                PROTOCOL_VERSION,
12087                ConnectionId::new(99),
12088                Vec::new(),
12089            )
12090            .expect("described management manifest registers");
12091
12092        let request = Frame::build(
12093            FrameType::Request,
12094            control_flags(),
12095            0,
12096            0,
12097            100,
12098            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
12099                .expect("catalog request serializes"),
12100        )
12101        .expect("catalog request frame builds");
12102        let response = handler
12103            .handle_catalog_list(request, None)
12104            .expect("catalog list succeeds");
12105        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
12106        assert_eq!(
12107            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
12108            "catalog.list must preserve the declared operation description verbatim"
12109        );
12110    }
12111
12112    #[test]
12113    fn catalog_list_mirrors_registered_operation_delivery() {
12114        let registry = Arc::new(Registry::default());
12115        let handler = ControlHandler::new(Arc::clone(&registry));
12116        let delivery =
12117            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
12118        let mut body = serde_json::to_value(ModuleHelloBody {
12119            manifest: manifest("watch-management", PROTOCOL_VERSION),
12120            protocol_ver: PROTOCOL_VERSION,
12121            control_ops: None,
12122            launch_nonce: None,
12123        })
12124        .unwrap();
12125        body["manifest"]["provides"] = json!([{
12126            "role": "management_surface",
12127            "operations": [
12128                {"name": "status", "kind": "query"},
12129                {"name": "future", "kind": "query"},
12130                {"name": "reset", "kind": "mutate"}
12131            ],
12132            "config_schema": {}, "observability": [], "identity_scope": []
12133        }]);
12134        body["manifest"]["operation_delivery"] = delivery.clone();
12135        let hello = Frame::build(
12136            FrameType::Hello,
12137            control_flags(),
12138            0,
12139            0,
12140            99,
12141            serde_json::to_vec(&body).unwrap(),
12142        )
12143        .unwrap();
12144        let response = handler
12145            .handle_control(ConnectionId::new(99), hello)
12146            .unwrap();
12147        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12148
12149        let (_, registrations) = registry.list_modules().unwrap();
12150        let registered = &registrations[0].manifest;
12151        assert!(registered.is_watch_operation("status"));
12152        assert!(!registered.is_watch_operation("future"));
12153        assert!(!registered.is_watch_operation("reset"));
12154        assert!(!registered.is_watch_operation("missing"));
12155
12156        let request = Frame::build(
12157            FrameType::Request,
12158            control_flags(),
12159            0,
12160            0,
12161            100,
12162            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12163        )
12164        .unwrap();
12165        let response = handler.handle_catalog_list(request, None).unwrap();
12166        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12167        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12168        let ClientControlResponse::CatalogList { modules, .. } =
12169            serde_json::from_slice(&response[0].body).unwrap()
12170        else {
12171            panic!("expected catalog.list");
12172        };
12173        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12174    }
12175
12176    #[test]
12177    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12178        let registry = Arc::new(Registry::default());
12179        let supervisor = SupervisorHandle::new();
12180        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12181        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12182        let descriptor = json!({
12183            "schema": "ckios.richui.manifest/1",
12184            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12185            "bytes": 4096,
12186            "chunks": 4
12187        });
12188        let connection = ConnectionId::new(201);
12189        let hello = handler
12190            .handle_control(
12191                connection,
12192                hello_frame_with_rich_ui(
12193                    "vault",
12194                    PROTOCOL_VERSION,
12195                    201,
12196                    Some("the-real-nonce"),
12197                    descriptor.clone(),
12198                ),
12199            )
12200            .unwrap();
12201        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12202
12203        let request =
12204            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12205        let provides = registry
12206            .get_module_by_connection(connection)
12207            .unwrap()
12208            .unwrap()
12209            .manifest
12210            .provides;
12211        handler
12212            .handle_catalog_update(connection, request, provides, None, Some(false))
12213            .unwrap();
12214
12215        let request = Frame::build(
12216            FrameType::Request,
12217            control_flags(),
12218            0,
12219            0,
12220            203,
12221            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12222        )
12223        .unwrap();
12224        let response = handler.handle_catalog_list(request, None).unwrap();
12225        let ClientControlResponse::CatalogList { modules, .. } =
12226            serde_json::from_slice(&response[0].body).unwrap()
12227        else {
12228            panic!("expected catalog.list");
12229        };
12230        assert_eq!(
12231            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12232            descriptor
12233        );
12234        assert!(modules[0].nonce_verified);
12235    }
12236
12237    fn hello_with_role_declarations(declarations: Value) -> Frame {
12238        let mut body = serde_json::to_value(ModuleHelloBody {
12239            manifest: manifest("role-test", PROTOCOL_VERSION),
12240            protocol_ver: PROTOCOL_VERSION,
12241            control_ops: None,
12242            launch_nonce: None,
12243        })
12244        .unwrap();
12245        body["manifest"]["role_declarations"] = declarations;
12246        Frame::build(
12247            FrameType::Hello,
12248            control_flags(),
12249            0,
12250            0,
12251            301,
12252            serde_json::to_vec(&body).unwrap(),
12253        )
12254        .unwrap()
12255    }
12256
12257    fn update_role_declarations_frame(declarations: Value) -> Frame {
12258        Frame::build(
12259            FrameType::Request,
12260            control_flags(),
12261            0,
12262            0,
12263            303,
12264            serde_json::to_vec(&json!({
12265                "op": "catalog.update_role_declarations",
12266                "role_declarations": declarations,
12267            }))
12268            .unwrap(),
12269        )
12270        .unwrap()
12271    }
12272
12273    #[tokio::test]
12274    async fn role_declarations_update_replaces_then_clears_catalog() {
12275        let registry = Arc::new(Registry::default());
12276        let handler = ControlHandler::new(Arc::clone(&registry));
12277        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12278        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12279        hello_via_sink(
12280            &handler,
12281            &ctx,
12282            &mut rx,
12283            hello_with_role_declarations(initial.clone()),
12284        )
12285        .await;
12286        assert_eq!(
12287            role_declarations_catalog(&handler).0["role_declarations"],
12288            initial
12289        );
12290        let before = registry.get_module("role-test").unwrap().unwrap();
12291        for declarations in [
12292            json!({"media-provider/v1": {"engines": ["new"]}}),
12293            json!({}),
12294        ] {
12295            let response = handler
12296                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12297                .await
12298                .unwrap();
12299            assert_eq!(response[0].header.ty, FrameType::Response);
12300            assert_eq!(
12301                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12302                json!({"op": "catalog.update_role_declarations"})
12303            );
12304            let (raw, entry) = role_declarations_catalog(&handler);
12305            assert_eq!(
12306                serde_json::to_value(entry.role_declarations).unwrap(),
12307                declarations
12308            );
12309            if declarations.as_object().unwrap().is_empty() {
12310                assert!(raw.get("role_declarations").is_none());
12311            } else {
12312                assert_eq!(raw["role_declarations"], declarations);
12313            }
12314            let after = registry.get_module("role-test").unwrap().unwrap();
12315            let mut expected = before.manifest.clone();
12316            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12317            assert_eq!(after.manifest, expected);
12318            assert_eq!(after.ready, before.ready);
12319        }
12320    }
12321
12322    #[tokio::test]
12323    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12324        let registry = Arc::new(Registry::default());
12325        let handler = ControlHandler::new(registry);
12326        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12327        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12328        hello_via_sink(
12329            &handler,
12330            &ctx,
12331            &mut rx,
12332            hello_with_role_declarations(initial.clone()),
12333        )
12334        .await;
12335        for (invalid, reason) in [
12336            (json!(null), "role_declarations must be an object"),
12337            (json!([]), "role_declarations must be an object"),
12338            (
12339                json!({"bad key": {}}),
12340                "role_declarations key must use capability-name grammar",
12341            ),
12342            (
12343                json!({"media-provider/v1": []}),
12344                "role_declarations values must be objects",
12345            ),
12346            (
12347                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12348                "role_declarations exceeds 16384 compact JSON bytes",
12349            ),
12350        ] {
12351            let response = handler
12352                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12353                .await
12354                .unwrap();
12355            let error = parse_error(&response[0]);
12356            assert_eq!(error["code"], "invalid_role_declarations");
12357            assert_eq!(error["message"], reason);
12358            assert_eq!(
12359                role_declarations_catalog(&handler).0["role_declarations"],
12360                initial
12361            );
12362        }
12363    }
12364
12365    #[tokio::test]
12366    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12367        let registry = Arc::new(Registry::default());
12368        let handler = ControlHandler::new(Arc::clone(&registry));
12369        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12370        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12371        hello_via_sink(
12372            &handler,
12373            &owner,
12374            &mut owner_rx,
12375            hello_with_role_declarations(initial.clone()),
12376        )
12377        .await;
12378        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12379        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12380        let response = handler
12381            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12382            .await
12383            .unwrap();
12384        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12385        hello_via_sink(
12386            &handler,
12387            &other,
12388            &mut other_rx,
12389            hello_frame("other", PROTOCOL_VERSION, 304),
12390        )
12391        .await;
12392        let response = handler
12393            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12394            .await
12395            .unwrap();
12396        assert_eq!(response[0].header.ty, FrameType::Response);
12397        assert_eq!(
12398            serde_json::to_value(
12399                registry
12400                    .get_module("role-test")
12401                    .unwrap()
12402                    .unwrap()
12403                    .manifest
12404                    .role_declarations
12405            )
12406            .unwrap(),
12407            initial
12408        );
12409        assert_eq!(
12410            serde_json::to_value(
12411                registry
12412                    .get_module("other")
12413                    .unwrap()
12414                    .unwrap()
12415                    .manifest
12416                    .role_declarations
12417            )
12418            .unwrap(),
12419            replacement
12420        );
12421    }
12422
12423    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12424        let request = Frame::build(
12425            FrameType::Request,
12426            control_flags(),
12427            0,
12428            0,
12429            302,
12430            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12431        )
12432        .unwrap();
12433        let response = handler.handle_catalog_list(request, None).unwrap();
12434        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12435        let ClientControlResponse::CatalogList { mut modules, .. } =
12436            serde_json::from_slice(&response[0].body).unwrap()
12437        else {
12438            panic!("expected catalog.list");
12439        };
12440        (raw["modules"][0].clone(), modules.remove(0))
12441    }
12442
12443    #[test]
12444    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12445        let registry = Arc::new(Registry::default());
12446        let handler = ControlHandler::new(Arc::clone(&registry));
12447        let declarations = json!({
12448            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12449            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12450        });
12451        let connection = ConnectionId::new(301);
12452        let response = handler
12453            .handle_control(
12454                connection,
12455                hello_with_role_declarations(declarations.clone()),
12456            )
12457            .unwrap();
12458        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12459        let registered = registry
12460            .get_module_by_connection(connection)
12461            .unwrap()
12462            .unwrap()
12463            .manifest;
12464        // Compared as JSON values, not bytes: object key order is not part of
12465        // the relay's promise, and workspace builds unify serde_json's
12466        // preserve_order feature, which changes the order a literal keeps.
12467        assert_eq!(
12468            serde_json::to_value(&registered.role_declarations).unwrap(),
12469            declarations
12470        );
12471        let (raw, entry) = role_declarations_catalog(&handler);
12472        assert_eq!(raw["role_declarations"], declarations);
12473        assert_eq!(entry.role_declarations, registered.role_declarations);
12474
12475        let request =
12476            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12477        handler
12478            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12479            .unwrap();
12480        let (raw, entry) = role_declarations_catalog(&handler);
12481        assert_eq!(raw["role_declarations"], declarations);
12482        assert_eq!(entry.role_declarations, registered.role_declarations);
12483    }
12484
12485    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12486        let registry = Arc::new(Registry::default());
12487        let handler = ControlHandler::new(Arc::clone(&registry));
12488        let capture = EventCapture::default();
12489        let _subscriber =
12490            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12491        let response = handler
12492            .handle_control(
12493                ConnectionId::new(301),
12494                hello_with_role_declarations(declarations),
12495            )
12496            .unwrap();
12497        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12498        assert!(registry
12499            .get_module_by_connection(ConnectionId::new(301))
12500            .unwrap()
12501            .unwrap()
12502            .manifest
12503            .role_declarations
12504            .is_empty());
12505        let (raw, entry) = role_declarations_catalog(&handler);
12506        assert!(raw.get("role_declarations").is_none());
12507        assert!(entry.role_declarations.is_empty());
12508        let warnings: Vec<_> = capture
12509            .events()
12510            .into_iter()
12511            .filter(|event| {
12512                event.fields.get("message").map(String::as_str)
12513                    == Some("dropping whole role_declarations map from HELLO")
12514            })
12515            .collect();
12516        assert_eq!(warnings.len(), 1);
12517        assert_eq!(warnings[0].level, tracing::Level::WARN);
12518        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12519        assert_eq!(warnings[0].fields["reason"], reason);
12520    }
12521
12522    #[test]
12523    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12524        for value in [
12525            json!(null),
12526            json!(false),
12527            json!(0),
12528            json!("opaque"),
12529            json!([]),
12530        ] {
12531            assert_hello_drops_role_declarations_with_warning(
12532                json!({"routing/v1": {}, "broken/v1": value}),
12533                "role_declarations values must be objects",
12534            );
12535        }
12536        assert_hello_drops_role_declarations_with_warning(
12537            json!([]),
12538            "role_declarations must be an object",
12539        );
12540    }
12541
12542    #[test]
12543    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12544        assert_hello_drops_role_declarations_with_warning(
12545            json!({"routing/v1": {}, "bad key": {}}),
12546            "role_declarations key must use capability-name grammar",
12547        );
12548    }
12549
12550    #[test]
12551    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12552        assert_hello_drops_role_declarations_with_warning(
12553            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12554            "role_declarations exceeds 16384 compact JSON bytes",
12555        );
12556    }
12557
12558    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12559        let mut body = serde_json::to_value(ModuleHelloBody {
12560            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12561            protocol_ver: PROTOCOL_VERSION,
12562            control_ops: None,
12563            launch_nonce: None,
12564        })
12565        .unwrap();
12566        body["manifest"]["provides"] = json!([{
12567            "role": "management_surface",
12568            "operations": [
12569                {"name": "diagnostics.findings", "kind": "query"},
12570                {"name": "reset", "kind": "mutate"}
12571            ],
12572            "config_schema": {}, "observability": [], "identity_scope": []
12573        }]);
12574        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12575        if let Some(flow_operations) = flow_operations {
12576            body["manifest"]["flow_operations"] = flow_operations;
12577        }
12578        Frame::build(
12579            FrameType::Hello,
12580            control_flags(),
12581            0,
12582            0,
12583            401,
12584            serde_json::to_vec(&body).unwrap(),
12585        )
12586        .unwrap()
12587    }
12588
12589    #[test]
12590    fn catalog_list_mirrors_flow_operations_unchanged() {
12591        // Order is kept as declared (not sorted) and an empty list stays an
12592        // affirmative "none", distinct from an absent declaration.
12593        for (capability, flow_operations) in [
12594            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12595            ("call-modes/v1", json!(["diagnostics.findings"])),
12596            ("flow-scopes/v1", json!([])),
12597        ] {
12598            let registry = Arc::new(Registry::default());
12599            let handler = ControlHandler::new(Arc::clone(&registry));
12600            let connection = ConnectionId::new(401);
12601            let response = handler
12602                .handle_control(
12603                    connection,
12604                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12605                )
12606                .unwrap();
12607            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12608            let registered = registry
12609                .get_module_by_connection(connection)
12610                .unwrap()
12611                .unwrap()
12612                .manifest;
12613            assert_eq!(
12614                serde_json::to_value(&registered.flow_operations).unwrap(),
12615                flow_operations
12616            );
12617            let (raw, entry) = role_declarations_catalog(&handler);
12618            assert_eq!(raw["flow_operations"], flow_operations);
12619            assert_eq!(entry.flow_operations, registered.flow_operations);
12620        }
12621
12622        let registry = Arc::new(Registry::default());
12623        let handler = ControlHandler::new(Arc::clone(&registry));
12624        let response = handler
12625            .handle_control(
12626                ConnectionId::new(401),
12627                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12628            )
12629            .unwrap();
12630        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12631        let (raw, entry) = role_declarations_catalog(&handler);
12632        assert!(raw.get("flow_operations").is_none());
12633        assert_eq!(entry.flow_operations, None);
12634    }
12635
12636    #[test]
12637    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12638        let oversized: serde_json::Map<String, Value> = (0..257)
12639            .map(|n| (format!("tool:t{n}"), json!(true)))
12640            .collect();
12641        for (capabilities, map, valid) in [
12642            (
12643                json!(["scope-federated/v1"]),
12644                json!({"tool:read":true,"management:reset":true}),
12645                true,
12646            ),
12647            (json!(["scope-federated/v1"]), json!({}), true),
12648            (json!([]), json!({"tool:read":true}), false),
12649            (
12650                json!(["scope-federated/v1"]),
12651                json!({"tool:valid":true,"tool:bad":false}),
12652                false,
12653            ),
12654            (
12655                json!(["scope-federated/v1"]),
12656                json!({"tool:valid":true,"management:missing":true}),
12657                false,
12658            ),
12659            (
12660                json!(["scope-federated/v1"]),
12661                Value::Object(oversized),
12662                false,
12663            ),
12664        ] {
12665            let capture = EventCapture::default();
12666            let _subscriber = tracing::subscriber::set_default(
12667                tracing_subscriber::registry().with(capture.clone()),
12668            );
12669            let registry = Arc::new(Registry::default());
12670            let handler = ControlHandler::new(Arc::clone(&registry));
12671            let hello = hello_with_flow_operations(capabilities, None);
12672            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12673            body["manifest"]["operation_deferral"] = map.clone();
12674            let hello = Frame::build(
12675                FrameType::Hello,
12676                control_flags(),
12677                0,
12678                0,
12679                401,
12680                serde_json::to_vec(&body).unwrap(),
12681            )
12682            .unwrap();
12683            let response = handler
12684                .handle_control(ConnectionId::new(401), hello)
12685                .unwrap();
12686            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12687            let (raw, entry) = role_declarations_catalog(&handler);
12688            if valid {
12689                assert_eq!(raw["operation_deferral"], map);
12690                assert_eq!(
12691                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12692                    map
12693                );
12694            } else {
12695                assert!(entry.operation_deferral.is_none());
12696                assert!(raw.get("operation_deferral").is_none());
12697                assert_eq!(
12698                    capture
12699                        .events()
12700                        .iter()
12701                        .filter(|event| event.fields.get("message").map(String::as_str)
12702                            == Some("dropping operation_deferral from HELLO"))
12703                        .count(),
12704                    1
12705                );
12706            }
12707        }
12708    }
12709
12710    fn assert_hello_drops_flow_operations_with_warning(
12711        capabilities: Value,
12712        flow_operations: Value,
12713        reason: &str,
12714    ) {
12715        let registry = Arc::new(Registry::default());
12716        let handler = ControlHandler::new(Arc::clone(&registry));
12717        let capture = EventCapture::default();
12718        let _subscriber =
12719            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12720        let response = handler
12721            .handle_control(
12722                ConnectionId::new(401),
12723                hello_with_flow_operations(capabilities, Some(flow_operations)),
12724            )
12725            .unwrap();
12726        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12727        let registered = registry
12728            .get_module_by_connection(ConnectionId::new(401))
12729            .unwrap()
12730            .expect("the module still registers")
12731            .manifest;
12732        assert_eq!(registered.module_id, "flow-ops");
12733        assert_eq!(registered.flow_operations, None);
12734        let (raw, entry) = role_declarations_catalog(&handler);
12735        assert_eq!(raw["module_id"], "flow-ops");
12736        assert!(raw.get("flow_operations").is_none());
12737        assert_eq!(entry.flow_operations, None);
12738        let warnings: Vec<_> = capture
12739            .events()
12740            .into_iter()
12741            .filter(|event| {
12742                event.fields.get("message").map(String::as_str)
12743                    == Some("dropping flow_operations from HELLO")
12744            })
12745            .collect();
12746        assert_eq!(warnings.len(), 1);
12747        assert_eq!(warnings[0].level, tracing::Level::WARN);
12748        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12749        assert_eq!(warnings[0].fields["reason"], reason);
12750    }
12751
12752    #[test]
12753    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12754        assert_hello_drops_flow_operations_with_warning(
12755            json!(["flow-scopes/v1"]),
12756            json!(["diagnostics.findings", "missing"]),
12757            "flow_operations names 'missing', which is not a declared management operation",
12758        );
12759    }
12760
12761    #[test]
12762    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12763        assert_hello_drops_flow_operations_with_warning(
12764            json!([]),
12765            json!(["diagnostics.findings"]),
12766            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12767        );
12768        // A run-only capability does not admit flows either.
12769        assert_hello_drops_flow_operations_with_warning(
12770            json!(["agent-run-scopes/v1"]),
12771            json!([]),
12772            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12773        );
12774    }
12775
12776    #[test]
12777    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12778        assert_hello_drops_flow_operations_with_warning(
12779            json!(["flow-scopes/v1"]),
12780            json!(["reset", "reset"]),
12781            "flow_operations names 'reset' more than once",
12782        );
12783        assert_hello_drops_flow_operations_with_warning(
12784            json!(["flow-scopes/v1"]),
12785            json!(vec!["reset"; 257]),
12786            "flow_operations lists 257 names, more than 256",
12787        );
12788        assert_hello_drops_flow_operations_with_warning(
12789            json!(["flow-scopes/v1"]),
12790            json!("reset"),
12791            "flow_operations must be an array of operation names",
12792        );
12793    }
12794
12795    #[test]
12796    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12797        let registry = Arc::new(Registry::default());
12798        let handler = ControlHandler::new(registry.clone());
12799        let descriptor = json!({
12800            "schema": "ckios.richui.manifest/1",
12801            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12802            "bytes": 128,
12803            "chunks": 2
12804        });
12805        let malformed = [
12806            ("schema", json!("")),
12807            ("schema", json!("a".repeat(65))),
12808            ("schema", json!("Bad schema")),
12809            (
12810                "manifest_digest",
12811                json!(format!("sha256:{}", "A".repeat(64))),
12812            ),
12813            ("manifest_digest", json!("sha256:abc")),
12814            ("bytes", json!(0)),
12815            ("bytes", json!(16_777_217)),
12816            ("bytes", json!("128")),
12817            ("chunks", json!(0)),
12818            ("chunks", json!(1025)),
12819            ("chunks", json!("2")),
12820        ];
12821        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12822            let mut invalid = descriptor.clone();
12823            invalid[field] = invalid_value;
12824            let response = handler
12825                .handle_control(
12826                    ConnectionId::new(210 + index as u64),
12827                    hello_frame_with_rich_ui(
12828                        &format!("bad-rich-ui-{index}"),
12829                        PROTOCOL_VERSION,
12830                        210 + index as u64,
12831                        None,
12832                        invalid,
12833                    ),
12834                )
12835                .unwrap();
12836            assert_eq!(response[0].header.ty, FrameType::Error);
12837            let error = parse_error(&response[0]);
12838            assert_eq!(error["code"], "invalid_manifest");
12839            assert!(error["message"]
12840                .as_str()
12841                .unwrap()
12842                .contains(&format!("rich_ui.{field}")));
12843            assert!(registry
12844                .get_module(&format!("bad-rich-ui-{index}"))
12845                .unwrap()
12846                .is_none());
12847        }
12848    }
12849
12850    #[test]
12851    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12852        let registry = Arc::new(Registry::default());
12853        let handler = ControlHandler::new(Arc::clone(&registry));
12854        let connection = ConnectionId::new(219);
12855        registry
12856            .register_with_control_ops(
12857                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12858                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12859                        "bad schema",
12860                        format!("sha256:{}", "a".repeat(64)),
12861                        128,
12862                        2,
12863                    )))
12864                    .build(),
12865                PROTOCOL_VERSION,
12866                connection,
12867                Vec::new(),
12868            )
12869            .unwrap();
12870        let request =
12871            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12872        let response = handler
12873            .handle_catalog_update(connection, request, Vec::new(), None, None)
12874            .unwrap();
12875        assert_eq!(response[0].header.ty, FrameType::Error);
12876        let error = parse_error(&response[0]);
12877        assert_eq!(error["code"], "invalid_manifest");
12878        assert!(error["message"]
12879            .as_str()
12880            .unwrap()
12881            .contains("rich_ui.schema"));
12882    }
12883
12884    #[test]
12885    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12886        let registry = Arc::new(Registry::default());
12887        let supervisor = SupervisorHandle::new();
12888        supervisor.open_swap("provider", "candidate-nonce".to_string());
12889        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12890        let connection = ConnectionId::new(218);
12891        let hello = handler
12892            .handle_control(
12893                connection,
12894                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12895            )
12896            .unwrap();
12897        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12898        assert!(registry.list_modules().unwrap().1.is_empty());
12899
12900        registry.promote_candidate("provider").unwrap().unwrap();
12901        let request = Frame::build(
12902            FrameType::Request,
12903            control_flags(),
12904            0,
12905            0,
12906            219,
12907            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12908        )
12909        .unwrap();
12910        let response = handler.handle_catalog_list(request, None).unwrap();
12911        let ClientControlResponse::CatalogList { modules, .. } =
12912            serde_json::from_slice(&response[0].body).unwrap()
12913        else {
12914            panic!("expected catalog.list");
12915        };
12916        assert_eq!(modules.len(), 1);
12917        assert!(modules[0].nonce_verified);
12918    }
12919
12920    #[test]
12921    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12922        for provenance_json in [
12923            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12924            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12925        ] {
12926            let registry = Arc::new(Registry::default());
12927            let handler = ControlHandler::new(registry);
12928            let hello = Frame::build(
12929                FrameType::Hello,
12930                control_flags(),
12931                0,
12932                0,
12933                220,
12934                serde_json::to_vec(&ModuleHelloBody {
12935                    manifest: ModuleManifest::builder("built", "0.1.0")
12936                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12937                        .build(),
12938                    protocol_ver: PROTOCOL_VERSION,
12939                    control_ops: None,
12940                    launch_nonce: None,
12941                })
12942                .unwrap(),
12943            )
12944            .unwrap();
12945            assert_eq!(
12946                handler
12947                    .handle_control(ConnectionId::new(220), hello)
12948                    .unwrap()[0]
12949                    .header
12950                    .ty,
12951                FrameType::HelloAck
12952            );
12953            let request = Frame::build(
12954                FrameType::Request,
12955                control_flags(),
12956                0,
12957                0,
12958                221,
12959                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12960            )
12961            .unwrap();
12962            let response = handler.handle_catalog_list(request, None).unwrap();
12963            let ClientControlResponse::CatalogList { modules, .. } =
12964                serde_json::from_slice(&response[0].body).unwrap()
12965            else {
12966                panic!("expected catalog.list");
12967            };
12968            assert_eq!(modules.len(), 1);
12969            assert_eq!(
12970                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12971                format!(
12972                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12973                )
12974                .as_bytes()
12975            );
12976        }
12977    }
12978
12979    #[test]
12980    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12981        let registry = Arc::new(Registry::default());
12982        let handler = ControlHandler::new(Arc::clone(&registry));
12983        let hello = Frame::build(
12984            FrameType::Hello,
12985            control_flags(),
12986            0,
12987            0,
12988            220,
12989            serde_json::to_vec(&ModuleHelloBody {
12990                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12991                protocol_ver: PROTOCOL_VERSION,
12992                control_ops: None,
12993                launch_nonce: Some("unverified".to_string()),
12994            })
12995            .unwrap(),
12996        )
12997        .unwrap();
12998        assert_eq!(
12999            handler
13000                .handle_control(ConnectionId::new(220), hello)
13001                .unwrap()[0]
13002                .header
13003                .ty,
13004            FrameType::HelloAck
13005        );
13006        let request = Frame::build(
13007            FrameType::Request,
13008            control_flags(),
13009            0,
13010            0,
13011            221,
13012            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13013        )
13014        .unwrap();
13015        let response = handler.handle_catalog_list(request, None).unwrap();
13016        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
13017        assert!(wire["modules"][0].get("provenance").is_none());
13018        let ClientControlResponse::CatalogList { modules, .. } =
13019            serde_json::from_slice(&response[0].body).unwrap()
13020        else {
13021            panic!("expected catalog.list");
13022        };
13023        assert_eq!(
13024            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
13025            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
13026        );
13027        assert!(!modules[0].nonce_verified);
13028        assert!(modules[0].provenance.is_none());
13029    }
13030
13031    // Preserve the legacy-field byte pins while discovery adds optional facts.
13032    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
13033        assert_eq!(entry.first_party, Some(false));
13034        entry.incarnation = None;
13035        entry.spawn = None;
13036        entry.first_party = None;
13037        entry.origin = None;
13038        entry.requested_declarations_digest = None;
13039        entry.approved_declarations_digest = None;
13040        entry
13041    }
13042
13043    #[test]
13044    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
13045        let registry = Arc::new(Registry::default());
13046        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13047            [("vault".to_string(), true), ("squatter".to_string(), true)],
13048            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13049        );
13050        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
13051        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13052            provides: vec!["credentials-provider/v1".to_string()],
13053            requires: Vec::new(),
13054            must_never_reach: Vec::new(),
13055        });
13056        let frame = Frame::build(
13057            FrameType::Hello,
13058            control_flags(),
13059            0,
13060            0,
13061            77,
13062            serde_json::to_vec(&ModuleHelloBody {
13063                manifest: squatter,
13064                protocol_ver: PROTOCOL_VERSION,
13065                control_ops: None,
13066                launch_nonce: None,
13067            })
13068            .expect("HELLO serializes"),
13069        )
13070        .expect("HELLO frame builds");
13071        let response = handler
13072            .handle_control(ConnectionId::new(77), frame)
13073            .expect("reserved claim receives a typed refusal");
13074        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13075        assert_eq!(
13076            registry
13077                .active_registration_count()
13078                .expect("registry reads"),
13079            0,
13080            "a reserved capability refusal must not leave a catalog entry"
13081        );
13082    }
13083
13084    #[test]
13085    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
13086        for settlement in ["timeout", "inconclusive", "drop"] {
13087            let breakers = RouteBindBreakers::default();
13088            let RouteBindAdmission::Admitted {
13089                guard: mut old,
13090                probe: false,
13091            } = breakers.admit("prov")
13092            else {
13093                panic!("ordinary relay admitted")
13094            };
13095            let RouteBindAdmission::Admitted {
13096                guard: mut opener, ..
13097            } = breakers.admit("prov")
13098            else {
13099                panic!("second relay admitted")
13100            };
13101            assert!(
13102                !opener
13103                    .record_timeout(1, Duration::ZERO)
13104                    .unwrap()
13105                    .reopened_after_probe
13106            );
13107            let RouteBindAdmission::Admitted {
13108                guard: mut probe,
13109                probe: true,
13110            } = breakers.admit("prov")
13111            else {
13112                panic!("one cooldown probe admitted")
13113            };
13114            match settlement {
13115                "timeout" => assert!(
13116                    !old.record_timeout(1, Duration::ZERO)
13117                        .unwrap()
13118                        .reopened_after_probe
13119                ),
13120                "inconclusive" => old.record_inconclusive(),
13121                "drop" => drop(old),
13122                _ => unreachable!(),
13123            }
13124            assert!(
13125                matches!(
13126                    breakers.admit("prov"),
13127                    RouteBindAdmission::Refused {
13128                        probe_in_flight: true,
13129                        ..
13130                    }
13131                ),
13132                "{settlement} of a pre-open relay cannot release the real probe"
13133            );
13134            assert!(
13135                probe
13136                    .record_timeout(1, Duration::ZERO)
13137                    .unwrap()
13138                    .reopened_after_probe
13139            );
13140            assert!(matches!(
13141                breakers.admit("prov"),
13142                RouteBindAdmission::Admitted { probe: true, .. }
13143            ));
13144        }
13145        let breakers = RouteBindBreakers::default();
13146        let admit = || match breakers.admit("prov") {
13147            RouteBindAdmission::Admitted { guard, .. } => guard,
13148            _ => panic!("relay admitted"),
13149        };
13150        admit().record_timeout(1, Duration::ZERO);
13151        let mut old_probe = admit();
13152        breakers.reset_for_new_module_connection("prov");
13153        admit().record_timeout(1, Duration::ZERO);
13154        let _new_probe = admit();
13155        old_probe.record_inconclusive();
13156        assert!(matches!(
13157            breakers.admit("prov"),
13158            RouteBindAdmission::Refused {
13159                probe_in_flight: true,
13160                ..
13161            }
13162        ));
13163    }
13164
13165    #[tokio::test]
13166    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13167        for candidate in [false, true] {
13168            let registry = Arc::new(Registry::default());
13169            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13170                [("vault".to_string(), true), ("squatter".to_string(), true)],
13171                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13172            );
13173            let conn = ConnectionId::new(77);
13174            let (ctx, mut rx) = route_ctx(conn);
13175            let initial = capability_manifest("squatter", &[], &[]);
13176            if candidate {
13177                registry
13178                    .register_candidate_with_control_ops(
13179                        initial.clone(),
13180                        PROTOCOL_VERSION,
13181                        conn,
13182                        module_baseline_control_ops(),
13183                    )
13184                    .unwrap();
13185                handler
13186                    .forwarding
13187                    .register_candidate_module_connection(
13188                        conn,
13189                        "squatter".to_string(),
13190                        PROTOCOL_VERSION,
13191                        manifest_concurrency(&initial),
13192                        ctx.egress.clone(),
13193                    )
13194                    .unwrap();
13195            } else {
13196                hello_via_sink(
13197                    &handler,
13198                    &ctx,
13199                    &mut rx,
13200                    hello_frame_with_manifest(initial.clone(), 1),
13201                )
13202                .await;
13203            }
13204            let response = handler
13205                .handle_control_frame(
13206                    &ctx,
13207                    catalog_update_with_capabilities_frame(
13208                        2,
13209                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13210                            .capabilities
13211                            .unwrap(),
13212                    ),
13213                )
13214                .await
13215                .unwrap();
13216            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13217            assert_eq!(
13218                registry
13219                    .get_module_by_connection(conn)
13220                    .unwrap()
13221                    .unwrap()
13222                    .manifest,
13223                initial
13224            );
13225        }
13226    }
13227
13228    #[test]
13229    #[cfg(not(feature = "dev-desktop-approval"))]
13230    fn server_describe_default_build_advertises_no_config_capability() {
13231        let assert_default = |handler: &ControlHandler| {
13232            let request = Frame::build(
13233                FrameType::Request,
13234                control_flags(),
13235                0,
13236                0,
13237                79,
13238                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13239            )
13240            .unwrap();
13241            let responses = handler.handle_server_describe(request).unwrap();
13242            assert_eq!(responses.len(), 1);
13243            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13244            assert_eq!(response["op"], "server.describe");
13245            let capabilities = response["capabilities"]
13246                .as_array()
13247                .expect("capability array");
13248            assert!(
13249                !capabilities.is_empty(),
13250                "exercise an actual describe response, not an empty fixture"
13251            );
13252            assert!(
13253                capabilities
13254                    .iter()
13255                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13256                "a default build must not announce configuration authority: {capabilities:?}"
13257            );
13258        };
13259        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13260        #[cfg(unix)]
13261        {
13262            // A local store does not prove that project-membership validation,
13263            // active-scope usage tracking and approved-program launch selection
13264            // are connected. Defaults must not advertise that authority.
13265            let (_rig, _owner, _supervisor, handler, _spec) =
13266                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13267                );
13268            assert_default(&handler);
13269        }
13270    }
13271
13272    #[test]
13273    fn server_describe_surfaces_required_capability_verdict_fields() {
13274        let registry = Arc::new(Registry::default());
13275        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13276            [
13277                ("consumer".to_string(), true),
13278                ("provider".to_string(), false),
13279            ],
13280            BTreeMap::new(),
13281        );
13282        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13283        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13284            provides: Vec::new(),
13285            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13286                capability: "credentials-provider/v1".to_string(),
13287                need: subc_protocol::manifest::CapabilityNeed::Required,
13288            }],
13289            must_never_reach: Vec::new(),
13290        });
13291        let hello = Frame::build(
13292            FrameType::Hello,
13293            control_flags(),
13294            0,
13295            0,
13296            78,
13297            serde_json::to_vec(&ModuleHelloBody {
13298                manifest: consumer,
13299                protocol_ver: PROTOCOL_VERSION,
13300                control_ops: None,
13301                launch_nonce: None,
13302            })
13303            .expect("HELLO serializes"),
13304        )
13305        .expect("HELLO frame builds");
13306        handler
13307            .handle_control(ConnectionId::new(78), hello)
13308            .expect("consumer registers");
13309        let describe = Frame::build(
13310            FrameType::Request,
13311            control_flags(),
13312            0,
13313            0,
13314            79,
13315            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13316                .expect("request serializes"),
13317        )
13318        .expect("describe frame builds");
13319        let response = handler
13320            .handle_server_describe(describe)
13321            .expect("server.describe succeeds");
13322        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13323        let requirement = &rendered["capability_requirements"][0];
13324        assert_eq!(requirement["consumer"], "consumer");
13325        assert_eq!(requirement["verdict"], "never_provided");
13326        assert_eq!(requirement["episode_seq"], 1);
13327        assert_eq!(requirement["config_satisfiable"], false);
13328        assert_eq!(requirement["runtime_available"], false);
13329        assert!(requirement["detail"]
13330            .as_str()
13331            .expect("detail string")
13332            .contains("credentials-provider/v1"));
13333    }
13334
13335    /// Register a consumer that requires `project-identity/v1` and the provider
13336    /// of it, optionally mark daemon shutdown as begun, then deregister the
13337    /// provider as its connection closes. Returns the `capability.requirement`
13338    /// events that deregistration logged and the verdict the evaluator then
13339    /// holds for the requirement (the one `route.open` refusals read).
13340    fn deregister_required_provider(
13341        daemon_shutdown_begun: bool,
13342    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13343        const CAPABILITY: &str = "project-identity/v1";
13344        let registry = Arc::new(Registry::default());
13345        let daemon_shutdown = DaemonShutdownFlag::default();
13346        let handler = ControlHandler::new(Arc::clone(&registry))
13347            .with_capability_config(
13348                [
13349                    ("consumer".to_string(), true),
13350                    ("provider".to_string(), true),
13351                ],
13352                BTreeMap::new(),
13353            )
13354            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13355        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13356        consumer.capabilities = Some(CapabilityDeclarations {
13357            provides: Vec::new(),
13358            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13359                capability: CAPABILITY.to_string(),
13360                need: subc_protocol::manifest::CapabilityNeed::Required,
13361            }],
13362            must_never_reach: Vec::new(),
13363        });
13364        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13365        let provider_conn = ConnectionId::new(182);
13366        for (conn, manifest, corr) in [
13367            (ConnectionId::new(181), consumer, 181),
13368            (provider_conn, provider, 182),
13369        ] {
13370            let hello = handler
13371                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13372                .expect("module registers");
13373            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13374        }
13375        assert_eq!(
13376            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13377            Some(CapabilityVerdict::Provided),
13378            "the registered provider must satisfy the requirement first"
13379        );
13380        if daemon_shutdown_begun {
13381            daemon_shutdown.set_for_test();
13382        }
13383
13384        let capture = EventCapture::default();
13385        let _subscriber =
13386            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13387        handler
13388            .cleanup_connection(provider_conn)
13389            .expect("provider deregisters");
13390        let events = capture
13391            .events()
13392            .into_iter()
13393            .filter(|event| {
13394                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13395            })
13396            .collect();
13397        (
13398            events,
13399            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13400        )
13401    }
13402
13403    #[test]
13404    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13405        let (events, verdict) = deregister_required_provider(true);
13406        assert_eq!(
13407            verdict,
13408            Some(CapabilityVerdict::NeverProvided),
13409            "shutdown must not change the verdict route.open refusals read"
13410        );
13411        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13412        let event = &events[0];
13413        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13414        assert_eq!(
13415            event.fields.get("cause").map(String::as_str),
13416            Some("\"daemon_shutdown\""),
13417            "{event:?}"
13418        );
13419        assert_eq!(
13420            event.fields.get("verdict").map(String::as_str),
13421            Some("\"never_provided\""),
13422            "{event:?}"
13423        );
13424    }
13425
13426    #[test]
13427    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13428        let (events, verdict) = deregister_required_provider(false);
13429        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13430        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13431        let event = &events[0];
13432        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13433        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13434        assert_eq!(
13435            event.fields.get("verdict").map(String::as_str),
13436            Some("\"never_provided\""),
13437            "{event:?}"
13438        );
13439    }
13440
13441    #[test]
13442    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13443        let registry = Arc::new(Registry::default());
13444        let handler = ControlHandler::new(Arc::clone(&registry));
13445        let hello = handler
13446            .handle_control(
13447                ConnectionId::new(101),
13448                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13449            )
13450            .expect("legacy HELLO registers");
13451        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13452
13453        let request = Frame::build(
13454            FrameType::Request,
13455            control_flags(),
13456            0,
13457            0,
13458            102,
13459            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13460                .expect("catalog request serializes"),
13461        )
13462        .expect("catalog request frame builds");
13463        let response = handler
13464            .handle_catalog_list(request, None)
13465            .expect("catalog list succeeds");
13466        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13467        assert!(
13468            body["modules"][0].get("capabilities").is_none(),
13469            "legacy manifest must retain an absent capabilities field on catalog.list"
13470        );
13471    }
13472
13473    #[test]
13474    fn hello_ack_omits_storage_when_no_storage_config() {
13475        let registry = Arc::new(Registry::default());
13476        let handler = ControlHandler::new(Arc::clone(&registry));
13477        let responses = handler
13478            .handle_control(
13479                ConnectionId::new(1),
13480                hello_frame("aft", PROTOCOL_VERSION, 7),
13481            )
13482            .unwrap();
13483        let ack = parse_ack(&responses[0]);
13484        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13485        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13486    }
13487
13488    #[tokio::test]
13489    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13490        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13491        let registry = Arc::new(Registry::default());
13492        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13493        let responses = handler
13494            .handle_control(
13495                ConnectionId::new(1),
13496                hello_frame("aft", PROTOCOL_VERSION, 7),
13497            )
13498            .unwrap();
13499        let ack = parse_ack(&responses[0]);
13500        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13501
13502        let described = handler
13503            .handle_control_frame(
13504                &route_ctx(ConnectionId::new(2)).0,
13505                Frame::build(
13506                    FrameType::Request,
13507                    control_flags(),
13508                    0,
13509                    0,
13510                    9,
13511                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13512                )
13513                .unwrap(),
13514            )
13515            .await
13516            .unwrap();
13517        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13518            serde_json::from_slice(&described[0].body).unwrap()
13519        else {
13520            panic!("server.describe answered with another shape");
13521        };
13522        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13523    }
13524
13525    #[test]
13526    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13527        // With a central sqlite storage policy, each registering module gets its
13528        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13529        let registry = Arc::new(Registry::default());
13530        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13531            crate::daemon_config::StorageConfig::Sqlite {
13532                data_home: std::path::PathBuf::from("/data"),
13533            },
13534        ));
13535
13536        let responses = handler
13537            .handle_control(
13538                ConnectionId::new(1),
13539                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13540            )
13541            .unwrap();
13542        let ack = parse_ack(&responses[0]);
13543        assert_eq!(
13544            ack.storage,
13545            Some(serde_json::json!({
13546                "module_id": "alfonso-routing",
13547                "storage_namespace": "default",
13548                "isolation": { "kind": "module" },
13549                "backend": {
13550                    "backend": "sqlite",
13551                    "path": "/data/cortexkit/alfonso-routing/store.db"
13552                }
13553            })),
13554            "the delivered descriptor is the module's own sqlite store path"
13555        );
13556    }
13557
13558    #[test]
13559    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13560        let registry = Arc::new(Registry::default());
13561        let handler = ControlHandler::new(Arc::clone(&registry));
13562        let conn = ConnectionId::new(1);
13563        let responses = handler
13564            .handle_control(
13565                conn,
13566                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13567            )
13568            .unwrap();
13569        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13570        let registration = registry.get_module("aft").unwrap().unwrap();
13571        assert_eq!(registration.control_ops, module_baseline_control_ops());
13572
13573        let frame =
13574            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13575        assert!(handler
13576            .guard_module_control_op(&frame, "aft", "route.bind")
13577            .unwrap()
13578            .is_none());
13579        let error = handler
13580            .guard_module_control_op(&frame, "aft", "test.synthetic")
13581            .unwrap()
13582            .expect("synthetic ungranted op should be rejected");
13583        assert_eq!(error.header.ty, FrameType::Error);
13584        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13585    }
13586
13587    #[test]
13588    fn hello_control_ops_some_adds_optional_grants() {
13589        let registry = Arc::new(Registry::default());
13590        let handler = ControlHandler::new(Arc::clone(&registry));
13591        handler
13592            .handle_control(
13593                ConnectionId::new(1),
13594                hello_frame_with_control_ops(
13595                    "aft",
13596                    PROTOCOL_VERSION,
13597                    7,
13598                    Some(vec![
13599                        "future.synthetic".to_string(),
13600                        "route.bind".to_string(),
13601                    ]),
13602                ),
13603            )
13604            .unwrap();
13605        let registration = registry.get_module("aft").unwrap().unwrap();
13606        assert_eq!(
13607            registration.control_ops,
13608            vec![
13609                "route.bind".to_string(),
13610                "route.status".to_string(),
13611                "future.synthetic".to_string(),
13612            ]
13613        );
13614        let frame =
13615            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13616        assert!(handler
13617            .guard_module_control_op(&frame, "aft", "future.synthetic")
13618            .unwrap()
13619            .is_none());
13620    }
13621
13622    #[tokio::test]
13623    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13624        let registry = Arc::new(Registry::default());
13625        let forwarding = Arc::new(ForwardingTable::default());
13626        let handler =
13627            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13628        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13629        hello_via_sink(
13630            &handler,
13631            &module_ctx,
13632            &mut module_rx,
13633            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13634        )
13635        .await;
13636
13637        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13638        let responses = handler
13639            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13640            .await
13641            .unwrap();
13642        assert_eq!(responses.len(), 1);
13643        assert_eq!(responses[0].header.ty, FrameType::Error);
13644        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13645        assert!(module_rx.try_recv().is_err());
13646    }
13647
13648    #[tokio::test]
13649    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13650        let registry = Arc::new(Registry::default());
13651        let forwarding = Arc::new(ForwardingTable::default());
13652        let handler =
13653            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13654        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13655        hello_via_sink(
13656            &handler,
13657            &module_ctx,
13658            &mut module_rx,
13659            hello_frame_with_control_ops(
13660                "aft",
13661                PROTOCOL_VERSION,
13662                7,
13663                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13664            ),
13665        )
13666        .await;
13667
13668        let project_root = unique_project_root("demux");
13669        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13670        let route_handler = handler.clone();
13671        let route_task = tokio::spawn(async move {
13672            route_handler
13673                .handle_control_frame(
13674                    &route_client_ctx,
13675                    route_open_frame(100, "aft", project_root),
13676                )
13677                .await
13678                .unwrap()
13679        });
13680        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13681            .await
13682            .unwrap()
13683            .unwrap();
13684        assert!(matches!(
13685            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13686            ModuleControlRequest::RouteBind { .. }
13687        ));
13688
13689        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13690        let health_handler = handler.clone();
13691        let health_task = tokio::spawn(async move {
13692            health_handler
13693                .handle_control_frame(
13694                    &health_client_ctx,
13695                    supervisor_health_probe_frame(101, "aft"),
13696                )
13697                .await
13698                .unwrap()
13699        });
13700        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13701            .await
13702            .unwrap()
13703            .unwrap();
13704        assert_eq!(
13705            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13706            ModuleControlRequest::HealthCheck {}
13707        );
13708
13709        handler
13710            .handle_control_frame(
13711                &module_ctx,
13712                health_response(health_frame.header.corr, HealthStatus::Degraded),
13713            )
13714            .await
13715            .unwrap();
13716        let health_response = health_task.await.unwrap();
13717        assert_eq!(health_response.len(), 1);
13718        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13719            ClientControlResponse::SupervisorHealthProbe {
13720                module_id,
13721                status,
13722                detail,
13723                metrics,
13724            } => {
13725                assert_eq!(module_id, "aft");
13726                assert_eq!(status, HealthStatus::Degraded);
13727                assert_eq!(detail.as_deref(), Some("warming"));
13728                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13729            }
13730            other => panic!("unexpected health response: {other:?}"),
13731        }
13732
13733        handler
13734            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13735            .await
13736            .unwrap();
13737        let route_response = route_task.await.unwrap();
13738        assert!(route_response.is_empty());
13739        let published = route_client_rx.recv().await.unwrap();
13740        assert!(matches!(
13741            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13742            ClientControlResponse::RouteOpen { .. }
13743        ));
13744    }
13745
13746    /// Start one `route.open` on `client_connection` and return its still-running
13747    /// handler task together with the `route.bind` the module received for it.
13748    /// The handler blocks until the module answers, so it has to run as a task
13749    /// while the test drives the module side.
13750    async fn relay_route_open(
13751        handler: &ControlHandler,
13752        client_connection: ConnectionId,
13753        client_egress: &FrameSink,
13754        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13755        corr: u64,
13756        module_id: &str,
13757        project_root_label: &str,
13758    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13759        let ctx = RouteCtx {
13760            connection_id: client_connection,
13761            egress: client_egress.clone(),
13762        };
13763        let handler = handler.clone();
13764        let project_root = unique_project_root(project_root_label);
13765        let module_id = module_id.to_string();
13766        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13767        let task = tokio::spawn(async move {
13768            let _guard = tracing::dispatcher::set_default(&dispatch);
13769            handler
13770                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13771                .await
13772                .unwrap()
13773        });
13774        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13775            .await
13776            .expect("module receives the relayed route.bind")
13777            .expect("module egress is open");
13778        (task, bind.frame)
13779    }
13780
13781    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13782        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13783            ModuleControlRequest::RouteBind {
13784                route_channel,
13785                epoch,
13786                ..
13787            } => (route_channel, epoch),
13788            other => panic!("expected a route.bind request, got {other:?}"),
13789        }
13790    }
13791
13792    fn published_route(frame: &Frame) -> (u16, u32) {
13793        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13794            ClientControlResponse::RouteOpen {
13795                route_channel,
13796                route_epoch,
13797                ..
13798            } => (route_channel, route_epoch),
13799            other => panic!("expected a route.open response, got {other:?}"),
13800        }
13801    }
13802
13803    /// Reproduction of a production outage. A client had `route.open`s in
13804    /// flight to a module and was already marked closing -- its egress had refused a
13805    /// module frame, so the daemon asked its connection to end -- while its sink
13806    /// was still open. When the module acked those binds, the daemon refused to
13807    /// commit a route for a closing client, and that refusal was returned from
13808    /// the MODULE connection's frame handler, where a router error that has no
13809    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13810    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13811    /// its tools for hours -- one client's teardown took down a connection
13812    /// carrying ~170 other routes.
13813    ///
13814    /// The window is opened here by calling the production path that opens it
13815    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13816    /// state that matters is "in `closing_connections`, sink still open, relay
13817    /// still pending", and it lasts only from the close request until the
13818    /// connection loop reacts to it; a socket-level test can flood a client into
13819    /// that escalation but cannot pin the module's ack inside the window. Closing
13820    /// the socket instead takes the other path entirely -- connection teardown
13821    /// removes the pending relay under the same lock, so the ack finds nothing.
13822    #[tokio::test]
13823    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13824        let registry = Arc::new(Registry::default());
13825        let forwarding = Arc::new(ForwardingTable::default());
13826        let handler =
13827            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13828
13829        let module_connection = ConnectionId::new(30);
13830        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13831        hello_via_sink(
13832            &handler,
13833            &module_ctx,
13834            &mut module_rx,
13835            hello_frame("aft", PROTOCOL_VERSION, 7),
13836        )
13837        .await;
13838
13839        let dying_client = ConnectionId::new(31);
13840        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13841
13842        // A published route on the dying client. The escalation below only marks
13843        // a connection closing for a route it has already published.
13844        let (first_task, first_bind) = relay_route_open(
13845            &handler,
13846            dying_client,
13847            &dying_ctx.egress,
13848            &mut module_rx,
13849            100,
13850            "aft",
13851            "closing-first",
13852        )
13853        .await;
13854        handler
13855            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13856            .await
13857            .unwrap();
13858        assert!(first_task.await.unwrap().is_empty());
13859        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13860
13861        // A second route.open from the same client, relayed and awaiting its ack.
13862        let (second_task, second_bind) = relay_route_open(
13863            &handler,
13864            dying_client,
13865            &dying_ctx.egress,
13866            &mut module_rx,
13867            101,
13868            "aft",
13869            "closing-second",
13870        )
13871        .await;
13872        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13873
13874        // The window: the client is closing, its sink is still open, and its
13875        // second bind is still pending.
13876        assert!(forwarding
13877            .escalate_client_delivery_failure(
13878                dying_client,
13879                first_channel,
13880                first_epoch,
13881                CloseReason::new(
13882                    "module_to_client_delivery_failed",
13883                    "client egress refused a module frame",
13884                ),
13885                crate::forwarding::UndeliveredFrame {
13886                    module_id: None,
13887                    sink: &dying_ctx.egress,
13888                },
13889            )
13890            .unwrap());
13891        assert!(!dying_ctx.egress.is_closed());
13892
13893        // The frame that used to end the module connection.
13894        let ack = handler
13895            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13896            .await;
13897        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13898        if module_loop_error.is_some() {
13899            // What the server's connection loop does with a router error that has
13900            // no ERROR-frame translation: end the connection, which releases the
13901            // module's registration and every route on it.
13902            handler.cleanup_connection(module_connection).unwrap();
13903        }
13904        // Read the module's next frame before opening the co-tenant's route, so
13905        // the GOODBYE assertion below is about THIS ack and not about later
13906        // traffic. `None` means the module was told nothing.
13907        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13908            .await
13909            .ok()
13910            .flatten();
13911
13912        // 1. The module connection is still registered.
13913        assert!(
13914            registry
13915                .get_module_by_connection(module_connection)
13916                .unwrap()
13917                .is_some(),
13918            "one client's closing connection ended the shared module connection: \
13919             {module_loop_error:?}"
13920        );
13921        // ...and still serving: another client can open and use a route on it.
13922        let cotenant = ConnectionId::new(32);
13923        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13924        let (cotenant_task, cotenant_bind) = relay_route_open(
13925            &handler,
13926            cotenant,
13927            &cotenant_ctx.egress,
13928            &mut module_rx,
13929            102,
13930            "aft",
13931            "closing-cotenant",
13932        )
13933        .await;
13934        handler
13935            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13936            .await
13937            .unwrap();
13938        assert!(cotenant_task.await.unwrap().is_empty());
13939        let (cotenant_channel, cotenant_epoch) =
13940            published_route(&cotenant_rx.recv().await.unwrap());
13941        assert!(matches!(
13942            forwarding
13943                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13944                .unwrap(),
13945            DataRoute::Client(DataRouteState::Bound(_))
13946        ));
13947
13948        // 2. The module was told to drop the binding it created for the route
13949        //    that will never be published.
13950        let goodbye = post_ack_module_frame
13951            .expect("module receives a GOODBYE for the abandoned route channel");
13952        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13953        assert_eq!(goodbye.header.channel, abandoned_channel);
13954        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13955
13956        // 3. The dying client received nothing: no route was ever published to
13957        //    it. Its route.open is answered as unavailable, which the connection
13958        //    loop would write to a socket that is already going away.
13959        assert!(dying_rx.try_recv().is_err());
13960        let second_response = second_task.await.unwrap();
13961        assert_eq!(second_response.len(), 1);
13962        assert_eq!(
13963            parse_error(&second_response[0])["code"],
13964            "target_unavailable"
13965        );
13966    }
13967
13968    /// One `catalog.list` as a client sees it: the generation and the listed
13969    /// module ids with their readiness.
13970    async fn catalog_snapshot(
13971        handler: &ControlHandler,
13972        client_ctx: &RouteCtx,
13973        corr: u64,
13974    ) -> (u64, Vec<(String, bool)>) {
13975        let body =
13976            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13977        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13978        let reply = handler
13979            .handle_control_frame(client_ctx, request)
13980            .await
13981            .unwrap()
13982            .pop()
13983            .unwrap();
13984        let ClientControlResponse::CatalogList {
13985            generation,
13986            modules,
13987            ..
13988        } = serde_json::from_slice(&reply.body).unwrap()
13989        else {
13990            panic!("not a catalog.list reply");
13991        };
13992        (
13993            generation,
13994            modules
13995                .into_iter()
13996                .map(|entry| (entry.module_id, entry.ready))
13997                .collect(),
13998        )
13999    }
14000
14001    /// A handler whose HELLO for module "aft" on connection 40 is parked
14002    /// between reserving its registry entry and installing its forwarding
14003    /// endpoint. Returns the handler, the two-party barrier (wait once to know
14004    /// the HELLO is parked, once more to release it), the HELLO's thread, and
14005    /// the module's context and receiver.
14006    fn hello_held_before_forwarding() -> (
14007        ControlHandler,
14008        Arc<std::sync::Barrier>,
14009        std::thread::JoinHandle<Vec<Frame>>,
14010        RouteCtx,
14011        mpsc::Receiver<crate::router::OutboundFrame>,
14012    ) {
14013        let hold = Arc::new(std::sync::Barrier::new(2));
14014        let handler = ControlHandler::with_forwarding(
14015            Arc::new(Registry::default()),
14016            Arc::new(ForwardingTable::default()),
14017        )
14018        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
14019        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14020        let hello = {
14021            let handler = handler.clone();
14022            let module_ctx = module_ctx.clone();
14023            std::thread::spawn(move || {
14024                handler
14025                    .handle_hello(
14026                        module_ctx.connection_id,
14027                        Some(module_ctx.egress.clone()),
14028                        hello_frame("aft", PROTOCOL_VERSION, 7),
14029                    )
14030                    .unwrap()
14031            })
14032        };
14033        (handler, hold, hello, module_ctx, module_rx)
14034    }
14035
14036    /// If a lookup can acquire the registry while publication is parked, let
14037    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
14038    /// after the lookup has tried the lock. Both schedules avoid timing guesses
14039    /// and return the actual lookup result, including an unpublished snapshot
14040    /// when the publication lock is missing.
14041    fn lookup_during_hello_publication<T: Send + 'static>(
14042        registry: &Registry,
14043        hold: &std::sync::Barrier,
14044        lookup: impl FnOnce() -> T + Send + 'static,
14045    ) -> T {
14046        let attempted = registry.observe_next_lock_attempt();
14047        let reader = std::thread::spawn(lookup);
14048        if attempted.recv().unwrap() {
14049            let result = reader.join().unwrap();
14050            hold.wait();
14051            result
14052        } else {
14053            hold.wait();
14054            reader.join().unwrap()
14055        }
14056    }
14057
14058    #[test]
14059    fn catalog_read_after_hello_ack_waits_for_publication() {
14060        let registry = Arc::new(Registry::default());
14061        let hold = Arc::new(std::sync::Barrier::new(2));
14062        let mut handler = ControlHandler::with_forwarding(
14063            Arc::clone(&registry),
14064            Arc::new(ForwardingTable::default()),
14065        );
14066        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
14067        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14068        let hello = {
14069            let handler = handler.clone();
14070            std::thread::spawn(move || {
14071                handler
14072                    .handle_hello(
14073                        module_ctx.connection_id,
14074                        Some(module_ctx.egress),
14075                        hello_frame("aft", PROTOCOL_VERSION, 7),
14076                    )
14077                    .unwrap()
14078            })
14079        };
14080        hold.wait();
14081        assert_eq!(
14082            module_rx.try_recv().unwrap().frame.header.ty,
14083            FrameType::HelloAck
14084        );
14085        let replies = lookup_during_hello_publication(&registry, &hold, move || {
14086            // A different connection can issue catalog.list as soon as the
14087            // module has read its ACK, even while HELLO has not returned.
14088            let request = Frame::build(
14089                FrameType::Request,
14090                control_flags(),
14091                0,
14092                0,
14093                300,
14094                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
14095            )
14096            .unwrap();
14097            handler.handle_catalog_list(request, None).unwrap()
14098        });
14099        assert!(hello.join().unwrap().is_empty());
14100        let ClientControlResponse::CatalogList {
14101            generation,
14102            modules,
14103            ..
14104        } = serde_json::from_slice(&replies[0].body).unwrap()
14105        else {
14106            panic!("not a catalog.list reply");
14107        };
14108        assert_eq!(
14109            modules
14110                .iter()
14111                .map(|entry| entry.module_id.as_str())
14112                .collect::<Vec<_>>(),
14113            vec!["aft"]
14114        );
14115        assert_eq!(generation, 1);
14116    }
14117
14118    /// While a HELLO has reserved its registry entry but its forwarding
14119    /// endpoint is not installed yet, `route.open` to the module can only be
14120    /// refused. `catalog.list` must not list the module in that window: a
14121    /// client that opens a route as soon as it sees a module listed and ready
14122    /// would be refused for a module the daemon had just advertised. The
14123    /// refusal in the window stays the retryable `target_unavailable`, never
14124    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
14125    /// Once the HELLO completes, the module is listed and a route to it opens.
14126    #[tokio::test]
14127    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
14128        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
14129        let client = ConnectionId::new(41);
14130        let (client_ctx, mut client_rx) = route_ctx(client);
14131
14132        hold.wait();
14133        // Parked: the registry holds "aft", forwarding has no endpoint for it.
14134        assert!(handler.registry.get_module("aft").unwrap().is_some());
14135        assert!(!handler
14136            .forwarding
14137            .has_live_module_connection("aft")
14138            .unwrap());
14139        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
14140        assert!(
14141            listed.is_empty(),
14142            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
14143        );
14144        let refused = handler
14145            .handle_control_frame(
14146                &client_ctx,
14147                route_open_frame(301, "aft", unique_project_root("listed-window")),
14148            )
14149            .await
14150            .unwrap();
14151        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14152        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14153        let duplicate = handler
14154            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14155            .await
14156            .unwrap();
14157        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14158
14159        hold.wait();
14160        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14161        let ack = module_rx.try_recv().unwrap().frame;
14162        assert_eq!(ack.header.ty, FrameType::HelloAck);
14163        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14164        assert_eq!(listed, vec![("aft".to_string(), true)]);
14165
14166        let (open_task, bind) = relay_route_open(
14167            &handler,
14168            client,
14169            &client_ctx.egress,
14170            &mut module_rx,
14171            303,
14172            "aft",
14173            "listed-after",
14174        )
14175        .await;
14176        assert!(handler
14177            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14178            .await
14179            .unwrap()
14180            .is_empty());
14181        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14182        published_route(&client_rx.try_recv().unwrap().frame);
14183    }
14184
14185    /// A catalog watcher keys on the generation: when it changes, it re-reads
14186    /// the listing. So the generation must advance exactly when the module
14187    /// appears. If it advanced while the module was still hidden, a watcher
14188    /// would read the new generation without the module, and the module would
14189    /// later appear under that same generation with nothing telling the
14190    /// watcher to look again.
14191    #[tokio::test]
14192    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14193        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14194        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14195        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14196
14197        hold.wait();
14198        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14199        assert!(listed.is_empty());
14200        assert_eq!(
14201            during, before,
14202            "the generation moved while the module was not listed"
14203        );
14204
14205        hold.wait();
14206        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14207        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14208        assert_eq!(listed, vec![("aft".to_string(), true)]);
14209        assert_eq!(
14210            after,
14211            before + 1,
14212            "the module appeared without exactly one generation bump"
14213        );
14214    }
14215
14216    /// A HELLO whose forwarding endpoint cannot be installed (here the
14217    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14218    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14219    /// and the catalog generation where it was.
14220    #[tokio::test]
14221    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14222        let registry = Arc::new(Registry::default());
14223        let handler = ControlHandler::with_forwarding(
14224            Arc::clone(&registry),
14225            Arc::new(ForwardingTable::default()),
14226        );
14227        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14228        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14229        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14230        drop(module_rx);
14231
14232        let replies = handler
14233            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14234            .await
14235            .unwrap();
14236        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14237        assert!(registry.get_module("aft").unwrap().is_none());
14238        assert!(registry
14239            .get_module_by_connection(module_ctx.connection_id)
14240            .unwrap()
14241            .is_none());
14242        assert_eq!(
14243            catalog_snapshot(&handler, &client_ctx, 301).await,
14244            (before, Vec::new())
14245        );
14246    }
14247
14248    /// A handler whose `route.open` parks after queueing the route.bind and
14249    /// before marking it enqueued, with module "aft" registered on connection
14250    /// 40. Returns the two-party barrier that parks and releases it.
14251    async fn route_open_held_after_bind_send() -> (
14252        ControlHandler,
14253        Arc<tokio::sync::Barrier>,
14254        RouteCtx,
14255        mpsc::Receiver<crate::router::OutboundFrame>,
14256    ) {
14257        let hold = Arc::new(tokio::sync::Barrier::new(2));
14258        let handler = ControlHandler::with_forwarding(
14259            Arc::new(Registry::default()),
14260            Arc::new(ForwardingTable::default()),
14261        )
14262        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14263        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14264        hello_via_sink(
14265            &handler,
14266            &module_ctx,
14267            &mut module_rx,
14268            hello_frame("aft", PROTOCOL_VERSION, 7),
14269        )
14270        .await;
14271        (handler, hold, module_ctx, module_rx)
14272    }
14273
14274    /// A fast module acks the route.bind, and the reader commits the route,
14275    /// before `route.open` has marked the relay enqueued. The daemon used to
14276    /// read the missing relay as an abandoned bind and send the module a
14277    /// GOODBYE for the route it had just committed: the client was told its
14278    /// route was open, the module unbound the channel, and the client's first
14279    /// request was dropped on the module side as unbound.
14280    #[tokio::test]
14281    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14282        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14283        let client = ConnectionId::new(41);
14284        let (client_ctx, mut client_rx) = route_ctx(client);
14285
14286        let (open_task, bind) = relay_route_open(
14287            &handler,
14288            client,
14289            &client_ctx.egress,
14290            &mut module_rx,
14291            200,
14292            "aft",
14293            "acked-before-mark",
14294        )
14295        .await;
14296        let (module_channel, module_epoch) = route_bind_channel(&bind);
14297        // route.open is now parked between queueing the bind and marking it.
14298        hold.wait().await;
14299
14300        // The module answers inside that window, and the route commits.
14301        assert!(handler
14302            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14303            .await
14304            .unwrap()
14305            .is_empty());
14306        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14307
14308        hold.wait().await;
14309        assert!(
14310            open_task.await.unwrap().is_empty(),
14311            "route.open answers accepted"
14312        );
14313
14314        // Every frame route.open could have sent is already queued, because it
14315        // has returned; the module must have been sent nothing.
14316        match module_rx.try_recv() {
14317            Err(mpsc::error::TryRecvError::Empty) => {}
14318            Ok(outbound) => panic!(
14319                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14320                outbound.frame.header.ty,
14321                outbound.frame.header.channel,
14322                outbound.frame.header.epoch
14323            ),
14324            Err(err) => panic!("module egress closed: {err}"),
14325        }
14326
14327        // The client's first request on the route is the next thing the module
14328        // reads, on the binding it just created.
14329        let router = Router::with_control_handler(Arc::new(handler.clone()));
14330        let request = Frame::build(
14331            FrameType::Request,
14332            Flags::new(true, Priority::Interactive, false),
14333            client_channel,
14334            client_epoch,
14335            201,
14336            b"first request".to_vec(),
14337        )
14338        .unwrap();
14339        router
14340            .route_for_connection(&client_ctx, request)
14341            .await
14342            .unwrap();
14343        let delivered = module_rx.try_recv().unwrap().frame;
14344        assert_eq!(delivered.header.ty, FrameType::Request);
14345        assert_eq!(
14346            (delivered.header.channel, delivered.header.epoch),
14347            (module_channel, module_epoch)
14348        );
14349        assert_eq!(delivered.body, b"first request");
14350    }
14351
14352    /// The client goes away while `route.open` is still queueing the bind, so
14353    /// the relay is dropped with no module reply. The teardown cannot send the
14354    /// GOODBYE itself (it could reach the module ahead of the bind), so
14355    /// `route.open` must send it once the bind is queued; otherwise the module
14356    /// keeps a binding the daemon will never commit.
14357    #[tokio::test]
14358    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14359        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14360        let client = ConnectionId::new(42);
14361        let (client_ctx, _client_rx) = route_ctx(client);
14362
14363        let (open_task, bind) = relay_route_open(
14364            &handler,
14365            client,
14366            &client_ctx.egress,
14367            &mut module_rx,
14368            300,
14369            "aft",
14370            "released-before-mark",
14371        )
14372        .await;
14373        let (module_channel, module_epoch) = route_bind_channel(&bind);
14374        hold.wait().await;
14375
14376        handler.cleanup_connection(client).unwrap();
14377        assert!(
14378            module_rx.try_recv().is_err(),
14379            "client teardown must not GOODBYE a bind route.open is still queueing"
14380        );
14381
14382        hold.wait().await;
14383        let response = open_task.await.unwrap();
14384        assert_eq!(response.len(), 1);
14385        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14386
14387        let goodbye = module_rx
14388            .try_recv()
14389            .expect("module is told to drop the binding the daemon abandoned")
14390            .frame;
14391        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14392        assert_eq!(
14393            (goodbye.header.channel, goodbye.header.epoch),
14394            (module_channel, module_epoch)
14395        );
14396        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14397    }
14398
14399    /// The module acks inside the same window, but the client's egress closed
14400    /// first, so the reader refuses to commit. The ack proves the module holds
14401    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14402    /// send a second one.
14403    #[tokio::test]
14404    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14405        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14406        let client = ConnectionId::new(43);
14407        let (client_ctx, client_rx) = route_ctx(client);
14408
14409        let (open_task, bind) = relay_route_open(
14410            &handler,
14411            client,
14412            &client_ctx.egress,
14413            &mut module_rx,
14414            400,
14415            "aft",
14416            "gone-client-before-mark",
14417        )
14418        .await;
14419        let (module_channel, module_epoch) = route_bind_channel(&bind);
14420        hold.wait().await;
14421
14422        drop(client_rx);
14423        assert!(client_ctx.egress.is_closed());
14424        handler
14425            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14426            .await
14427            .unwrap();
14428
14429        hold.wait().await;
14430        let response = open_task.await.unwrap();
14431        assert_eq!(response.len(), 1);
14432        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14433
14434        let goodbye = module_rx
14435            .try_recv()
14436            .expect("module is told to drop the binding it acked")
14437            .frame;
14438        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14439        assert_eq!(
14440            (goodbye.header.channel, goodbye.header.epoch),
14441            (module_channel, module_epoch)
14442        );
14443        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14444        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14445    }
14446
14447    /// The fence at the module-loop boundary, stated as its own contract: which
14448    /// forwarding failures are allowed to end the module connection that is being
14449    /// served. A `ConnectionClosing` naming some client is about that client, and
14450    /// a module connection is shared; the same error naming the module's own
14451    /// connection is about this connection and must stay fatal, as must failures
14452    /// that are about the forwarding table itself.
14453    #[test]
14454    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14455        let handler = ControlHandler::default();
14456        let module_connection = ConnectionId::new(30);
14457        let client_connection = ConnectionId::new(31);
14458
14459        handler
14460            .refuse_to_end_module_connection_for_a_client(
14461                module_connection,
14462                77,
14463                ForwardingError::ConnectionClosing {
14464                    connection_id: client_connection,
14465                },
14466            )
14467            .expect("a closing client must never end the module connection");
14468
14469        assert!(matches!(
14470            handler.refuse_to_end_module_connection_for_a_client(
14471                module_connection,
14472                78,
14473                ForwardingError::ConnectionClosing {
14474                    connection_id: module_connection,
14475                },
14476            ),
14477            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14478                connection_id
14479            })) if connection_id == module_connection
14480        ));
14481        assert!(matches!(
14482            handler.refuse_to_end_module_connection_for_a_client(
14483                module_connection,
14484                79,
14485                ForwardingError::Poisoned,
14486            ),
14487            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14488        ));
14489        assert!(matches!(
14490            handler.refuse_to_end_module_connection_for_a_client(
14491                module_connection,
14492                80,
14493                ForwardingError::StaleModuleEndpoint,
14494            ),
14495            Err(RouterError::Forwarding(
14496                ForwardingError::StaleModuleEndpoint
14497            ))
14498        ));
14499    }
14500
14501    /// The spawn-attestation guard is what stops a connected module from claiming
14502    /// another module's identity and being stamped `Reserved` for it. Every other
14503    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14504    /// correct one is what the rest of the flow needs -- so the guard's rejection
14505    /// branch was never the subject of an assertion, only its acceptance branch.
14506    ///
14507    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14508    /// whole subc-core library suite green; only the forwarding integration tests
14509    /// notice, and they notice for unrelated reasons. This test exists so the
14510    /// refusal itself is asserted where the guard lives: it fails if the identity
14511    /// check stops refusing, which is the direction that matters, since a guard
14512    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14513    #[tokio::test]
14514    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14515        let registry = Arc::new(Registry::default());
14516        let forwarding = Arc::new(ForwardingTable::default());
14517        let supervisor = SupervisorHandle::new();
14518        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14519        let handler =
14520            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14521                .with_supervisor(supervisor);
14522
14523        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14524        hello_via_sink(
14525            &handler,
14526            &target_ctx,
14527            &mut target_rx,
14528            hello_frame("target", PROTOCOL_VERSION, 1),
14529        )
14530        .await;
14531
14532        // A real supervised module id presenting the wrong nonce. This is the
14533        // impersonation case: the attacker knows a privileged module_id, which is
14534        // public, and guesses at the nonce, which is not.
14535        let wrong_nonce = handler
14536            .handle_control_frame(
14537                &route_ctx(ConnectionId::new(91)).0,
14538                route_open_frame_with_admission_facts(
14539                    20,
14540                    "target",
14541                    unique_project_root("admission-facts"),
14542                    Some(subc_control::ConsumerIdentity {
14543                        module_id: "fed".to_string(),
14544                        launch_nonce: "not-the-real-nonce".to_string(),
14545                    }),
14546                    None,
14547                ),
14548            )
14549            .await
14550            .unwrap();
14551        assert_eq!(
14552            parse_error(&wrong_nonce[0])["code"],
14553            "bad_consumer_identity",
14554            "a mismatched launch nonce must be refused, not stamped Reserved"
14555        );
14556
14557        // A module id the supervisor never spawned at all, so no nonce exists to
14558        // compare against. An implementation that treats "no record" as "nothing
14559        // to check" fails open here while passing the case above.
14560        let never_spawned = handler
14561            .handle_control_frame(
14562                &route_ctx(ConnectionId::new(92)).0,
14563                route_open_frame_with_admission_facts(
14564                    21,
14565                    "target",
14566                    unique_project_root("admission-facts"),
14567                    Some(subc_control::ConsumerIdentity {
14568                        module_id: "never-spawned".to_string(),
14569                        launch_nonce: "any-nonce".to_string(),
14570                    }),
14571                    None,
14572                ),
14573            )
14574            .await
14575            .unwrap();
14576        assert_eq!(
14577            parse_error(&never_spawned[0])["code"],
14578            "bad_consumer_identity",
14579            "an unspawned module_id must be refused rather than accepted for lack of a record"
14580        );
14581    }
14582
14583    /// The refusal test above proves the guard says NO. Nothing proved it can say
14584    /// YES, and the difference is not academic: replacing the whole authorization
14585    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14586    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14587    /// library tests GREEN. The one that notices does so by HANGING, because it
14588    /// waits for a bind that can no longer happen.
14589    ///
14590    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14591    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14592    /// hangs too and gets blamed on the runner. So a total revocation of the
14593    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14594    /// to code.
14595    ///
14596    /// The bias is structural rather than accidental. A REFUSAL looks like a
14597    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14598    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14599    /// suite for that reason, and this one is the purest case in the daemon.
14600    ///
14601    /// This test asserts the EFFECT rather than the absence of an error: the module
14602    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14603    /// A guard that admitted nobody would produce no bind at all; one that admitted
14604    /// everybody would stamp the wrong principal, which the refusal test catches.
14605    #[tokio::test]
14606    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14607        let registry = Arc::new(Registry::default());
14608        let forwarding = Arc::new(ForwardingTable::default());
14609        let supervisor = SupervisorHandle::new();
14610        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14611        let handler =
14612            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14613                .with_supervisor(supervisor);
14614
14615        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14616        hello_via_sink(
14617            &handler,
14618            &target_ctx,
14619            &mut target_rx,
14620            hello_frame("target", PROTOCOL_VERSION, 1),
14621        )
14622        .await;
14623
14624        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14625        let route_handler = handler.clone();
14626        let route_task = tokio::spawn(async move {
14627            route_handler
14628                .handle_control_frame(
14629                    &client_ctx,
14630                    route_open_frame_with_admission_facts(
14631                        30,
14632                        "target",
14633                        unique_project_root("admission-facts"),
14634                        Some(subc_control::ConsumerIdentity {
14635                            module_id: "fed".to_string(),
14636                            launch_nonce: "fed-nonce".to_string(),
14637                        }),
14638                        None,
14639                    ),
14640                )
14641                .await
14642                .unwrap()
14643        });
14644
14645        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14646        // the very mutation it exists to catch -- a guard that admits nobody -- no
14647        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14648        // exact defect being fixed: a total revocation detected only as a stalled
14649        // suite, which reads as flakiness and invites a retry. An acceptance test
14650        // that waits for an effect must bound the wait, or a red becomes a hang.
14651        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14652            .await
14653            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14654            .expect("module control channel closed before route.bind");
14655        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14656        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14657            panic!("expected route.bind")
14658        };
14659        assert_eq!(
14660            principal,
14661            Some(Principal::Reserved {
14662                module_id: "fed".to_string()
14663            }),
14664            "a correctly attested consumer must be stamped Reserved for its own id"
14665        );
14666
14667        handler
14668            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14669            .await
14670            .unwrap();
14671        assert!(route_task.await.unwrap().is_empty());
14672        assert!(
14673            matches!(
14674                serde_json::from_slice::<ClientControlResponse>(
14675                    &client_rx.recv().await.unwrap().body
14676                )
14677                .unwrap(),
14678                ClientControlResponse::RouteOpen { .. }
14679            ),
14680            "the route must actually open, not merely avoid an error"
14681        );
14682    }
14683
14684    #[tokio::test(start_paused = true)]
14685    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14686        let registry = Arc::new(Registry::default());
14687        let forwarding = Arc::new(ForwardingTable::default());
14688        let supervisor = SupervisorHandle::new();
14689        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14690        let handler =
14691            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14692                .with_supervisor(supervisor);
14693
14694        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14695        hello_via_sink(
14696            &handler,
14697            &target_ctx,
14698            &mut target_rx,
14699            hello_frame("target", PROTOCOL_VERSION, 1),
14700        )
14701        .await;
14702
14703        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14704        let direct_handler = handler.clone();
14705        let direct_open = tokio::spawn(async move {
14706            direct_handler
14707                .handle_control_frame(
14708                    &direct_ctx,
14709                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14710                )
14711                .await
14712                .unwrap()
14713        });
14714        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14715            .await
14716            .expect("no direct route.bind within 5s")
14717            .expect("target control channel closed before direct route.bind");
14718        handler
14719            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14720            .await
14721            .unwrap();
14722        assert!(direct_open.await.unwrap().is_empty());
14723        let _ = direct_rx.recv().await.unwrap();
14724
14725        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14726        let reserved_handler = handler.clone();
14727        let reserved_open = tokio::spawn(async move {
14728            reserved_handler
14729                .handle_control_frame(
14730                    &reserved_ctx,
14731                    route_open_frame_with_admission_facts(
14732                        3,
14733                        "target",
14734                        unique_project_root("admission-facts"),
14735                        Some(ConsumerIdentity {
14736                            module_id: "fed".to_string(),
14737                            launch_nonce: "fed-nonce".to_string(),
14738                        }),
14739                        None,
14740                    ),
14741                )
14742                .await
14743                .unwrap()
14744        });
14745        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14746            .await
14747            .expect("no reserved route.bind within 5s")
14748            .expect("target control channel closed before reserved route.bind");
14749        handler
14750            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14751            .await
14752            .unwrap();
14753        assert!(reserved_open.await.unwrap().is_empty());
14754        let _ = reserved_rx.recv().await.unwrap();
14755
14756        forwarding
14757            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14758            .unwrap();
14759        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14760        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14761            module_id: Some("target".to_string()),
14762        })
14763        .unwrap();
14764        let census_frame =
14765            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14766        let response = handler
14767            .handle_control_frame(&census_ctx, census_frame)
14768            .await
14769            .unwrap()
14770            .pop()
14771            .unwrap();
14772        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14773        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14774        assert!(matches!(
14775            decoded,
14776            ClientControlResponse::SupervisorRoutes { .. }
14777        ));
14778        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14779        assert_eq!(routes.len(), 2);
14780        assert!(routes.iter().all(|route| route["draining"] == true));
14781        // The census carries WHY: the reason the drain was begun with, in the
14782        // route.closing vocabulary, on every draining route this drain marked.
14783        assert!(
14784            routes.iter().all(|route| route["drain_reason"] == "reload"),
14785            "draining routes must name the drain's reason: {routes:?}"
14786        );
14787        assert!(routes.iter().any(|route| {
14788            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14789        }));
14790        assert!(routes.iter().any(|route| {
14791            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14792        }));
14793
14794        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14795            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14796        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14797            std::fs::write(
14798                &golden_path,
14799                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14800            )
14801            .unwrap();
14802        }
14803        let expected: Value =
14804            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14805        assert_eq!(actual, expected);
14806    }
14807
14808    async fn query_live_roots(
14809        handler: &ControlHandler,
14810        module_ctx: &RouteCtx,
14811    ) -> ModuleControlResponseToModule {
14812        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14813        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14814        let response = handler
14815            .handle_control_frame(module_ctx, frame)
14816            .await
14817            .unwrap()
14818            .pop()
14819            .unwrap();
14820        serde_json::from_slice(&response.body).unwrap()
14821    }
14822
14823    #[tokio::test(start_paused = true)]
14824    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14825        let registry = Arc::new(Registry::default());
14826        let forwarding = Arc::new(ForwardingTable::default());
14827        let handler = ControlHandler::with_forwarding(registry, forwarding);
14828        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14829        hello_via_sink(
14830            &handler,
14831            &target_ctx,
14832            &mut target_rx,
14833            hello_frame("target", PROTOCOL_VERSION, 1),
14834        )
14835        .await;
14836        let root = unique_project_root("live-roots-known");
14837        let path = ProjectRootId::from_path_allowing_missing(root.path())
14838            .unwrap()
14839            .as_path()
14840            .to_path_buf();
14841        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14842        let open_handler = handler.clone();
14843        let opened = tokio::spawn(async move {
14844            open_handler
14845                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14846                .await
14847                .unwrap()
14848        });
14849        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14850            .await
14851            .unwrap()
14852            .unwrap();
14853        handler
14854            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14855            .await
14856            .unwrap();
14857        assert!(opened.await.unwrap().is_empty());
14858        let _ = client_rx.recv().await.unwrap();
14859
14860        let root = unique_project_root("live-roots-pending");
14861        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14862            .unwrap()
14863            .as_path()
14864            .to_path_buf();
14865        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14866        let open_handler = handler.clone();
14867        let pending = tokio::spawn(async move {
14868            open_handler
14869                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14870                .await
14871                .unwrap()
14872        });
14873        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14874            .await
14875            .unwrap()
14876            .unwrap();
14877        let actual = query_live_roots(&handler, &target_ctx).await;
14878        let ModuleControlResponseToModule::LiveRoots {
14879            roots,
14880            unknown_root_bindings,
14881            total_bindings,
14882        } = actual
14883        else {
14884            panic!("expected live roots")
14885        };
14886        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14887        assert_eq!(unknown_root_bindings, 0);
14888        assert_eq!(
14889            roots.len(),
14890            2,
14891            "root-known arm must retain each canonical root"
14892        );
14893        assert_eq!(
14894            total_bindings,
14895            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14896        );
14897        let counts = roots
14898            .iter()
14899            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14900            .collect::<Vec<_>>();
14901        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14902        expected.sort_by(|a, b| a.0.cmp(&b.0));
14903        assert_eq!(
14904            counts, expected,
14905            "roots must sort by path and count pending separately"
14906        );
14907        handler
14908            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14909            .await
14910            .unwrap();
14911        assert!(pending.await.unwrap().is_empty());
14912    }
14913
14914    #[tokio::test(start_paused = true)]
14915    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14916        let forwarding = Arc::new(ForwardingTable::default());
14917        let handler =
14918            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14919        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14920        hello_via_sink(
14921            &handler,
14922            &target_ctx,
14923            &mut target_rx,
14924            hello_frame("target", PROTOCOL_VERSION, 1),
14925        )
14926        .await;
14927        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14928        let pending = forwarding
14929            .begin_route_bind_relay_for_test(
14930                client_ctx.connection_id,
14931                client_ctx.egress.clone(),
14932                2,
14933                "target",
14934            )
14935            .unwrap();
14936        forwarding
14937            .complete_pending_relay(
14938                target_ctx.connection_id,
14939                pending.corr,
14940                RouteBindRelayOutcome::Accepted,
14941            )
14942            .unwrap();
14943        let actual = query_live_roots(&handler, &target_ctx).await;
14944        let ModuleControlResponseToModule::LiveRoots {
14945            roots,
14946            unknown_root_bindings,
14947            total_bindings,
14948        } = actual
14949        else {
14950            panic!("expected live roots")
14951        };
14952        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14953        assert_eq!(
14954            unknown_root_bindings, 1,
14955            "unknown-root arm must not read as no bindings"
14956        );
14957        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14958        assert_eq!(
14959            total_bindings,
14960            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14961        );
14962    }
14963
14964    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14965    /// so the ack has to be on its outbound queue before the module is
14966    /// routable. The connection loop writes a handler's replies only after the
14967    /// handler returns; this test stops in exactly that gap, runs a real
14968    /// route.open from another connection, and only then writes whatever the
14969    /// HELLO handler returned, the way the loop would. If the ack were still a
14970    /// reply, the route.bind request would reach the module first.
14971    #[tokio::test(start_paused = true)]
14972    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14973        let forwarding = Arc::new(ForwardingTable::default());
14974        let handler =
14975            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14976        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14977        let replies = handler
14978            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14979            .await
14980            .unwrap();
14981        let queued_by_hello = module_rx.len();
14982
14983        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14984        let open_handler = handler.clone();
14985        let open = tokio::spawn(async move {
14986            open_handler
14987                .handle_control_frame(
14988                    &client_ctx,
14989                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14990                )
14991                .await
14992                .unwrap()
14993        });
14994        // Let the route.open run until its route.bind is on the module's queue.
14995        let mut spins = 0;
14996        while module_rx.len() == queued_by_hello {
14997            spins += 1;
14998            assert!(spins < 10_000, "route.open never queued a route.bind");
14999            tokio::task::yield_now().await;
15000        }
15001
15002        // Now the connection loop's half: write the HELLO handler's replies.
15003        for reply in replies {
15004            module_ctx.egress.send(reply).await.unwrap();
15005        }
15006
15007        let first = module_rx.recv().await.unwrap().frame;
15008        assert_eq!(
15009            first.header.ty,
15010            FrameType::HelloAck,
15011            "the first frame a registering module reads must be its HELLO_ACK"
15012        );
15013        assert_eq!(first.header.corr, 7);
15014        let second = module_rx.recv().await.unwrap().frame;
15015        assert_eq!(second.header.ty, FrameType::Request);
15016        assert!(
15017            matches!(
15018                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
15019                ModuleControlRequest::RouteBind { .. }
15020            ),
15021            "the route.bind follows the ack"
15022        );
15023        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
15024
15025        handler
15026            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
15027            .await
15028            .unwrap();
15029        assert!(open.await.unwrap().is_empty());
15030        let _ = client_rx.recv().await.unwrap();
15031    }
15032
15033    #[tokio::test(start_paused = true)]
15034    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
15035        let handler = ControlHandler::with_forwarding(
15036            Arc::new(Registry::default()),
15037            Arc::new(ForwardingTable::default()),
15038        );
15039        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
15040        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
15041        hello_via_sink(
15042            &handler,
15043            &first_ctx,
15044            &mut first_rx,
15045            hello_frame("first", PROTOCOL_VERSION, 1),
15046        )
15047        .await;
15048        hello_via_sink(
15049            &handler,
15050            &second_ctx,
15051            &mut second_rx,
15052            hello_frame("second", PROTOCOL_VERSION, 2),
15053        )
15054        .await;
15055        let root = unique_project_root("second-only");
15056        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
15057        let cloned = handler.clone();
15058        let open = tokio::spawn(async move {
15059            cloned
15060                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
15061                .await
15062                .unwrap()
15063        });
15064        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
15065            .await
15066            .unwrap()
15067            .unwrap();
15068        let first = query_live_roots(&handler, &first_ctx).await;
15069        let second = query_live_roots(&handler, &second_ctx).await;
15070        assert!(
15071            matches!(
15072                first,
15073                ModuleControlResponseToModule::LiveRoots {
15074                    total_bindings: 0,
15075                    ..
15076                }
15077            ),
15078            "cross-module scope must not expose another module's roots"
15079        );
15080        assert!(
15081            matches!(
15082                second,
15083                ModuleControlResponseToModule::LiveRoots {
15084                    total_bindings: 1,
15085                    ..
15086                }
15087            ),
15088            "second module must see its pending route"
15089        );
15090        handler
15091            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
15092            .await
15093            .unwrap();
15094        assert!(open.await.unwrap().is_empty());
15095    }
15096
15097    #[tokio::test(start_paused = true)]
15098    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
15099        let handler = ControlHandler::with_forwarding(
15100            Arc::new(Registry::default()),
15101            Arc::new(ForwardingTable::default()),
15102        );
15103        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
15104        hello_via_sink(
15105            &handler,
15106            &target_ctx,
15107            &mut target_rx,
15108            hello_frame("target", PROTOCOL_VERSION, 1),
15109        )
15110        .await;
15111        let actual = query_live_roots(&handler, &target_ctx).await;
15112        let ModuleControlResponseToModule::LiveRoots {
15113            roots,
15114            unknown_root_bindings,
15115            total_bindings,
15116        } = actual
15117        else {
15118            panic!("expected live roots")
15119        };
15120        assert!(roots.is_empty());
15121        assert_eq!(unknown_root_bindings, 0);
15122        assert_eq!(total_bindings, 0);
15123        assert_eq!(
15124            total_bindings,
15125            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
15126        );
15127    }
15128
15129    /// Read the vendored fed corpus rather than hand-building a package.
15130    ///
15131    /// A hand-built object encodes what the test author believed the carrier
15132    /// emits. These vectors are what it actually emits, and one of them exists
15133    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
15134    /// ignores additive unknown fields at the traversal emit terminus."
15135    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
15136        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15137            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
15138        let text = std::fs::read_to_string(&path)
15139            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
15140        let vectors: Vec<(String, Value)> = text
15141            .lines()
15142            .filter(|line| !line.trim().is_empty())
15143            .map(|line| {
15144                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
15145                let id = entry["corpus_id"]
15146                    .as_str()
15147                    .expect("every vector carries a corpus_id")
15148                    .to_string();
15149                (id, entry["package"].clone())
15150            })
15151            .collect();
15152        // Pin the count: a corpus that silently shrinks would take its coverage
15153        // with it, and a suite reading N-1 vectors reports the same clean pass
15154        // as one reading N.
15155        assert_eq!(
15156            vectors.len(),
15157            3,
15158            "vendored fed corpus changed size; re-sync from subc-federation"
15159        );
15160
15161        // Pin what makes the corpus DISCRIMINATING, not just present.
15162        //
15163        // The relay test below takes its expected value from the corpus, so the
15164        // corpus supplies the test's power to detect a lossy relay rather than
15165        // its correctness. A relay that dropped unrecognised fields would still
15166        // be caught -- but only by a package carrying fields it does not know.
15167        // Shrink every package to the handful of keys any implementation would
15168        // recognise and the test keeps passing over an input that can no longer
15169        // fail, which is the same clean green as a corpus that shrank away.
15170        //
15171        // So assert the precondition rather than duplicating the packages here:
15172        // at least one vector must carry a field beyond the small common set.
15173        // That is one claim to maintain instead of nine, and it fails loudly if
15174        // a re-sync ever flattens the corpus.
15175        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15176        let richest = vectors
15177            .iter()
15178            .filter_map(|(_, package)| package.as_object())
15179            .map(|object| {
15180                object
15181                    .keys()
15182                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15183                    .count()
15184            })
15185            .max()
15186            .unwrap_or(0);
15187        assert!(
15188            richest >= 2,
15189            "vendored corpus no longer carries a package with unmodelled fields, \
15190             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15191        );
15192
15193        vectors
15194    }
15195
15196    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15197    ///
15198    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15199    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15200    /// three-key object, so a relay that quietly dropped fields it did not
15201    /// recognise would satisfy it. These vectors carry nine keys including ones
15202    /// this crate has no type for, so a typed relay fails here and only here.
15203    #[tokio::test]
15204    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15205        for (corpus_id, package) in fed_admission_facts_vectors() {
15206            let registry = Arc::new(Registry::default());
15207            let forwarding = Arc::new(ForwardingTable::default());
15208            let supervisor = SupervisorHandle::new();
15209            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15210            let handler =
15211                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15212                    .with_supervisor(supervisor)
15213                    .with_admission_facts_config(
15214                        Some("fed".to_string()),
15215                        Some(vec!["target".to_string()]),
15216                    );
15217
15218            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15219            hello_via_sink(
15220                &handler,
15221                &target_ctx,
15222                &mut target_rx,
15223                hello_frame("target", PROTOCOL_VERSION, 1),
15224            )
15225            .await;
15226
15227            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15228            let route_handler = handler.clone();
15229            let expected = package.clone();
15230            let route_task = tokio::spawn(async move {
15231                route_handler
15232                    .handle_control_frame(
15233                        &client_ctx,
15234                        route_open_frame_with_admission_facts(
15235                            20,
15236                            "target",
15237                            unique_project_root("admission-facts"),
15238                            Some(subc_control::ConsumerIdentity {
15239                                module_id: "fed".to_string(),
15240                                launch_nonce: "fed-nonce".to_string(),
15241                            }),
15242                            Some(package),
15243                        ),
15244                    )
15245                    .await
15246                    .unwrap()
15247            });
15248
15249            let bind_frame = target_rx.recv().await.unwrap();
15250            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15251            let ModuleControlRequest::RouteBind {
15252                admission_facts, ..
15253            } = bind
15254            else {
15255                panic!("{corpus_id}: expected route.bind")
15256            };
15257            assert_eq!(
15258                admission_facts,
15259                Some(expected),
15260                "{corpus_id}: relay must not add, drop or reshape any field"
15261            );
15262
15263            handler
15264                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15265                .await
15266                .unwrap();
15267            route_task.await.unwrap();
15268        }
15269    }
15270
15271    #[tokio::test]
15272    async fn route_bind_never_relays_the_openers_build_class() {
15273        let registry = Arc::new(Registry::default());
15274        let forwarding = Arc::new(ForwardingTable::default());
15275        let handler =
15276            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15277        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15278        hello_via_sink(
15279            &handler,
15280            &target_ctx,
15281            &mut target_rx,
15282            hello_frame("target", PROTOCOL_VERSION, 1),
15283        )
15284        .await;
15285
15286        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15287        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15288        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15289            busy_refusals: None,
15290            target: RouteTarget::ToolProvider {
15291                module_id: "target".to_string(),
15292            },
15293            identity,
15294            consumer_identity: None,
15295            consumer_capabilities: None,
15296            role_versions: None,
15297            admission_facts: None,
15298            scope: None,
15299        })
15300        .unwrap();
15301        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15302
15303        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15304        let route_handler = handler.clone();
15305        let route_task = tokio::spawn(async move {
15306            route_handler
15307                .handle_control_frame(&client_ctx, open)
15308                .await
15309                .unwrap()
15310        });
15311        let bind_frame = target_rx.recv().await.unwrap();
15312        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15313        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15314            panic!("expected route.bind")
15315        };
15316        assert_eq!(
15317            identity.build_class, None,
15318            "route.bind carried the build class"
15319        );
15320        assert!(
15321            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15322            "the route.bind bytes still name build_class"
15323        );
15324        handler
15325            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15326            .await
15327            .unwrap();
15328        route_task.await.unwrap();
15329    }
15330
15331    #[tokio::test]
15332    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15333        let registry = Arc::new(Registry::default());
15334        let forwarding = Arc::new(ForwardingTable::default());
15335        let supervisor = SupervisorHandle::new();
15336        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15337        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15338        let handler =
15339            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15340                .with_supervisor(supervisor)
15341                .with_admission_facts_config(
15342                    Some("fed".to_string()),
15343                    Some(vec!["target".to_string()]),
15344                );
15345
15346        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15347        hello_via_sink(
15348            &handler,
15349            &target_ctx,
15350            &mut target_rx,
15351            hello_frame("target", PROTOCOL_VERSION, 1),
15352        )
15353        .await;
15354        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15355        hello_via_sink(
15356            &handler,
15357            &other_ctx,
15358            &mut other_rx,
15359            hello_frame("other", PROTOCOL_VERSION, 2),
15360        )
15361        .await;
15362
15363        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15364        let expected_facts = facts.clone();
15365        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15366        let route_handler = handler.clone();
15367        let route_task = tokio::spawn(async move {
15368            route_handler
15369                .handle_control_frame(
15370                    &client_ctx,
15371                    route_open_frame_with_admission_facts(
15372                        10,
15373                        "target",
15374                        unique_project_root("admission-facts"),
15375                        Some(subc_control::ConsumerIdentity {
15376                            module_id: "fed".to_string(),
15377                            launch_nonce: "fed-nonce".to_string(),
15378                        }),
15379                        Some(facts.clone()),
15380                    ),
15381                )
15382                .await
15383                .unwrap()
15384        });
15385        let bind_frame = target_rx.recv().await.unwrap();
15386        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15387        let ModuleControlRequest::RouteBind {
15388            admission_facts, ..
15389        } = bind
15390        else {
15391            panic!("expected route.bind")
15392        };
15393        assert_eq!(admission_facts, Some(expected_facts));
15394        handler
15395            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15396            .await
15397            .unwrap();
15398        assert!(route_task.await.unwrap().is_empty());
15399        assert!(matches!(
15400            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15401                .unwrap(),
15402            ClientControlResponse::RouteOpen { .. }
15403        ));
15404
15405        let direct = handler
15406            .handle_control_frame(
15407                &route_ctx(ConnectionId::new(73)).0,
15408                route_open_frame_with_admission_facts(
15409                    11,
15410                    "target",
15411                    unique_project_root("admission-facts"),
15412                    None,
15413                    Some(json!({"x": 1})),
15414                ),
15415            )
15416            .await
15417            .unwrap();
15418        assert_eq!(
15419            parse_error(&direct[0])["code"],
15420            "admission_facts_not_permitted"
15421        );
15422
15423        let different_reserved = handler
15424            .handle_control_frame(
15425                &route_ctx(ConnectionId::new(77)).0,
15426                route_open_frame_with_admission_facts(
15427                    15,
15428                    "target",
15429                    unique_project_root("admission-facts"),
15430                    Some(subc_control::ConsumerIdentity {
15431                        module_id: "other".to_string(),
15432                        launch_nonce: "other-nonce".to_string(),
15433                    }),
15434                    Some(json!({"x": 1})),
15435                ),
15436            )
15437            .await
15438            .unwrap();
15439        assert_eq!(
15440            parse_error(&different_reserved[0])["code"],
15441            "admission_facts_not_permitted"
15442        );
15443
15444        let other_target = handler
15445            .handle_control_frame(
15446                &route_ctx(ConnectionId::new(74)).0,
15447                route_open_frame_with_admission_facts(
15448                    12,
15449                    "other",
15450                    unique_project_root("admission-facts"),
15451                    Some(subc_control::ConsumerIdentity {
15452                        module_id: "fed".to_string(),
15453                        launch_nonce: "fed-nonce".to_string(),
15454                    }),
15455                    Some(json!({"x": 1})),
15456                ),
15457            )
15458            .await
15459            .unwrap();
15460        assert_eq!(
15461            parse_error(&other_target[0])["code"],
15462            "admission_facts_target_not_allowed"
15463        );
15464
15465        let nonexistent = handler
15466            .handle_control_frame(
15467                &route_ctx(ConnectionId::new(75)).0,
15468                route_open_frame_with_admission_facts(
15469                    13,
15470                    "missing",
15471                    unique_project_root("admission-facts"),
15472                    None,
15473                    Some(json!({"x": 1})),
15474                ),
15475            )
15476            .await
15477            .unwrap();
15478        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15479
15480        let described = handler
15481            .handle_control_frame(
15482                &route_ctx(ConnectionId::new(76)).0,
15483                Frame::build(
15484                    FrameType::Request,
15485                    control_flags(),
15486                    0,
15487                    0,
15488                    14,
15489                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15490                )
15491                .unwrap(),
15492            )
15493            .await
15494            .unwrap();
15495        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15496            serde_json::from_slice(&described[0].body).unwrap()
15497        else {
15498            panic!("expected server.describe response")
15499        };
15500        assert!(capabilities
15501            .iter()
15502            .any(|cap| cap == "admission_facts_relay_v1"));
15503    }
15504
15505    #[tokio::test]
15506    async fn admission_facts_without_configured_carrier_are_rejected() {
15507        let registry = Arc::new(Registry::default());
15508        let forwarding = Arc::new(ForwardingTable::default());
15509        let handler = ControlHandler::with_forwarding(registry, forwarding);
15510        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15511        hello_via_sink(
15512            &handler,
15513            &target_ctx,
15514            &mut target_rx,
15515            hello_frame("target", PROTOCOL_VERSION, 1),
15516        )
15517        .await;
15518
15519        let responses = handler
15520            .handle_control_frame(
15521                &route_ctx(ConnectionId::new(79)).0,
15522                route_open_frame_with_admission_facts(
15523                    16,
15524                    "target",
15525                    unique_project_root("admission-facts"),
15526                    None,
15527                    Some(json!({"x": 1})),
15528                ),
15529            )
15530            .await
15531            .unwrap();
15532        assert_eq!(
15533            parse_error(&responses[0])["code"],
15534            "admission_facts_not_permitted"
15535        );
15536    }
15537
15538    #[tokio::test]
15539    async fn route_open_relays_consumer_capabilities_verbatim() {
15540        let registry = Arc::new(Registry::default());
15541        let forwarding = Arc::new(ForwardingTable::default());
15542        let handler =
15543            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15544        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15545        hello_via_sink(
15546            &handler,
15547            &module_ctx,
15548            &mut module_rx,
15549            hello_frame("aft", PROTOCOL_VERSION, 7),
15550        )
15551        .await;
15552
15553        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15554        let expected_for_request = expected.clone();
15555        let project_root = unique_project_root("consumer-capabilities-present");
15556        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15557        let route_handler = handler.clone();
15558        let route_task = tokio::spawn(async move {
15559            route_handler
15560                .handle_control_frame(
15561                    &client_ctx,
15562                    route_open_frame_with_consumer_capabilities(
15563                        401,
15564                        "aft",
15565                        project_root,
15566                        Some(expected_for_request),
15567                    ),
15568                )
15569                .await
15570                .unwrap()
15571        });
15572        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15573            .await
15574            .unwrap()
15575            .unwrap();
15576        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15577        let ModuleControlRequest::RouteBind {
15578            consumer_capabilities,
15579            ..
15580        } = bind
15581        else {
15582            panic!("expected route.bind request, got {bind:?}");
15583        };
15584        assert_eq!(consumer_capabilities, Some(expected.clone()));
15585
15586        handler
15587            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15588            .await
15589            .unwrap();
15590        let route_response = route_task.await.unwrap();
15591        assert!(route_response.is_empty());
15592        let published = client_rx.recv().await.unwrap();
15593        assert!(matches!(
15594            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15595            ClientControlResponse::RouteOpen { .. }
15596        ));
15597    }
15598
15599    #[tokio::test]
15600    async fn route_open_without_consumer_capabilities_relays_none() {
15601        let registry = Arc::new(Registry::default());
15602        let forwarding = Arc::new(ForwardingTable::default());
15603        let handler =
15604            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15605        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15606        hello_via_sink(
15607            &handler,
15608            &module_ctx,
15609            &mut module_rx,
15610            hello_frame("aft", PROTOCOL_VERSION, 7),
15611        )
15612        .await;
15613
15614        let project_root = unique_project_root("consumer-capabilities-absent");
15615        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15616        let route_handler = handler.clone();
15617        let route_task = tokio::spawn(async move {
15618            route_handler
15619                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15620                .await
15621                .unwrap()
15622        });
15623        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15624            .await
15625            .unwrap()
15626            .unwrap();
15627        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15628        let ModuleControlRequest::RouteBind {
15629            consumer_capabilities,
15630            ..
15631        } = bind
15632        else {
15633            panic!("expected route.bind request, got {bind:?}");
15634        };
15635        assert_eq!(consumer_capabilities, None);
15636
15637        handler
15638            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15639            .await
15640            .unwrap();
15641        let route_response = route_task.await.unwrap();
15642        assert!(route_response.is_empty());
15643        let published = client_rx.recv().await.unwrap();
15644        assert!(matches!(
15645            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15646            ClientControlResponse::RouteOpen { .. }
15647        ));
15648    }
15649
15650    /// Opens a route to a freshly registered `aft` with `sent` as the
15651    /// route.open's role_versions, acks the bind, and returns the role_versions
15652    /// the module's bind carried.
15653    async fn bind_role_versions_for(
15654        sent: Option<BTreeMap<String, String>>,
15655        connection: u64,
15656    ) -> Option<BTreeMap<String, String>> {
15657        let registry = Arc::new(Registry::default());
15658        let forwarding = Arc::new(ForwardingTable::default());
15659        let handler =
15660            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15661        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15662        hello_via_sink(
15663            &handler,
15664            &module_ctx,
15665            &mut module_rx,
15666            hello_frame("aft", PROTOCOL_VERSION, 7),
15667        )
15668        .await;
15669        let project_root = unique_project_root("role-versions");
15670        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15671        let route_handler = handler.clone();
15672        let route_task = tokio::spawn(async move {
15673            route_handler
15674                .handle_control_frame(
15675                    &client_ctx,
15676                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15677                )
15678                .await
15679                .unwrap()
15680        });
15681        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15682            .await
15683            .expect("a well-formed route.open reaches the module as a bind")
15684            .unwrap();
15685        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15686        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15687            panic!("expected route.bind request, got {bind:?}");
15688        };
15689        handler
15690            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15691            .await
15692            .unwrap();
15693        assert!(route_task.await.unwrap().is_empty());
15694        let published = client_rx.recv().await.unwrap();
15695        assert!(matches!(
15696            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15697            ClientControlResponse::RouteOpen { .. }
15698        ));
15699        role_versions
15700    }
15701
15702    #[tokio::test]
15703    async fn route_open_relays_role_versions_verbatim() {
15704        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15705        assert_eq!(
15706            bind_role_versions_for(Some(sent.clone()), 141).await,
15707            Some(sent)
15708        );
15709    }
15710
15711    /// An empty map declares nothing, so the provider sees no field rather
15712    /// than an empty object it would have to treat as a second "none".
15713    #[tokio::test]
15714    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15715        assert_eq!(bind_role_versions_for(None, 143).await, None);
15716        assert_eq!(
15717            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15718            None
15719        );
15720    }
15721
15722    #[tokio::test]
15723    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15724        let registry = Arc::new(Registry::default());
15725        let forwarding = Arc::new(ForwardingTable::default());
15726        let handler =
15727            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15728        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15729        hello_via_sink(
15730            &handler,
15731            &module_ctx,
15732            &mut module_rx,
15733            hello_frame("aft", PROTOCOL_VERSION, 7),
15734        )
15735        .await;
15736
15737        let nine: BTreeMap<String, String> = (0..9)
15738            .map(|index| (format!("role-{index}"), "v1".to_string()))
15739            .collect();
15740        for (label, malformed) in [
15741            (
15742                "invalid role name",
15743                role_versions(&[("Tool_Provider", "v1")]),
15744            ),
15745            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15746            ("nine entries", nine),
15747        ] {
15748            // A refused open answers at once; one that reached the module
15749            // would wait for its bind ack and trip this timeout.
15750            let responses = tokio::time::timeout(
15751                Duration::from_secs(1),
15752                handler.handle_control_frame(
15753                    &route_ctx(ConnectionId::new(148)).0,
15754                    route_open_frame_with_role_versions(
15755                        404,
15756                        "aft",
15757                        unique_project_root("role-versions-malformed"),
15758                        Some(malformed),
15759                    ),
15760                ),
15761            )
15762            .await
15763            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15764            .unwrap();
15765            assert_eq!(responses.len(), 1, "{label}");
15766            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15767            let error = parse_error(&responses[0]);
15768            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15769            assert_eq!(
15770                error["detail"]["field"], "role_versions",
15771                "{label}: {error}"
15772            );
15773            assert!(
15774                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15775                "{label}: a malformed declaration is terminal"
15776            );
15777            assert!(
15778                module_rx.try_recv().is_err(),
15779                "{label}: the module must never see a bind"
15780            );
15781        }
15782    }
15783
15784    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15785    /// consumer can tell this daemon forwards the field from one that would
15786    /// drop it.
15787    #[tokio::test]
15788    async fn route_role_versions_capability_is_advertised() {
15789        let handler = ControlHandler::new(Arc::new(Registry::default()));
15790        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15791        let ack = hello_via_sink(
15792            &handler,
15793            &ctx,
15794            &mut rx,
15795            hello_frame("m", PROTOCOL_VERSION, 1),
15796        )
15797        .await;
15798        let ack = parse_ack(&ack);
15799        assert!(
15800            ack.subc_capabilities
15801                .iter()
15802                .any(|c| c == "route-role-versions/v1"),
15803            "{:?}",
15804            ack.subc_capabilities
15805        );
15806
15807        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15808        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15809        let reply = handler
15810            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15811            .await
15812            .unwrap()
15813            .pop()
15814            .unwrap();
15815        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15816            serde_json::from_slice(&reply.body).unwrap()
15817        else {
15818            panic!("not a server.describe reply");
15819        };
15820        assert!(
15821            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15822            "{capabilities:?}"
15823        );
15824    }
15825
15826    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15827    /// catalog entry without `events` (the module declares none) from a daemon
15828    /// that never reports declared events.
15829    #[tokio::test]
15830    async fn catalog_events_capability_is_advertised() {
15831        let handler = ControlHandler::new(Arc::new(Registry::default()));
15832        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15833        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15834        let reply = handler
15835            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
15836            .await
15837            .unwrap()
15838            .pop()
15839            .unwrap();
15840        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15841            serde_json::from_slice(&reply.body).unwrap()
15842        else {
15843            panic!("not a server.describe reply");
15844        };
15845        assert!(
15846            capabilities
15847                .iter()
15848                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
15849            "{capabilities:?}"
15850        );
15851    }
15852
15853    #[tokio::test]
15854    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15855        let handler = ControlHandler::new(Arc::new(Registry::default()));
15856        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15857        let ack = hello_via_sink(
15858            &handler,
15859            &module,
15860            &mut module_rx,
15861            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15862        )
15863        .await;
15864        let ack = parse_ack(&ack);
15865        assert!(
15866            ack.subc_capabilities
15867                .iter()
15868                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15869            "{:?}",
15870            ack.subc_capabilities
15871        );
15872        assert!(ack
15873            .subc_capabilities
15874            .iter()
15875            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15876
15877        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15878        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15879        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15880        let reply = handler
15881            .handle_control_frame(&client, frame)
15882            .await
15883            .unwrap()
15884            .pop()
15885            .unwrap();
15886        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15887            serde_json::from_slice(&reply.body).unwrap()
15888        else {
15889            panic!("not a server.describe reply");
15890        };
15891        assert!(
15892            capabilities
15893                .iter()
15894                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15895            "{capabilities:?}"
15896        );
15897        assert!(capabilities
15898            .iter()
15899            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15900    }
15901
15902    #[tokio::test]
15903    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15904        let handler = ControlHandler::new(Arc::new(Registry::default()));
15905        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15906        let ack = hello_via_sink(
15907            &handler,
15908            &module,
15909            &mut rx,
15910            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15911        )
15912        .await;
15913        assert!(parse_ack(&ack)
15914            .subc_capabilities
15915            .iter()
15916            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15917        assert!(parse_ack(&ack)
15918            .subc_capabilities
15919            .iter()
15920            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15921        let (client, _rx) = route_ctx(ConnectionId::new(157));
15922        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15923        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15924        let reply = handler
15925            .handle_control_frame(&client, frame)
15926            .await
15927            .unwrap()
15928            .pop()
15929            .unwrap();
15930        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15931            serde_json::from_slice(&reply.body).unwrap()
15932        else {
15933            panic!("server.describe reply")
15934        };
15935        assert!(capabilities
15936            .iter()
15937            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15938        assert!(capabilities
15939            .iter()
15940            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15941    }
15942
15943    #[tokio::test]
15944    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15945        let handler = ControlHandler::new(Arc::new(Registry::default()));
15946        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15947        let ack = hello_via_sink(
15948            &handler,
15949            &module,
15950            &mut rx,
15951            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15952        )
15953        .await;
15954        assert!(parse_ack(&ack)
15955            .subc_capabilities
15956            .iter()
15957            .any(|cap| cap == "scope-workdir/v1"));
15958        let (client, _rx) = route_ctx(ConnectionId::new(159));
15959        let frame = Frame::build(
15960            FrameType::Request,
15961            control_flags(),
15962            0,
15963            0,
15964            5,
15965            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15966        )
15967        .unwrap();
15968        let reply = handler
15969            .handle_control_frame(&client, frame)
15970            .await
15971            .unwrap()
15972            .remove(0);
15973        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15974            serde_json::from_slice(&reply.body).unwrap()
15975        else {
15976            panic!("server.describe reply")
15977        };
15978        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15979    }
15980
15981    #[tokio::test]
15982    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15983        let handler = ControlHandler::new(Arc::new(Registry::default()));
15984        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15985        let ack = hello_via_sink(
15986            &handler,
15987            &module,
15988            &mut rx,
15989            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15990        )
15991        .await;
15992        assert!(parse_ack(&ack)
15993            .subc_capabilities
15994            .iter()
15995            .any(|cap| cap == "worker-runs/v1"));
15996        let (client, _rx) = route_ctx(ConnectionId::new(161));
15997        let frame = Frame::build(
15998            FrameType::Request,
15999            control_flags(),
16000            0,
16001            0,
16002            5,
16003            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
16004        )
16005        .unwrap();
16006        let reply = handler
16007            .handle_control_frame(&client, frame)
16008            .await
16009            .unwrap()
16010            .remove(0);
16011        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16012            serde_json::from_slice(&reply.body).unwrap()
16013        else {
16014            panic!("server.describe reply")
16015        };
16016        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
16017    }
16018
16019    #[tokio::test]
16020    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
16021        let handler = ControlHandler::new(Arc::new(Registry::default()));
16022        let (module, mut rx) = route_ctx(ConnectionId::new(154));
16023        let ack = hello_via_sink(
16024            &handler,
16025            &module,
16026            &mut rx,
16027            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
16028        )
16029        .await;
16030        assert!(parse_ack(&ack)
16031            .subc_capabilities
16032            .iter()
16033            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16034        let (client, _rx) = route_ctx(ConnectionId::new(155));
16035        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
16036        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
16037        let reply = handler
16038            .handle_control_frame(&client, frame)
16039            .await
16040            .unwrap()
16041            .pop()
16042            .unwrap();
16043        let ClientControlResponse::ServerDescribe { capabilities, .. } =
16044            serde_json::from_slice(&reply.body).unwrap()
16045        else {
16046            panic!("not a server.describe reply")
16047        };
16048        assert!(capabilities
16049            .iter()
16050            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
16051    }
16052
16053    #[tokio::test]
16054    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
16055        let registry = Arc::new(Registry::default());
16056        let forwarding = Arc::new(ForwardingTable::default());
16057        let handler =
16058            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
16059                .with_health_probe_timeout(Duration::from_secs(5));
16060        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
16061        hello_via_sink(
16062            &handler,
16063            &module_ctx,
16064            &mut module_rx,
16065            non_routable_hello_frame_with_control_ops(
16066                "mcp",
16067                300,
16068                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
16069            ),
16070        )
16071        .await;
16072        assert!(registry
16073            .get_module("mcp")
16074            .unwrap()
16075            .unwrap()
16076            .manifest
16077            .provides
16078            .is_empty());
16079
16080        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
16081        let route_response = handler
16082            .handle_control_frame(
16083                &route_client_ctx,
16084                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
16085            )
16086            .await
16087            .unwrap();
16088        assert_eq!(route_response[0].header.ty, FrameType::Error);
16089        assert_eq!(
16090            parse_error(&route_response[0])["code"],
16091            "target_unavailable"
16092        );
16093        assert!(parse_error(&route_response[0])["message"]
16094            .as_str()
16095            .unwrap()
16096            .contains("does not provide the requested target"));
16097        assert!(module_rx.try_recv().is_err());
16098
16099        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
16100        let health_handler = handler.clone();
16101        let health_task = tokio::spawn(async move {
16102            health_handler
16103                .handle_control_frame(
16104                    &health_client_ctx,
16105                    supervisor_health_probe_frame(302, "mcp"),
16106                )
16107                .await
16108                .unwrap()
16109        });
16110        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
16111            .await
16112            .unwrap()
16113            .unwrap();
16114        assert_eq!(
16115            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
16116            ModuleControlRequest::HealthCheck {}
16117        );
16118        handler
16119            .handle_control_frame(
16120                &module_ctx,
16121                health_response(health_frame.header.corr, HealthStatus::Ok),
16122            )
16123            .await
16124            .unwrap();
16125        let health_response = health_task.await.unwrap();
16126        assert_eq!(health_response[0].header.ty, FrameType::Response);
16127        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
16128            ClientControlResponse::SupervisorHealthProbe {
16129                module_id, status, ..
16130            } => {
16131                assert_eq!(module_id, "mcp");
16132                assert_eq!(status, HealthStatus::Ok);
16133            }
16134            other => panic!("unexpected health response: {other:?}"),
16135        }
16136
16137        // Exercise the forwarding cleanup path directly while leaving the registry
16138        // advertisement in place. If cleanup leaves a stale control sink behind,
16139        // the next probe will enqueue onto it and wait for the long probe timeout
16140        // instead of returning an immediate no-connection error.
16141        forwarding
16142            .cleanup_connection(module_ctx.connection_id)
16143            .unwrap();
16144        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16145        let cleanup_response = tokio::time::timeout(
16146            Duration::from_millis(200),
16147            handler.handle_control_frame(
16148                &cleanup_probe_ctx,
16149                supervisor_health_probe_frame(303, "mcp"),
16150            ),
16151        )
16152        .await
16153        .expect("probe should fail immediately when the control lane is gone")
16154        .unwrap();
16155        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16156        assert_eq!(
16157            parse_error(&cleanup_response[0])["code"],
16158            "target_unavailable"
16159        );
16160        assert!(parse_error(&cleanup_response[0])["message"]
16161            .as_str()
16162            .unwrap()
16163            .contains("no module connection"));
16164
16165        handler
16166            .cleanup_connection(module_ctx.connection_id)
16167            .unwrap();
16168    }
16169
16170    #[tokio::test]
16171    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16172        let registry = Arc::new(Registry::default());
16173        let supervisor_handle = SupervisorHandle::new();
16174        let supervisor =
16175            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16176                .with_handle(supervisor_handle.clone())
16177                .with_connection_file_path(
16178                    std::env::temp_dir()
16179                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16180                );
16181        let module = supervisor
16182            .supervise_configured(
16183                ModuleSpec {
16184                    script: None,
16185                    carry_containment: false,
16186                    module_id: "warming".to_string(),
16187                    program: fake_aft_stub_path(),
16188                    args: Vec::new(),
16189                    env: Vec::new(),
16190                    reserved: false,
16191                    reserved_prefixes: Vec::new(),
16192                    protocol: ModuleProtocol::Subc,
16193                    overlap: Default::default(),
16194                },
16195                true,
16196            )
16197            .unwrap();
16198        assert_eq!(module.state().unwrap(), ModuleState::Running);
16199
16200        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16201        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16202        let response = handler
16203            .handle_control_frame(
16204                &ctx,
16205                route_open_frame(304, "warming", unique_project_root("warming")),
16206            )
16207            .await
16208            .unwrap();
16209        module.stop().await.unwrap();
16210
16211        assert_eq!(response[0].header.ty, FrameType::Error);
16212        let error = parse_error(&response[0]);
16213        assert_eq!(error["code"], "module_warming");
16214        assert!(error["message"]
16215            .as_str()
16216            .unwrap()
16217            .contains("state=running, enabled=true, live=false"));
16218    }
16219
16220    #[test]
16221    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16222        let handler = ControlHandler::new(Arc::new(Registry::default()));
16223        let capture = EventCapture::default();
16224        let _subscriber =
16225            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16226        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16227        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16228        let pending = (0..limit).collect::<Vec<_>>();
16229        let response = handler
16230            .route_open_capacity_refusal(
16231                &ctx,
16232                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16233                "busy",
16234                pending.len(),
16235                limit,
16236            )
16237            .unwrap();
16238        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16239        let event = capture
16240            .events()
16241            .into_iter()
16242            .find(|event| {
16243                event.target == "control"
16244                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16245            })
16246            .expect("connection admission refusal event");
16247        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16248        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16249        // Refused before `handle_route_open` parses the request, so the caller
16250        // fields are read from the frame itself.
16251        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16252        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16253    }
16254
16255    #[test]
16256    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16257        let handler = ControlHandler::new(Arc::new(Registry::default()));
16258        let capture = EventCapture::default();
16259        let _subscriber =
16260            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16261        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16262        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16263        let guards = (0..limit)
16264            .map(|_| {
16265                handler
16266                    .route_bind_concurrency
16267                    .try_admit("busy", limit)
16268                    .unwrap()
16269            })
16270            .collect::<Vec<_>>();
16271        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16272            Err(in_flight) => in_flight,
16273            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16274        };
16275        let response = handler
16276            .route_open_target_capacity_refusal(
16277                &ctx,
16278                &RouteOpenCaller::unknown(),
16279                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16280                "busy",
16281                in_flight,
16282            )
16283            .unwrap();
16284        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16285        let event = capture
16286            .events()
16287            .into_iter()
16288            .find(|event| {
16289                event.target == "control"
16290                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16291            })
16292            .expect("target admission refusal event");
16293        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16294        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16295        drop(guards);
16296    }
16297
16298    #[cfg(unix)]
16299    #[tokio::test(start_paused = true)]
16300    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16301        let registry = Arc::new(Registry::default());
16302        let handle = SupervisorHandle::new();
16303        let supervisor =
16304            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16305                .with_handle(handle.clone());
16306        let module = supervisor
16307            .spawn(crate::ModuleSpec {
16308                script: None,
16309                carry_containment: false,
16310                module_id: "retry-list".into(),
16311                program: PathBuf::from("/bin/sh"),
16312                args: vec!["-c".into(), "exit 17".into()],
16313                env: vec![],
16314                reserved: false,
16315                reserved_prefixes: vec![],
16316                protocol: ModuleProtocol::None,
16317                overlap: Default::default(),
16318            })
16319            .unwrap();
16320        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16321        while module.state().unwrap() != crate::ModuleState::Failed {
16322            assert!(
16323                std::time::Instant::now() < deadline,
16324                "waiting for budget failure"
16325            );
16326            tokio::task::yield_now().await;
16327        }
16328        let handler = ControlHandler::new(registry).with_supervisor(handle);
16329        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, 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_eq!(body["modules"][0]["state"], "failed");
16333        let retry = body["modules"][0]["next_retry_at_ms"]
16334            .as_u64()
16335            .expect("scheduled retry on the wire");
16336        let now = std::time::SystemTime::now()
16337            .duration_since(std::time::UNIX_EPOCH)
16338            .unwrap()
16339            .as_millis() as u64;
16340        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16341        module.set_enabled(false).await.unwrap();
16342        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16343        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16344        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16345        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16346    }
16347
16348    #[tokio::test]
16349    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16350        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16351        let supervisor =
16352            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16353        let module = supervisor
16354            .spawn(crate::ModuleSpec {
16355                script: None,
16356                carry_containment: false,
16357                module_id: "pid-read-budget".into(),
16358                program: std::env::current_exe().unwrap(),
16359                args: vec![
16360                    "--exact".into(),
16361                    "control::tests::pid_resource_read_fixture".into(),
16362                ],
16363                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16364                    .into_iter()
16365                    .map(|key| (key.into(), dir.display().to_string()))
16366                    .chain(std::iter::once((
16367                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16368                        "1".into(),
16369                    )))
16370                    .collect(),
16371                reserved: false,
16372                reserved_prefixes: Vec::new(),
16373                protocol: ModuleProtocol::None,
16374                overlap: Default::default(),
16375            })
16376            .unwrap();
16377        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16378        while !matches!(
16379            module.child_resource_usage(),
16380            subc_control::ChildResourceUsage::Measured(_)
16381        ) {
16382            assert!(
16383                tokio::time::Instant::now() < ready_deadline,
16384                "fixture process was not measurable"
16385            );
16386            tokio::time::sleep(Duration::from_millis(10)).await;
16387        }
16388        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16389        let reading = {
16390            let _guard = crate::subtree_resources::fault_read_guard().await;
16391            crate::subtree_resources::read_process(module.clone()).await
16392        };
16393        stop_resource_fixture(&module, &dir).await;
16394        assert!(
16395            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16396            "{reading:?}"
16397        );
16398    }
16399
16400    #[test]
16401    fn pid_resource_read_fixture() {
16402        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16403            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16404            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16405            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16406                std::thread::sleep(Duration::from_millis(5));
16407            }
16408            std::fs::write(dir.join("module-stopped"), "").unwrap();
16409        }
16410    }
16411
16412    async fn stop_resource_fixture(
16413        module: &crate::supervise::SupervisedModule,
16414        dir: &std::path::Path,
16415    ) {
16416        let stopping = module.stop();
16417        tokio::pin!(stopping);
16418        tokio::select! {
16419            result = &mut stopping => result.unwrap(),
16420            () = async {
16421                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16422                    tokio::time::sleep(Duration::from_millis(5)).await;
16423                }
16424                std::fs::write(dir.join("stop-module"), "").unwrap();
16425            } => stopping.await.unwrap(),
16426        }
16427        #[cfg(windows)]
16428        assert!(
16429            dir.join("module-stopped").exists(),
16430            "the resource fixture must exit cooperatively, not wait for the drain kill"
16431        );
16432        assert_eq!(
16433            module.state().unwrap(),
16434            crate::supervise::ModuleState::Stopped
16435        );
16436    }
16437
16438    #[tokio::test]
16439    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16440        let registry = Arc::new(Registry::default());
16441        let handle = SupervisorHandle::new();
16442        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16443            .with_handle(handle.clone());
16444        supervisor
16445            .supervise_configured(
16446                crate::ModuleSpec {
16447                    script: None,
16448                    module_id: "disabled-resource-reading".into(),
16449                    program: std::env::current_exe().unwrap(),
16450                    args: Vec::new(),
16451                    env: Vec::new(),
16452                    reserved: false,
16453                    reserved_prefixes: Vec::new(),
16454                    protocol: ModuleProtocol::None,
16455                    overlap: Default::default(),
16456                    carry_containment: false,
16457                },
16458                false,
16459            )
16460            .unwrap();
16461        let handler = ControlHandler::new(registry).with_supervisor(handle);
16462        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16463        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16464        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16465        assert!(body["modules"][0].get("tree").is_none());
16466        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16467    }
16468
16469    #[tokio::test]
16470    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16471        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16472        let registry = Arc::new(Registry::default());
16473        let handle = SupervisorHandle::new();
16474        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16475            .with_handle(handle.clone());
16476        let module = supervisor
16477            .spawn(crate::ModuleSpec {
16478                script: None,
16479                carry_containment: false,
16480                module_id: "list-process-priority".into(),
16481                program: std::env::current_exe().unwrap(),
16482                args: vec![
16483                    "--exact".into(),
16484                    "control::tests::pid_resource_read_fixture".into(),
16485                ],
16486                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16487                    .into_iter()
16488                    .map(|key| (key.into(), dir.display().to_string()))
16489                    .chain(std::iter::once((
16490                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16491                        "1".into(),
16492                    )))
16493                    .collect(),
16494                reserved: false,
16495                reserved_prefixes: Vec::new(),
16496                protocol: ModuleProtocol::None,
16497                overlap: Default::default(),
16498            })
16499            .unwrap();
16500        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16501        loop {
16502            let image = module.running_image_agreement().await;
16503            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16504                break;
16505            }
16506            assert!(
16507                tokio::time::Instant::now() < ready_deadline,
16508                "the fixture process never became observable: {image:?}"
16509            );
16510            tokio::time::sleep(Duration::from_millis(10)).await;
16511        }
16512        let guard = crate::subtree_resources::fault_read_guard().await;
16513        let (target, release, _) = crate::subtree_resources::held();
16514        module.set_subtree_target_for_test(target);
16515        let handler = ControlHandler::new(registry).with_supervisor(handle);
16516        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16517        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16518        drop(release);
16519        drop(guard);
16520        stop_resource_fixture(&module, &dir).await;
16521        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16522        assert_eq!(
16523            body["modules"][0]["resources"]["status"], "measured",
16524            "the optional tree timeout must not discard the process reading: {body}"
16525        );
16526        assert!(body["modules"][0].get("tree").is_none());
16527        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16528        assert_eq!(
16529            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16530            "the tree timeout must not hide a completed image observation"
16531        );
16532    }
16533
16534    #[cfg(any(target_os = "linux", target_os = "macos"))]
16535    #[tokio::test]
16536    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16537        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16538            .with_daemon_provenance(
16539                std::process::id(),
16540                0,
16541                Some(std::env::current_exe().unwrap()),
16542                None,
16543                None,
16544            );
16545        let (probe, release, began) = ExecutableIdentityProbe::held();
16546        handler.daemon_provenance.probe = probe;
16547        let observe = |handler: ControlHandler, corr| {
16548            tokio::spawn(async move {
16549                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16550                let frame =
16551                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16552                        .unwrap();
16553                handler
16554                    .handle_supervisor_provenance(&ctx, frame, None)
16555                    .await
16556                    .unwrap()
16557            })
16558        };
16559        let explicit = observe(handler.clone(), 114);
16560        began.await.unwrap();
16561        let concurrent = observe(handler.clone(), 115);
16562        // Keep explicit provenance waiting on its first image observation beyond
16563        // the list deadline; release it only after the concurrent list replies.
16564        tokio::time::sleep(Duration::from_millis(300)).await;
16565        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16566        let list = tokio::time::timeout(
16567            Duration::from_secs(1),
16568            handler.handle_supervisor_list(frame),
16569        )
16570        .await;
16571        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16572        drop(release);
16573        let replies = explicit.await.unwrap();
16574        let concurrent_replies = concurrent.await.unwrap();
16575        assert!(
16576            explicit_was_pending,
16577            "explicit provenance must await the full observation"
16578        );
16579        let list = list
16580            .expect("a concurrent explicit probe must not stall list")
16581            .unwrap();
16582        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16583        assert_eq!(list_body["op"], "supervisor.list");
16584        for replies in [replies, concurrent_replies] {
16585            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16586            assert_eq!(
16587                body["daemon"]["daemon_observed"]["running_image"]["status"],
16588                "match"
16589            );
16590        }
16591    }
16592
16593    #[tokio::test]
16594    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16595        let registry = Arc::new(Registry::default());
16596        let handle = SupervisorHandle::new();
16597        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16598            .with_handle(handle.clone());
16599        let module = supervisor
16600            .supervise_configured(
16601                crate::ModuleSpec {
16602                    script: None,
16603                    carry_containment: false,
16604                    module_id: "memory-read".into(),
16605                    program: PathBuf::from("disabled-module"),
16606                    args: Vec::new(),
16607                    env: Vec::new(),
16608                    reserved: false,
16609                    reserved_prefixes: Vec::new(),
16610                    protocol: ModuleProtocol::Subc,
16611                    overlap: Default::default(),
16612                },
16613                true,
16614            )
16615            .unwrap();
16616        let _guard = crate::subtree_resources::fault_read_guard().await;
16617        let (target, release, began) = crate::subtree_resources::held();
16618        // Optional list work may be skipped when its deadline is already spent.
16619        // Establish the stalled fixture before asking the list to observe it.
16620        let stalled_target = target.clone();
16621        let stalled = tokio::task::spawn_blocking(move || {
16622            stalled_target.tree(&subc_os::ProcessTable::default())
16623        });
16624        began.await.unwrap();
16625        module.set_subtree_target_for_test(target);
16626        let handler = ControlHandler::new(registry).with_supervisor(handle);
16627        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16628        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16629        let replies = handler
16630            .handle_client_control_request(
16631                &ctx,
16632                frame,
16633                ClientControlRequest::SupervisorList {},
16634                &mut None,
16635            )
16636            .await
16637            .unwrap();
16638        assert!(
16639            replies.is_empty(),
16640            "list reply must be detached from the connection reader"
16641        );
16642        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16643        let replies = handler
16644            .handle_client_control_request(
16645                &ctx,
16646                frame,
16647                ClientControlRequest::SupervisorSpawnSnapshot {},
16648                &mut None,
16649            )
16650            .await
16651            .unwrap();
16652        assert_eq!(
16653            replies.len(),
16654            1,
16655            "another request must complete while the subtree read stalls"
16656        );
16657        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16658            .await
16659            .unwrap()
16660            .unwrap();
16661        release.send(()).unwrap();
16662        drop(release);
16663        stalled.await.unwrap();
16664        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16665        assert!(
16666            body["modules"][0].get("tree").is_none(),
16667            "an unknown tree reading must be omitted after the bounded read expires"
16668        );
16669        // Lists export completed work rather than measuring synchronously.
16670        // Complete a refresh after the fixture is released before asserting
16671        // that a later list contains its measured tree.
16672        handler
16673            .resource_tracker
16674            .read(handler.supervisor.list(), false, "released_tree_fixture")
16675            .await;
16676        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16677        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16678        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16679        assert_eq!(
16680            body["modules"][0]["tree"]["source"], "process_tree",
16681            "the next request must export the completed refresh"
16682        );
16683        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16684    }
16685
16686    #[tokio::test]
16687    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16688        use subc_control::{
16689            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16690            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16691            TreeReading, TreeSource,
16692        };
16693        let registry = Arc::new(Registry::default());
16694        let handle = SupervisorHandle::new();
16695        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16696            .with_handle(handle.clone());
16697        supervisor
16698            .supervise_configured(
16699                crate::ModuleSpec {
16700                    script: None,
16701                    carry_containment: false,
16702                    module_id: "budget-worker".into(),
16703                    program: PathBuf::from("disabled-module"),
16704                    args: Vec::new(),
16705                    env: Vec::new(),
16706                    reserved: false,
16707                    reserved_prefixes: Vec::new(),
16708                    protocol: ModuleProtocol::Subc,
16709                    overlap: Default::default(),
16710                },
16711                true,
16712            )
16713            .unwrap();
16714        let handler = ControlHandler::new(registry).with_supervisor(handle);
16715        let now = u64::try_from(
16716            std::time::SystemTime::now()
16717                .duration_since(std::time::UNIX_EPOCH)
16718                .unwrap()
16719                .as_millis(),
16720        )
16721        .unwrap();
16722        let measured = now - 1_000;
16723        let hour = CpuLastHour::new(100, 60_000);
16724        let daemon = DaemonResources::new(7, 1, "test")
16725            .with_measured_at_ms(Some(measured))
16726            .with_resources(Some(ChildResourceUsage::Measured(
16727                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16728            )))
16729            .with_cpu_last_hour(Some(hour.clone()));
16730        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16731            .with_measured_at_ms(Some(measured))
16732            .with_cpu_last_hour(Some(hour.clone()));
16733        let tree = TreeReading::new(
16734            150,
16735            50,
16736            ChildMemoryKind::ResidentSet,
16737            1,
16738            TreeSource::ProcessTree,
16739        )
16740        .with_measured_at_ms(Some(measured));
16741        handler.resource_tracker.seed_committed_for_test(
16742            &handler.supervisor.list(),
16743            crate::resource_totals::Readings {
16744                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16745                daemon: Some(daemon),
16746                agent_commands: Some(vec![agents]),
16747                ..Default::default()
16748            },
16749            now,
16750        );
16751        list_diagnostics::scope(async {
16752            tokio::time::sleep(Duration::from_millis(110)).await;
16753            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16754            let request =
16755                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16756            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16757            let ClientControlResponse::SupervisorList {
16758                modules,
16759                daemon,
16760                agent_commands,
16761                ..
16762            } = serde_json::from_slice(&replies[0].body).unwrap()
16763            else {
16764                panic!("expected a list response")
16765            };
16766            assert!(matches!(
16767                modules[0].resources,
16768                Some(ChildResourceUsage::Unavailable {
16769                    reason: ChildResourceUnavailableReason::Unreadable
16770                })
16771            ));
16772            assert_eq!(
16773                (
16774                    modules[0].tree.as_ref().unwrap().cpu_ms,
16775                    modules[0].tree.as_ref().unwrap().measured_at_ms
16776                ),
16777                (150, Some(measured))
16778            );
16779            let daemon = daemon.unwrap();
16780            let agents = agent_commands.unwrap();
16781            assert_eq!(daemon.measured_at_ms, Some(measured));
16782            assert_eq!(
16783                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16784                (1, 50, Some(measured))
16785            );
16786            for hour in [
16787                modules[0].cpu_last_hour.as_ref(),
16788                daemon.cpu_last_hour.as_ref(),
16789                agents[0].cpu_last_hour.as_ref(),
16790            ] {
16791                let hour = hour.unwrap();
16792                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16793            }
16794        })
16795        .await;
16796    }
16797
16798    #[tokio::test]
16799    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16800        let registry = Arc::new(Registry::default());
16801        let handle = SupervisorHandle::new();
16802        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16803            .with_handle(handle.clone());
16804        supervisor
16805            .supervise_configured(
16806                crate::ModuleSpec {
16807                    script: None,
16808                    carry_containment: false,
16809                    module_id: "drift".into(),
16810                    program: PathBuf::from("disabled-module"),
16811                    args: Vec::new(),
16812                    env: Vec::new(),
16813                    reserved: false,
16814                    reserved_prefixes: Vec::new(),
16815                    protocol: ModuleProtocol::Subc,
16816                    overlap: Default::default(),
16817                },
16818                false,
16819            )
16820            .unwrap();
16821        let handler = ControlHandler::new(registry).with_supervisor(handle);
16822        for configured in [None, Some(false), Some(true)] {
16823            handler.capability_evaluator.configure(
16824                configured.map(|enabled| ("drift".to_string(), enabled)),
16825                BTreeMap::new(),
16826            );
16827            let frame =
16828                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16829            let replies = handler
16830                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16831                .await
16832                .unwrap();
16833            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16834            assert!(body.get("configured_enabled").is_none());
16835            assert_eq!(body["op"], "supervisor.ack");
16836            let frame =
16837                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16838            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16839            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16840            assert_eq!(
16841                body["modules"][0].get("configured_enabled"),
16842                configured.map(Value::Bool).as_ref()
16843            );
16844            assert!(body["modules"][0].get("tree").is_none());
16845            assert!(body["modules"][0].get("subtree").is_none());
16846        }
16847    }
16848
16849    #[tokio::test(flavor = "current_thread")]
16850    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16851        let handler = ControlHandler::new(Arc::new(Registry::default()));
16852        let capture = EventCapture::default();
16853        let _subscriber =
16854            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16855        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16856        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16857
16858        let _ = handler
16859            .handle_client_control_request(
16860                &ctx,
16861                frame,
16862                ClientControlRequest::SupervisorSetEnabled {
16863                    module_id: "broca".to_string(),
16864                    enabled: false,
16865                },
16866                &mut None,
16867            )
16868            .await
16869            .unwrap();
16870
16871        let events = capture
16872            .events()
16873            .into_iter()
16874            .filter(|event| {
16875                event.target == "control"
16876                    && event.fields.get("message").map(String::as_str)
16877                        == Some("supervisor request received")
16878            })
16879            .collect::<Vec<_>>();
16880        assert_eq!(events.len(), 1, "one supervisor request log line");
16881        let event = &events[0];
16882        assert_eq!(event.level, tracing::Level::INFO);
16883        assert_eq!(
16884            event.fields.get("op"),
16885            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16886        );
16887        assert_eq!(
16888            event.fields.get("module_id"),
16889            Some(&"\"broca\"".to_string())
16890        );
16891        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16892        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16893        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16894    }
16895
16896    #[tokio::test(flavor = "current_thread")]
16897    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16898        let registry = Arc::new(Registry::default());
16899        let module_connection = ConnectionId::new(303);
16900        registry
16901            .register_with_control_ops(
16902                manifest("aft", PROTOCOL_VERSION),
16903                PROTOCOL_VERSION,
16904                module_connection,
16905                module_baseline_control_ops(),
16906            )
16907            .unwrap();
16908        let handler = ControlHandler::new(registry);
16909        let capture = EventCapture::default();
16910        let _subscriber =
16911            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16912        let (ctx, _rx) = route_ctx(module_connection);
16913        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16914
16915        let _ = handler
16916            .handle_client_control_request(
16917                &ctx,
16918                frame,
16919                ClientControlRequest::SupervisorSetEnabled {
16920                    module_id: "broca".to_string(),
16921                    enabled: false,
16922                },
16923                &mut None,
16924            )
16925            .await
16926            .unwrap();
16927
16928        let callers = capture
16929            .events()
16930            .into_iter()
16931            .filter(|event| {
16932                event.fields.get("message").map(String::as_str)
16933                    == Some("supervisor request received")
16934            })
16935            .map(|event| event.fields.get("caller").cloned())
16936            .collect::<Vec<_>>();
16937        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16938    }
16939
16940    #[tokio::test(flavor = "current_thread")]
16941    async fn supervisor_list_does_not_log_request_received() {
16942        let handler = ControlHandler::new(Arc::new(Registry::default()));
16943        let capture = EventCapture::default();
16944        let _subscriber =
16945            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16946        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16947        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16948
16949        handler
16950            .handle_client_control_request(
16951                &ctx,
16952                frame,
16953                ClientControlRequest::SupervisorList {},
16954                &mut None,
16955            )
16956            .await
16957            .unwrap();
16958
16959        assert!(capture.events().into_iter().all(|event| {
16960            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16961        }));
16962    }
16963
16964    #[tokio::test(flavor = "current_thread")]
16965    async fn supervisor_rescan_preview_does_not_log_request_received() {
16966        let handler = ControlHandler::new(Arc::new(Registry::default()));
16967        let capture = EventCapture::default();
16968        let _subscriber =
16969            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16970        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16971        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16972
16973        handler
16974            .handle_client_control_request(
16975                &ctx,
16976                frame,
16977                ClientControlRequest::SupervisorRescan { preview: true },
16978                &mut None,
16979            )
16980            .await
16981            .unwrap();
16982
16983        assert!(capture.events().into_iter().all(|event| {
16984            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16985        }));
16986    }
16987
16988    struct ApproveOperator;
16989    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16990        fn prompt(
16991            &self,
16992            _: &str,
16993            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16994        ) -> crate::operator_confirm::ProviderResult {
16995            crate::operator_confirm::ProviderResult::Approved
16996        }
16997    }
16998
16999    #[tokio::test]
17000    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
17001        assert_eq!(
17002            ControlHandler::default().privileged_operator_prompt,
17003            PrivilegedOperatorPrompt::Log
17004        );
17005        for (initial, changed, running) in [
17006            ("log", "enforce", PrivilegedOperatorPrompt::Log),
17007            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
17008        ] {
17009            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
17010            let path = dir.join("subc.jsonc");
17011            std::fs::write(
17012                &path,
17013                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
17014            )
17015            .unwrap();
17016            let config = crate::daemon_config::load(&path).unwrap().unwrap();
17017            let registry = Arc::new(Registry::default());
17018            let handle = SupervisorHandle::new();
17019            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
17020                .with_handle(handle.clone());
17021            let handler = ControlHandler::new(registry)
17022                .with_supervisor(handle)
17023                .with_privileged_operator_prompt(config.privileged_operator_prompt)
17024                .with_supervisor_rescan(supervisor, &path, config.port);
17025            handler.forwarding.operator_confirms().configure(
17026                Arc::new(ApproveOperator),
17027                crate::operator_confirm::OperatorLimits::default(),
17028            );
17029            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
17030
17031            for (disk_mode, needs_restart) in [
17032                (Some(initial), false),
17033                (Some(changed), true),
17034                (Some(changed), true),
17035                (None, running == PrivilegedOperatorPrompt::Enforce),
17036                (Some(initial), false),
17037            ] {
17038                let mut doc = json!({"version":1});
17039                if let Some(mode) = disk_mode {
17040                    doc["privileged_operator_prompt"] = json!(mode);
17041                }
17042                std::fs::write(&path, doc.to_string()).unwrap();
17043                for preview in [true, false] {
17044                    let request = ClientControlRequest::SupervisorRescan { preview };
17045                    let frame = Frame::build(
17046                        FrameType::Request,
17047                        control_flags(),
17048                        0,
17049                        0,
17050                        1,
17051                        serde_json::to_vec(&request).unwrap(),
17052                    )
17053                    .unwrap();
17054                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17055                    assert_eq!(frames.len(), 1);
17056                    let ClientControlResponse::SupervisorRescan { result } =
17057                        serde_json::from_slice(&frames[0].body).unwrap()
17058                    else {
17059                        panic!("expected a rescan response");
17060                    };
17061                    let expected = if needs_restart {
17062                        vec!["privileged_operator_prompt"]
17063                    } else {
17064                        Vec::new()
17065                    };
17066                    assert_eq!(result.restart_required, expected);
17067                    assert_eq!(handler.privileged_operator_prompt, running);
17068                    assert_eq!(
17069                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
17070                        running
17071                    );
17072                }
17073            }
17074        }
17075    }
17076
17077    #[tokio::test]
17078    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
17079        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
17080        let path = dir.join("subc.jsonc");
17081        let registry = Arc::new(Registry::default());
17082        let handle = SupervisorHandle::new();
17083        let supervisor =
17084            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
17085        let handler = ControlHandler::new(registry)
17086            .with_supervisor(handle)
17087            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
17088            .with_supervisor_rescan(supervisor, &path, None);
17089        handler.forwarding.operator_confirms().configure(
17090            Arc::new(ApproveOperator),
17091            crate::operator_confirm::OperatorLimits::default(),
17092        );
17093        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
17094        for preview in [true, false] {
17095            std::fs::write(
17096                &path,
17097                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
17098            )
17099            .unwrap();
17100            let request = ClientControlRequest::SupervisorRescan { preview };
17101            let frame = Frame::build(
17102                FrameType::Request,
17103                control_flags(),
17104                0,
17105                0,
17106                1,
17107                serde_json::to_vec(&request).unwrap(),
17108            )
17109            .unwrap();
17110            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
17111            assert_eq!(frames.len(), 1);
17112            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
17113            assert_eq!(
17114                handler.privileged_operator_prompt,
17115                PrivilegedOperatorPrompt::Enforce
17116            );
17117        }
17118    }
17119
17120    /// One wire code has several senders, so the refusal line names the check
17121    /// that refused. This drives the shared refusal path for ordinary refusals
17122    /// with an unregistered
17123    /// target and requires the branch label on the event.
17124    #[tokio::test]
17125    async fn route_open_refusal_names_the_check_that_refused() {
17126        let handler = ControlHandler::new(Arc::new(Registry::default()));
17127        let capture = EventCapture::default();
17128        let _subscriber =
17129            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17130        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17131        let response = handler
17132            .handle_control_frame(
17133                &ctx,
17134                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
17135            )
17136            .await
17137            .unwrap();
17138
17139        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17140        let event = capture
17141            .events()
17142            .into_iter()
17143            .find(|event| {
17144                event.target == "control"
17145                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17146            })
17147            .expect("route.open refusal event");
17148        assert_eq!(
17149            event.fields.get("reason"),
17150            Some(&"\"not_registered\"".to_string())
17151        );
17152    }
17153
17154    #[tokio::test]
17155    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17156        let registry = Arc::new(Registry::default());
17157        let supervisor_handle = SupervisorHandle::new();
17158        let supervisor =
17159            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17160                .with_handle(supervisor_handle.clone())
17161                .with_connection_file_path(std::env::temp_dir().join(format!(
17162                    "subc-route-open-refusal-info-{}",
17163                    std::process::id()
17164                )));
17165        let module = supervisor
17166            .supervise_configured(
17167                ModuleSpec {
17168                    script: None,
17169                    carry_containment: false,
17170                    module_id: "warming".to_string(),
17171                    program: fake_aft_stub_path(),
17172                    args: Vec::new(),
17173                    env: Vec::new(),
17174                    reserved: false,
17175                    reserved_prefixes: Vec::new(),
17176                    protocol: ModuleProtocol::Subc,
17177                    overlap: Default::default(),
17178                },
17179                true,
17180            )
17181            .unwrap();
17182        assert_eq!(module.state().unwrap(), ModuleState::Running);
17183
17184        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17185        assert!(handler
17186            .counters()
17187            .snapshot()
17188            .get("route_open_refused_by_code")
17189            .is_none());
17190        let capture = EventCapture::default();
17191        let _subscriber =
17192            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17193        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17194        let response = handler
17195            .handle_control_frame(
17196                &ctx,
17197                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17198            )
17199            .await
17200            .unwrap();
17201        module.stop().await.unwrap();
17202
17203        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17204        let event = capture
17205            .events()
17206            .into_iter()
17207            .find(|event| {
17208                event.target == "control"
17209                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17210            })
17211            .expect("route.open refusal event");
17212        assert_eq!(
17213            event.fields.get("module_id"),
17214            Some(&"\"warming\"".to_string())
17215        );
17216        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17217        assert_eq!(
17218            event.fields.get("reason"),
17219            Some(&"\"supervised_not_registered\"".to_string())
17220        );
17221        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17222        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17223        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17224        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17225        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17226        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17227        assert_eq!(
17228            handler.counters().snapshot()["route_open_refused_by_code"],
17229            json!({ "module_warming": 1 })
17230        );
17231    }
17232
17233    const OUTAGE_START: &str = "route.open refusing module: not serving";
17234    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17235
17236    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17237        capture
17238            .events()
17239            .into_iter()
17240            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17241            .collect()
17242    }
17243
17244    fn supervise_stub(
17245        registry: &Arc<Registry>,
17246        module_id: &str,
17247        enabled: bool,
17248    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17249        let supervisor_handle = SupervisorHandle::new();
17250        let supervisor =
17251            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17252                .with_handle(supervisor_handle.clone())
17253                .with_connection_file_path(std::env::temp_dir().join(format!(
17254                    "subc-route-outage-{module_id}-{}",
17255                    std::process::id()
17256                )));
17257        let module = supervisor
17258            .supervise_configured(
17259                ModuleSpec {
17260                    script: None,
17261                    carry_containment: false,
17262                    module_id: module_id.to_string(),
17263                    program: fake_aft_stub_path(),
17264                    args: Vec::new(),
17265                    env: Vec::new(),
17266                    reserved: false,
17267                    reserved_prefixes: Vec::new(),
17268                    protocol: ModuleProtocol::Subc,
17269                    overlap: Default::default(),
17270                },
17271                enabled,
17272            )
17273            .unwrap();
17274        (supervisor_handle, module)
17275    }
17276
17277    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17278        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17279            module_id: module_id.to_string(),
17280            drain_timeout_ms: Some(50),
17281        })
17282        .unwrap();
17283        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17284    }
17285
17286    /// Two handlers built over one forwarding table must share one outage
17287    /// tracker; separate trackers would each log their own opening line for
17288    /// the same outage.
17289    #[test]
17290    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17291        let registry = Arc::new(Registry::default());
17292        let forwarding = Arc::new(ForwardingTable::default());
17293        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17294        let second = ControlHandler::with_forwarding(registry, forwarding);
17295        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17296    }
17297
17298    /// A client can name any module id it likes. Refusing an unknown one,
17299    /// however often, must not create outage state or outage lines, or the
17300    /// tracker would be a memory sink any client could fill.
17301    #[tokio::test(flavor = "current_thread")]
17302    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17303        let handler = ControlHandler::new(Arc::new(Registry::default()));
17304        let capture = EventCapture::default();
17305        let _subscriber =
17306            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17307        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17308        for corr in 0..8 {
17309            let response = handler
17310                .handle_control_frame(
17311                    &ctx,
17312                    route_open_frame(
17313                        380 + corr,
17314                        &format!("nobody-{corr}"),
17315                        unique_project_root("outage-unknown"),
17316                    ),
17317                )
17318                .await
17319                .unwrap();
17320            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17321        }
17322
17323        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17324        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17325        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17326    }
17327
17328    /// Drives the refusal path end to end: a supervised module that served
17329    /// before and stopped being registered with no instruction to stop is a
17330    /// WARN, and the same module refused after an operator `supervisor.restart`
17331    /// is an INFO.
17332    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17333    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17334        let registry = Arc::new(Registry::default());
17335        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17336        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17337        let capture = EventCapture::default();
17338        let _subscriber =
17339            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17340        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17341        // The stub never registers, so pretend it served once: otherwise every
17342        // refusal would fall in its startup window.
17343        handler.route_outages.record_accepted("outage-restart");
17344
17345        let response = handler
17346            .handle_control_frame(
17347                &ctx,
17348                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17349            )
17350            .await
17351            .unwrap();
17352        assert_eq!(response[0].header.ty, FrameType::Error);
17353        let starts = outage_lines(&capture, OUTAGE_START);
17354        assert_eq!(starts.len(), 1, "{starts:?}");
17355        assert_eq!(starts[0].level, tracing::Level::WARN);
17356        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17357        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17358        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17359        handler.route_outages.record_accepted("outage-restart");
17360        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17361
17362        // The missing connection file makes the stub exit immediately. Restart
17363        // is deliberately deferred while that exit is being recorded; Failed
17364        // means the zero restart budget and terminal record have been published.
17365        tokio::time::timeout(Duration::from_secs(10), async {
17366            while module.state().unwrap() != crate::ModuleState::Failed {
17367                tokio::task::yield_now().await;
17368            }
17369        })
17370        .await
17371        .expect("stub exit must be recorded before the operator restart");
17372
17373        let restart = handler
17374            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17375            .await
17376            .unwrap();
17377        assert_eq!(
17378            restart[0].header.ty,
17379            FrameType::Response,
17380            "{:?}",
17381            parse_error(&restart[0])
17382        );
17383        handler
17384            .handle_control_frame(
17385                &ctx,
17386                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17387            )
17388            .await
17389            .unwrap();
17390        module.stop().await.unwrap();
17391
17392        let starts = outage_lines(&capture, OUTAGE_START);
17393        assert_eq!(starts.len(), 2, "{starts:?}");
17394        assert_eq!(starts[1].level, tracing::Level::INFO);
17395        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17396    }
17397
17398    /// A restart refused before it touched the module (here: the module is
17399    /// disabled) must clear its operator mark, so the next real outage is
17400    /// still reported as a warning.
17401    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17402    async fn failed_operator_restart_leaves_no_operator_mark() {
17403        let registry = Arc::new(Registry::default());
17404        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17405        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17406        let capture = EventCapture::default();
17407        let _subscriber =
17408            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17409        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17410        handler.route_outages.record_accepted("outage-disabled");
17411
17412        let restart = handler
17413            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17414            .await
17415            .unwrap();
17416        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17417        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17418
17419        handler
17420            .handle_control_frame(
17421                &ctx,
17422                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17423            )
17424            .await
17425            .unwrap();
17426        let starts = outage_lines(&capture, OUTAGE_START);
17427        assert_eq!(starts.len(), 1, "{starts:?}");
17428        assert_eq!(starts[0].level, tracing::Level::WARN);
17429    }
17430
17431    #[tokio::test(flavor = "current_thread")]
17432    async fn route_open_unknown_module_escapes_target_module_id() {
17433        let handler = ControlHandler::new(Arc::new(Registry::default()));
17434        let capture = EventCapture::default();
17435        let _subscriber =
17436            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17437        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17438        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17439        let response = handler
17440            .handle_control_frame(
17441                &ctx,
17442                route_open_frame(
17443                    395,
17444                    hostile_module_id,
17445                    unique_project_root("hostile-target-module-id"),
17446                ),
17447            )
17448            .await
17449            .unwrap();
17450
17451        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17452        let event = capture
17453            .events()
17454            .into_iter()
17455            .find(|event| {
17456                event.target == "control"
17457                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17458            })
17459            .expect("route.open unknown-module refusal event");
17460        let logged = event.fields.get("module_id").expect("module_id field");
17461        assert!(!logged.bytes().any(|byte| byte < 0x20));
17462        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17463    }
17464
17465    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17466    /// the daemon-origin bit on the frame the client receives.
17467    #[tokio::test(flavor = "current_thread")]
17468    async fn route_open_refusal_carries_daemon_origin() {
17469        let handler = ControlHandler::new(Arc::new(Registry::default()));
17470        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17471        let response = handler
17472            .handle_control_frame(
17473                &ctx,
17474                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17475            )
17476            .await
17477            .unwrap();
17478
17479        assert_eq!(response.len(), 1);
17480        assert_eq!(response[0].header.ty, FrameType::Error);
17481        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17482        assert!(
17483            response[0].header.flags.is_daemon_origin(),
17484            "route.open refusal must carry daemon origin: {:?}",
17485            response[0].header.flags
17486        );
17487    }
17488
17489    /// The drain `module_reloading` refusal is daemon-synthesized for an
17490    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17491    /// frame the client receives.
17492    #[tokio::test(flavor = "current_thread")]
17493    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17494        let registry = Arc::new(Registry::default());
17495        let forwarding = Arc::new(ForwardingTable::default());
17496        let handler =
17497            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17498        let module_connection = ConnectionId::new(95);
17499        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17500        hello_via_sink(
17501            &handler,
17502            &module_ctx,
17503            &mut module_rx,
17504            hello_frame("aft", PROTOCOL_VERSION, 395),
17505        )
17506        .await;
17507        forwarding
17508            .begin_module_drain("aft", RouteCloseReason::Restart)
17509            .unwrap()
17510            .expect("the module endpoint drains");
17511
17512        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17513        let response = handler
17514            .handle_control_frame(
17515                &client_ctx,
17516                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17517            )
17518            .await
17519            .unwrap();
17520
17521        assert_eq!(response.len(), 1);
17522        assert_eq!(response[0].header.ty, FrameType::Error);
17523        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17524        assert!(
17525            response[0].header.flags.is_daemon_origin(),
17526            "drain module_reloading must carry daemon origin: {:?}",
17527            response[0].header.flags
17528        );
17529    }
17530
17531    /// A module that refuses a bind with a daemon code still cannot mint a
17532    /// daemon refusal: the relayed `module_reloading` body reaches the client
17533    /// with the daemon-origin bit clear.
17534    #[tokio::test(flavor = "current_thread")]
17535    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17536        let registry = Arc::new(Registry::default());
17537        let forwarding = Arc::new(ForwardingTable::default());
17538        let handler =
17539            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17540        let module_connection = ConnectionId::new(95);
17541        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17542        hello_via_sink(
17543            &handler,
17544            &module_ctx,
17545            &mut module_rx,
17546            hello_frame("aft", PROTOCOL_VERSION, 395),
17547        )
17548        .await;
17549
17550        let client_connection = ConnectionId::new(96);
17551        let (client_ctx, _client_rx) = route_ctx(client_connection);
17552        let (route_task, bind) = relay_route_open(
17553            &handler,
17554            client_connection,
17555            &client_ctx.egress,
17556            &mut module_rx,
17557            396,
17558            "aft",
17559            "spoofed-reloading",
17560        )
17561        .await;
17562        // The module sets the origin bit on its own rejection too: neither
17563        // the bit nor the daemon code may survive the relay as daemon-owned.
17564        let rejection = Frame::build(
17565            FrameType::Error,
17566            crate::router::daemon_error_flags(),
17567            0,
17568            0,
17569            bind.header.corr,
17570            serde_json::to_vec(&ErrorBody::new(
17571                "module_reloading",
17572                "module refused route.bind",
17573            ))
17574            .unwrap(),
17575        )
17576        .unwrap();
17577        handler
17578            .handle_control_frame(&module_ctx, rejection)
17579            .await
17580            .unwrap();
17581
17582        let response = route_task.await.unwrap();
17583        assert_eq!(response.len(), 1);
17584        assert_eq!(response[0].header.ty, FrameType::Error);
17585        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17586        assert!(
17587            !response[0].header.flags.is_daemon_origin(),
17588            "a module's own rejection must not carry daemon origin: {:?}",
17589            response[0].header.flags
17590        );
17591    }
17592
17593    #[tokio::test(flavor = "current_thread")]
17594    async fn route_open_module_rejection_uses_daemon_counter_key() {
17595        let registry = Arc::new(Registry::default());
17596        let forwarding = Arc::new(ForwardingTable::default());
17597        let handler =
17598            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17599        let module_connection = ConnectionId::new(95);
17600        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17601        hello_via_sink(
17602            &handler,
17603            &module_ctx,
17604            &mut module_rx,
17605            hello_frame("aft", PROTOCOL_VERSION, 395),
17606        )
17607        .await;
17608
17609        let client_connection = ConnectionId::new(96);
17610        let (client_ctx, _client_rx) = route_ctx(client_connection);
17611        let capture = EventCapture::default();
17612        // tracing-core decides once per callsite whether its events are enabled,
17613        // and caches the answer. If a parallel test with no subscriber reaches
17614        // this callsite first, the cached answer is "disabled" and this test's
17615        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17616        // ask every live subscriber instead, while only this test's default
17617        // receives the events.
17618        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17619        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17620        let _subscriber =
17621            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17622        let (route_task, bind) = relay_route_open(
17623            &handler,
17624            client_connection,
17625            &client_ctx.egress,
17626            &mut module_rx,
17627            396,
17628            "aft",
17629            "hostile-module-code",
17630        )
17631        .await;
17632        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17633        let rejection = Frame::build(
17634            FrameType::Error,
17635            control_flags(),
17636            0,
17637            0,
17638            bind.header.corr,
17639            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17640        )
17641        .unwrap();
17642        handler
17643            .handle_control_frame(&module_ctx, rejection)
17644            .await
17645            .unwrap();
17646
17647        let response = route_task.await.unwrap();
17648        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17649        let counters = handler.counters().snapshot();
17650        assert_eq!(
17651            counters["route_open_refused_by_code"],
17652            json!({ "module_rejected": 1 })
17653        );
17654        assert!(counters["route_open_refused_by_code"]
17655            .get(hostile_code)
17656            .is_none());
17657
17658        let event = capture
17659            .events()
17660            .into_iter()
17661            .find(|event| {
17662                event.target == "control"
17663                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17664            })
17665            .expect("route.open module-rejection refusal event");
17666        let logged = event.fields.get("module_code").expect("module_code field");
17667        assert!(!logged.bytes().any(|byte| byte < 0x20));
17668        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17669    }
17670
17671    #[tokio::test]
17672    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17673        let registry = Arc::new(Registry::default());
17674        let supervisor_handle = SupervisorHandle::new();
17675        let missing_program = std::env::temp_dir().join(format!(
17676            "subc-route-open-missing-program-{}",
17677            std::process::id()
17678        ));
17679        let supervisor =
17680            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17681                .with_handle(supervisor_handle.clone());
17682        let module = supervisor
17683            .supervise_configured(
17684                ModuleSpec {
17685                    script: None,
17686                    carry_containment: false,
17687                    module_id: "failed".to_string(),
17688                    program: missing_program,
17689                    args: Vec::new(),
17690                    env: Vec::new(),
17691                    reserved: false,
17692                    reserved_prefixes: Vec::new(),
17693                    protocol: ModuleProtocol::Subc,
17694                    overlap: Default::default(),
17695                },
17696                true,
17697            )
17698            .unwrap();
17699        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17700
17701        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17702        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17703        let response = handler
17704            .handle_control_frame(
17705                &ctx,
17706                route_open_frame(305, "failed", unique_project_root("failed")),
17707            )
17708            .await
17709            .unwrap();
17710
17711        assert_eq!(response[0].header.ty, FrameType::Error);
17712        let error = parse_error(&response[0]);
17713        assert_eq!(error["code"], "target_unavailable");
17714        assert!(error["message"]
17715            .as_str()
17716            .unwrap()
17717            .contains("state=failed, enabled=true, live=false"));
17718    }
17719
17720    #[tokio::test]
17721    async fn route_open_role_mismatch_remains_target_unavailable() {
17722        let registry = Arc::new(Registry::default());
17723        let handler = ControlHandler::new(Arc::clone(&registry));
17724        handler
17725            .handle_control(
17726                ConnectionId::new(41),
17727                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17728            )
17729            .unwrap();
17730
17731        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17732        let response = handler
17733            .handle_control_frame(
17734                &ctx,
17735                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17736            )
17737            .await
17738            .unwrap();
17739
17740        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17741        assert!(parse_error(&response[0])["message"]
17742            .as_str()
17743            .unwrap()
17744            .contains("does not provide the requested target"));
17745    }
17746
17747    #[tokio::test]
17748    async fn route_open_inactive_registration_remains_target_unavailable() {
17749        let registry = Arc::new(Registry::default());
17750        let handler = ControlHandler::new(Arc::clone(&registry));
17751        handler
17752            .handle_control(
17753                ConnectionId::new(43),
17754                hello_frame("inactive", PROTOCOL_VERSION, 308),
17755            )
17756            .unwrap();
17757        assert!(registry
17758            .set_module_state_for_test("inactive", ChannelState::Closed)
17759            .unwrap());
17760
17761        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17762        let response = handler
17763            .handle_control_frame(
17764                &ctx,
17765                route_open_frame(309, "inactive", unique_project_root("inactive")),
17766            )
17767            .await
17768            .unwrap();
17769
17770        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17771        assert!(parse_error(&response[0])["message"]
17772            .as_str()
17773            .unwrap()
17774            .contains("is not active"));
17775    }
17776
17777    #[tokio::test]
17778    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17779        let registry = Arc::new(Registry::default());
17780        let forwarding = Arc::new(ForwardingTable::default());
17781        let supervisor_handle = SupervisorHandle::new();
17782        let supervisor =
17783            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17784                .with_forwarding(Arc::clone(&forwarding))
17785                .with_handle(supervisor_handle.clone());
17786        let module = supervisor
17787            .supervise_configured(
17788                crate::ModuleSpec {
17789                    script: None,
17790                    carry_containment: false,
17791                    module_id: "late-health-response".to_string(),
17792                    program: PathBuf::from("disabled-module"),
17793                    args: Vec::new(),
17794                    env: Vec::new(),
17795                    reserved: false,
17796                    reserved_prefixes: Vec::new(),
17797                    protocol: ModuleProtocol::Subc,
17798                    overlap: Default::default(),
17799                },
17800                false,
17801            )
17802            .unwrap();
17803        let handler =
17804            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17805                .with_supervisor(supervisor_handle);
17806        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17807        handler
17808            .handle_control_frame(
17809                &module_ctx,
17810                hello_frame_with_control_ops(
17811                    "late-health-response",
17812                    PROTOCOL_VERSION,
17813                    7,
17814                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17815                ),
17816            )
17817            .await
17818            .unwrap();
17819        let probe_started_at = Instant::now() - Duration::from_millis(80);
17820        let pending = forwarding
17821            .begin_health_probe_rpc_for(
17822                "late-health-response",
17823                MODULE_CONTROL_OP_HEALTH_CHECK,
17824                probe_started_at,
17825                Instant::now() - Duration::from_millis(1),
17826            )
17827            .unwrap();
17828        assert!(forwarding
17829            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17830            .unwrap());
17831
17832        let responses = handler
17833            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17834            .await
17835            .unwrap();
17836
17837        assert!(responses.is_empty());
17838        let health = module.status().unwrap().health;
17839        assert_eq!(health.late_answer_count, 1);
17840        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17841    }
17842
17843    #[tokio::test]
17844    async fn health_probe_timeout_and_module_death_are_typed() {
17845        let registry = Arc::new(Registry::default());
17846        let forwarding = Arc::new(ForwardingTable::default());
17847        let handler =
17848            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17849                .with_health_probe_timeout(Duration::from_millis(50));
17850        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17851        hello_via_sink(
17852            &handler,
17853            &module_ctx,
17854            &mut module_rx,
17855            hello_frame_with_control_ops(
17856                "aft",
17857                PROTOCOL_VERSION,
17858                7,
17859                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17860            ),
17861        )
17862        .await;
17863
17864        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17865        let responses = handler
17866            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17867            .await
17868            .unwrap();
17869        assert_eq!(responses[0].header.ty, FrameType::Error);
17870        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17871        let _ = module_rx.try_recv();
17872
17873        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17874        let health_handler = handler.clone();
17875        let death_task = tokio::spawn(async move {
17876            health_handler
17877                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17878                .await
17879                .unwrap()
17880        });
17881        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17882            .await
17883            .unwrap()
17884            .unwrap();
17885        handler
17886            .cleanup_connection(module_ctx.connection_id)
17887            .unwrap();
17888        let responses = death_task.await.unwrap();
17889        assert_eq!(responses[0].header.ty, FrameType::Error);
17890        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17891    }
17892
17893    #[test]
17894    fn hello_requires_exact_protocol_version() {
17895        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17896            let registry = Arc::new(Registry::default());
17897            let handler = ControlHandler::new(Arc::clone(&registry));
17898            let responses = handler
17899                .handle_control(
17900                    ConnectionId::new(connection),
17901                    hello_frame("aft", offered, 9),
17902                )
17903                .unwrap();
17904
17905            assert_eq!(responses.len(), 1);
17906            assert_eq!(responses[0].header.ty, FrameType::Error);
17907            let error = parse_error(&responses[0]);
17908            assert_eq!(error["code"], "version_unsupported");
17909            assert!(registry.get_module("aft").unwrap().is_none());
17910            assert_eq!(registry.active_registration_count().unwrap(), 0);
17911        }
17912    }
17913
17914    #[test]
17915    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17916        let registry = Arc::new(Registry::default());
17917        let forwarding = Arc::new(ForwardingTable::default());
17918        let handler =
17919            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17920        let module_connection = ConnectionId::new(301);
17921        let registration = registry
17922            .register_with_control_ops(
17923                manifest("aft-push", PROTOCOL_VERSION),
17924                PROTOCOL_VERSION,
17925                module_connection,
17926                module_baseline_control_ops(),
17927            )
17928            .unwrap();
17929        let (module_tx, _module_rx) = mpsc::channel(8);
17930        let endpoint = forwarding
17931            .register_module_connection(
17932                module_connection,
17933                "aft-push".to_string(),
17934                PROTOCOL_VERSION,
17935                manifest_concurrency(&registration.manifest),
17936                FrameSink::new(module_tx),
17937            )
17938            .unwrap();
17939
17940        // A push op this version does not know is ignored (forward-compat), not errored.
17941        let unknown = Frame::build(
17942            FrameType::Push,
17943            control_flags(),
17944            0,
17945            0,
17946            5,
17947            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17948        )
17949        .unwrap();
17950        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17951        assert!(
17952            out.is_empty(),
17953            "unknown push op must be ignored, got {out:?}"
17954        );
17955
17956        // A malformed body for a KNOWN op is a real error worth surfacing.
17957        let malformed = Frame::build(
17958            FrameType::Push,
17959            control_flags(),
17960            0,
17961            0,
17962            6,
17963            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17964        )
17965        .unwrap();
17966        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17967        assert_eq!(out.len(), 1);
17968        assert_eq!(out[0].header.ty, FrameType::Error);
17969        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17970    }
17971
17972    #[test]
17973    fn hello_rejected_when_connection_already_owns_client_routes() {
17974        let registry = Arc::new(Registry::default());
17975        let forwarding = Arc::new(ForwardingTable::default());
17976        let handler =
17977            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17978        // Commits a client route on connection 202 (bound to a module on conn 101).
17979        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17980        let client_connection = ConnectionId::new(202);
17981
17982        // That same connection now tries to register as a module: rejected, so one
17983        // connection never holds both client-route and module-endpoint state.
17984        let responses = handler
17985            .handle_control(
17986                client_connection,
17987                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17988            )
17989            .unwrap();
17990        assert_eq!(responses[0].header.ty, FrameType::Error);
17991        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17992        assert!(registry.get_module("aft-second").unwrap().is_none());
17993    }
17994
17995    #[tokio::test]
17996    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17997        let registry = Arc::new(Registry::default());
17998        let forwarding = Arc::new(ForwardingTable::default());
17999        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
18000        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
18001        hello_via_sink(
18002            &handler,
18003            &module_ctx,
18004            &mut module_rx,
18005            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
18006        )
18007        .await;
18008        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
18009        let pending = forwarding
18010            .begin_route_bind_relay_for_test(
18011                client_ctx.connection_id,
18012                client_ctx.egress.clone(),
18013                2,
18014                "alpha",
18015            )
18016            .unwrap();
18017        forwarding
18018            .complete_pending_relay(
18019                module_ctx.connection_id,
18020                pending.corr,
18021                RouteBindRelayOutcome::Accepted,
18022            )
18023            .unwrap();
18024        client_rx.try_recv().unwrap();
18025        for module_id in ["beta", "alpha"] {
18026            let replies = handler
18027                .handle_control_frame(
18028                    &module_ctx,
18029                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
18030                )
18031                .await
18032                .unwrap();
18033            assert_eq!(replies.len(), 1, "second HELLO must be refused");
18034            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
18035        }
18036        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
18037        assert!(registry.get_module("beta").unwrap().is_none());
18038        assert!(matches!(
18039            forwarding
18040                .lookup_data_route(
18041                    client_ctx.connection_id,
18042                    pending.client_channel,
18043                    pending.client_epoch,
18044                )
18045                .unwrap(),
18046            DataRoute::Client(DataRouteState::Bound(_))
18047        ));
18048        assert!(handler
18049            .hello_launch_nonces
18050            .lock()
18051            .unwrap()
18052            .presented(module_ctx.connection_id, Some("alpha-nonce")));
18053        assert!(module_rx.try_recv().is_err());
18054    }
18055
18056    #[test]
18057    fn reserved_module_hello_requires_matching_launch_nonce() {
18058        let registry = Arc::new(Registry::default());
18059        let supervisor = SupervisorHandle::new();
18060        // The supervisor recorded the nonce it injected when it spawned the reserved
18061        // module; the HELLO verifier checks against the same shared handle.
18062        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
18063        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18064
18065        // A HELLO with NO nonce is rejected.
18066        let no_nonce = handler
18067            .handle_control(
18068                ConnectionId::new(1),
18069                hello_frame("vault", PROTOCOL_VERSION, 1),
18070            )
18071            .unwrap();
18072        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
18073        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
18074        assert!(registry.get_module("vault").unwrap().is_none());
18075
18076        // A HELLO with the WRONG nonce is rejected.
18077        let wrong = handler
18078            .handle_control(
18079                ConnectionId::new(2),
18080                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
18081            )
18082            .unwrap();
18083        assert_eq!(wrong[0].header.ty, FrameType::Error);
18084        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
18085        assert!(registry.get_module("vault").unwrap().is_none());
18086
18087        // A HELLO with the CORRECT nonce registers.
18088        let ok = handler
18089            .handle_control(
18090                ConnectionId::new(3),
18091                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
18092            )
18093            .unwrap();
18094        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
18095        assert!(registry.get_module("vault").unwrap().is_some());
18096    }
18097
18098    #[test]
18099    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
18100        let registry = Arc::new(Registry::default());
18101        let supervisor = SupervisorHandle::new();
18102        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18103        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18104        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18105
18106        let squat = handler
18107            .handle_control(
18108                ConnectionId::new(1),
18109                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
18110            )
18111            .unwrap();
18112        assert_eq!(squat[0].header.ty, FrameType::Error);
18113        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
18114        assert!(parse_error(&squat[0])["message"]
18115            .as_str()
18116            .unwrap()
18117            .contains("fed:"));
18118
18119        let accepted_peer = handler
18120            .handle_control(
18121                ConnectionId::new(2),
18122                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
18123            )
18124            .unwrap();
18125        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
18126
18127        let accepted_short = handler
18128            .handle_control(
18129                ConnectionId::new(3),
18130                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
18131            )
18132            .unwrap();
18133        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
18134
18135        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
18136            let response = handler
18137                .handle_control(
18138                    ConnectionId::new(conn),
18139                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18140                )
18141                .unwrap();
18142            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18143        }
18144    }
18145
18146    #[test]
18147    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18148        let registry = Arc::new(Registry::default());
18149        let supervisor = SupervisorHandle::new();
18150        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18151        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18152        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18153        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18154
18155        let owner_nonce = handler
18156            .handle_control(
18157                ConnectionId::new(1),
18158                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18159            )
18160            .unwrap();
18161        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18162        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18163        assert!(registry.get_module("fed:special").unwrap().is_none());
18164
18165        let exact_nonce = handler
18166            .handle_control(
18167                ConnectionId::new(2),
18168                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18169            )
18170            .unwrap();
18171        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18172        assert!(registry.get_module("fed:special").unwrap().is_some());
18173    }
18174
18175    #[test]
18176    fn non_reserved_module_ignores_launch_nonce() {
18177        let registry = Arc::new(Registry::default());
18178        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18179        // registration succeeds whether a spawned process echoes a nonce or not.
18180        let handler = ControlHandler::new(Arc::clone(&registry));
18181        let no_nonce = handler
18182            .handle_control(
18183                ConnectionId::new(1),
18184                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18185            )
18186            .unwrap();
18187        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18188        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18189
18190        let echoed_nonce = handler
18191            .handle_control(
18192                ConnectionId::new(2),
18193                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18194            )
18195            .unwrap();
18196        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18197        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18198    }
18199
18200    #[test]
18201    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18202        let handler = ControlHandler::default();
18203        let conn = ConnectionId::new(1);
18204        let malformed = Frame::build(
18205            FrameType::Hello,
18206            control_flags(),
18207            0,
18208            0,
18209            3,
18210            b"{not json".to_vec(),
18211        )
18212        .unwrap();
18213
18214        let error = handler.handle_control(conn, malformed).unwrap();
18215        assert_eq!(error[0].header.ty, FrameType::Error);
18216        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18217
18218        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18219        let pong = handler.handle_control(conn, ping).unwrap();
18220        assert_eq!(pong[0].header.ty, FrameType::Pong);
18221        assert_eq!(pong[0].header.corr, 4);
18222    }
18223
18224    #[test]
18225    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18226        let registry = Arc::new(Registry::default());
18227        let handler = ControlHandler::new(Arc::clone(&registry));
18228
18229        handler
18230            .handle_control(
18231                ConnectionId::new(1),
18232                hello_frame("aft", PROTOCOL_VERSION, 1),
18233            )
18234            .unwrap();
18235        let duplicate = handler
18236            .handle_control(
18237                ConnectionId::new(2),
18238                hello_frame("aft", PROTOCOL_VERSION, 2),
18239            )
18240            .unwrap();
18241
18242        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18243        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18244        let registration = registry.get_module("aft").unwrap().unwrap();
18245        assert_eq!(registration.connection_id, ConnectionId::new(1));
18246    }
18247
18248    #[test]
18249    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18250        let registry = Arc::new(Registry::default());
18251        let forwarding = Arc::new(ForwardingTable::default());
18252        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18253        let handler =
18254            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18255                .with_process_liveness(process_liveness);
18256        let (ctx, route_channel, route_epoch) =
18257            bind_liveness_route(&registry, &forwarding, "aft-dead");
18258        let responses = handler
18259            .handle_route_poll(
18260                &ctx,
18261                route_poll_frame(41, PollKind::Liveness, route_channel),
18262                route_channel,
18263                route_epoch,
18264                PollKind::Liveness,
18265            )
18266            .unwrap();
18267
18268        assert_eq!(responses.len(), 1);
18269        assert_eq!(responses[0].header.ty, FrameType::Response);
18270        assert_route_poll_liveness(&responses[0], false);
18271    }
18272
18273    #[test]
18274    fn liveness_poll_without_process_source_uses_bound_route() {
18275        let registry = Arc::new(Registry::default());
18276        let forwarding = Arc::new(ForwardingTable::default());
18277        let handler =
18278            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18279        let (ctx, route_channel, route_epoch) =
18280            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18281        let responses = handler
18282            .handle_route_poll(
18283                &ctx,
18284                route_poll_frame(42, PollKind::Liveness, route_channel),
18285                route_channel,
18286                route_epoch,
18287                PollKind::Liveness,
18288            )
18289            .unwrap();
18290
18291        assert_route_poll_liveness(&responses[0], true);
18292    }
18293
18294    #[test]
18295    fn liveness_poll_untracked_process_source_uses_bound_route() {
18296        let registry = Arc::new(Registry::default());
18297        let forwarding = Arc::new(ForwardingTable::default());
18298        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18299        let handler =
18300            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18301                .with_process_liveness(process_liveness);
18302        let (ctx, route_channel, route_epoch) =
18303            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18304        let responses = handler
18305            .handle_route_poll(
18306                &ctx,
18307                route_poll_frame(43, PollKind::Liveness, route_channel),
18308                route_channel,
18309                route_epoch,
18310                PollKind::Liveness,
18311            )
18312            .unwrap();
18313
18314        assert_route_poll_liveness(&responses[0], true);
18315    }
18316
18317    #[tokio::test]
18318    async fn unknown_op_returns_unknown_control_op() {
18319        let handler = ControlHandler::default();
18320        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18321        let request = Frame::build(
18322            FrameType::Request,
18323            control_flags(),
18324            0,
18325            0,
18326            55,
18327            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18328        )
18329        .unwrap();
18330
18331        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18332
18333        assert_eq!(response.len(), 1);
18334        assert_eq!(response[0].header.ty, FrameType::Error);
18335        assert_eq!(response[0].header.corr, 55);
18336        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18337    }
18338
18339    #[tokio::test]
18340    async fn supervisor_provenance_rejects_unknown_exact_module() {
18341        let handler = ControlHandler::default();
18342        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18343        let request = Frame::build(
18344            FrameType::Request,
18345            control_flags(),
18346            0,
18347            0,
18348            57,
18349            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18350        )
18351        .unwrap();
18352
18353        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18354
18355        assert_eq!(response.len(), 1);
18356        assert_eq!(response[0].header.ty, FrameType::Error);
18357        assert_eq!(response[0].header.corr, 57);
18358        let error = parse_error(&response[0]);
18359        assert_eq!(error["code"], "unknown_module");
18360        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18361    }
18362
18363    #[test]
18364    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18365        let expected = subc_control::RunningImageAgreement::Unavailable {
18366            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18367        };
18368        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18369        assert_eq!(handler.provenance_probe_override, Some(expected));
18370    }
18371
18372    #[test]
18373    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18374        let verdict = reload_verdict(
18375            std::path::Path::new("/bin/new"),
18376            Some(std::path::Path::new("/bin/old")),
18377            subc_control::RunningImageAgreement::Unavailable {
18378                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18379            },
18380        );
18381        assert!(matches!(
18382            verdict.path,
18383            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18384                if configured == std::path::Path::new("/bin/new")
18385                    && spawned_from == std::path::Path::new("/bin/old")
18386        ));
18387    }
18388
18389    #[test]
18390    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18391        use subc_control::{
18392            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18393        };
18394        let configured = crate::supervise::ModuleSpec {
18395            script: None,
18396            carry_containment: false,
18397            module_id: "legacy".into(),
18398            program: "/module".into(),
18399            args: Vec::new(),
18400            env: Vec::new(),
18401            reserved: false,
18402            reserved_prefixes: Vec::new(),
18403            protocol: subc_control::ModuleProtocol::Subc,
18404            overlap: Default::default(),
18405        };
18406        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18407        assert_eq!(
18408            launch_spec_agreement(&configured, false, Some(&digest)),
18409            Agreement::Unavailable {
18410                reason: Reason::NotRunning
18411            }
18412        );
18413        assert_eq!(
18414            launch_spec_agreement(&configured, true, None),
18415            Agreement::Unavailable {
18416                reason: Reason::SpawnedSpecUnavailable
18417            }
18418        );
18419        assert_eq!(
18420            launch_spec_agreement(&configured, true, Some(&digest)),
18421            Agreement::Match
18422        );
18423    }
18424
18425    #[cfg(windows)]
18426    #[test]
18427    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18428        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18429        let configured = dir.join("module.exe");
18430        std::fs::write(&configured, b"executable path fixture").unwrap();
18431        let spawned = std::fs::canonicalize(&configured).unwrap();
18432        assert_ne!(
18433            configured, spawned,
18434            "fixture must exercise different path spellings"
18435        );
18436        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18437        let lower_case = configured.to_string_lossy().to_lowercase();
18438        for spelling in [
18439            &configured,
18440            Path::new(&forward_slashes),
18441            Path::new(&lower_case),
18442        ] {
18443            let verdict = reload_verdict(
18444                spelling,
18445                Some(&spawned),
18446                subc_control::RunningImageAgreement::Unavailable {
18447                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18448                },
18449            );
18450            assert_eq!(
18451                verdict.path,
18452                ReloadPathAgreement::Match,
18453                "configured {spelling:?}, spawned {spawned:?}"
18454            );
18455        }
18456    }
18457
18458    #[cfg(windows)]
18459    #[test]
18460    fn windows_reload_path_keeps_different_existing_program_pending() {
18461        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18462        let old = dir.join("old.exe");
18463        let new = dir.join("new.exe");
18464        std::fs::write(&old, b"same executable content").unwrap();
18465        std::fs::copy(&old, &new).unwrap();
18466        let spawned = std::fs::canonicalize(&old).unwrap();
18467        let image = subc_control::RunningImageAgreement::Unavailable {
18468            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18469        };
18470        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18471        assert!(
18472            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18473            if configured == new && spawned_from == spawned)
18474        );
18475        let missing = dir.join("missing.exe");
18476        assert!(matches!(
18477            reload_verdict(&missing, Some(&spawned), image).path,
18478            ReloadPathAgreement::Mismatch { .. }
18479        ));
18480    }
18481
18482    #[test]
18483    fn reload_verdict_detects_replaced_image_at_same_path() {
18484        let image = subc_control::RunningImageAgreement::Mismatch {
18485            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18486                digest: "old".into(),
18487            },
18488            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18489                digest: "new".into(),
18490            },
18491        };
18492        let verdict = reload_verdict(
18493            std::path::Path::new("/bin/same"),
18494            Some(std::path::Path::new("/bin/same")),
18495            image.clone(),
18496        );
18497        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18498        assert_eq!(verdict.image, image);
18499    }
18500
18501    #[test]
18502    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18503        let image = subc_control::RunningImageAgreement::Unavailable {
18504            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18505        };
18506        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18507        assert_eq!(
18508            verdict.path,
18509            subc_control::ReloadPathAgreement::Unavailable {
18510                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18511            }
18512        );
18513        assert_eq!(verdict.image, image);
18514
18515        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18516            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18517        };
18518        let verdict = reload_verdict(
18519            std::path::Path::new("/bin/same"),
18520            Some(std::path::Path::new("/bin/same")),
18521            unconfirmed.clone(),
18522        );
18523        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18524        assert_eq!(verdict.image, unconfirmed);
18525    }
18526
18527    #[test]
18528    fn reload_verdict_preserves_each_image_unavailability_reason() {
18529        use subc_control::RunningImageUnavailableReason as Reason;
18530
18531        for reason in [
18532            Reason::NotRunning,
18533            Reason::UnsupportedPlatform,
18534            Reason::RunningExecutableUnreadable,
18535            Reason::SpawnedPathUnreadable,
18536            Reason::HashFailed,
18537            Reason::ProcessIdentityUnconfirmed,
18538            Reason::Unknown("future_probe_reason".to_string()),
18539        ] {
18540            let image = subc_control::RunningImageAgreement::Unavailable {
18541                reason: reason.clone(),
18542            };
18543            let verdict = reload_verdict(
18544                std::path::Path::new("/bin/same"),
18545                Some(std::path::Path::new("/bin/same")),
18546                image.clone(),
18547            );
18548            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18549            assert_eq!(verdict.image, image, "{reason:?}");
18550        }
18551    }
18552
18553    #[tokio::test]
18554    async fn malformed_control_bodies_return_invalid_control_body() {
18555        let handler = ControlHandler::default();
18556        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18557
18558        for (corr, body) in [
18559            (56, br#"{"route_channel":1}"#.as_slice()),
18560            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18561            (
18562                58,
18563                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18564            ),
18565        ] {
18566            let request = Frame::build(
18567                FrameType::Request,
18568                control_flags(),
18569                0,
18570                0,
18571                corr,
18572                body.to_vec(),
18573            )
18574            .unwrap();
18575            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18576
18577            assert_eq!(response.len(), 1);
18578            assert_eq!(response[0].header.ty, FrameType::Error);
18579            assert_eq!(response[0].header.corr, corr);
18580            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18581        }
18582    }
18583
18584    #[tokio::test]
18585    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18586        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18587        let registry = Arc::new(Registry::default());
18588        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18589        let router = Router::with_control_handler(Arc::clone(&control));
18590        let connection = router.begin_connection();
18591        let (ctx, mut rx) = route_ctx(connection.id());
18592
18593        router
18594            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18595            .await
18596            .unwrap();
18597        let response = rx.recv().await.unwrap();
18598        let ack = parse_ack(&response);
18599        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18600        let channel = 1;
18601
18602        let goodbye =
18603            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18604        router.route_for_connection(&ctx, goodbye).await.unwrap();
18605        assert!(rx.try_recv().is_err());
18606        assert!(registry.get_module("aft").unwrap().is_none());
18607
18608        router
18609            .route_for_connection(&ctx, channel_request(channel, 13))
18610            .await
18611            .unwrap();
18612        let error_frame = rx.recv().await.unwrap();
18613        assert_eq!(error_frame.header.ty, FrameType::Error);
18614        assert_eq!(error_frame.header.channel, channel);
18615        let captured = crate::router::test_log::captured_logs(&logs);
18616        assert_eq!(
18617            captured
18618                .lines()
18619                .filter(|line| {
18620                    line.contains("module_id=aft")
18621                        && line.contains("reason=explicit_goodbye")
18622                        && line.contains("module registration ended")
18623                })
18624                .count(),
18625            1,
18626            "unexpected GOODBYE registry log: {captured}"
18627        );
18628    }
18629
18630    #[tokio::test]
18631    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18632        let registry = Arc::new(Registry::default());
18633        let handler = ControlHandler::new(registry).with_capability_config(
18634            [("prov".to_string(), true), ("cons".to_string(), true)],
18635            BTreeMap::new(),
18636        );
18637        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18638        register_capability_manifest(
18639            &handler,
18640            &provider_ctx,
18641            &mut provider_rx,
18642            capability_manifest("prov", &["thing/v1"], &[]),
18643            1,
18644        )
18645        .await;
18646        let mut consumer = capability_manifest("cons", &[], &[]);
18647        consumer.capabilities.as_mut().unwrap().requires.push(
18648            subc_protocol::manifest::CapabilityRequirement {
18649                capability: "thing/v1".to_string(),
18650                need: subc_protocol::manifest::CapabilityNeed::Required,
18651            },
18652        );
18653        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18654        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18655        assert_eq!(
18656            handler.capability_evaluator.verdict("cons", "thing/v1"),
18657            Some(CapabilityVerdict::Provided)
18658        );
18659        let (mut client_rx, _) = open_route_for_capability_test(
18660            &handler,
18661            &provider_ctx,
18662            &mut provider_rx,
18663            703,
18664            3,
18665            "prov",
18666            None,
18667        )
18668        .await;
18669        let goodbye =
18670            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18671        handler
18672            .handle_control_frame(&provider_ctx, goodbye)
18673            .await
18674            .unwrap();
18675        assert_eq!(
18676            handler.capability_evaluator.verdict("cons", "thing/v1"),
18677            Some(CapabilityVerdict::NeverProvided)
18678        );
18679        let closed = client_rx
18680            .try_recv()
18681            .expect("GOODBYE pushes route.closed before route GOODBYE");
18682        assert!(
18683            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18684            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18685        );
18686        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18687        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18688    }
18689
18690    struct RouteClosedFixture {
18691        handler: ControlHandler,
18692        #[cfg(unix)]
18693        supervisor: Supervisor,
18694        module_ctx: RouteCtx,
18695        #[cfg(unix)]
18696        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18697        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18698        route: Arc<crate::forwarding::RouteBinding>,
18699    }
18700
18701    async fn route_closed_fixture() -> RouteClosedFixture {
18702        let registry = Arc::new(Registry::default());
18703        let handler = ControlHandler::new(Arc::clone(&registry));
18704        #[cfg(unix)]
18705        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18706            .with_forwarding(Arc::clone(&handler.forwarding));
18707        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18708        register_capability_manifest(
18709            &handler,
18710            &module_ctx,
18711            &mut module_rx,
18712            capability_manifest("prov", &[], &[]),
18713            1,
18714        )
18715        .await;
18716        let (client_rx, bind) = open_route_for_capability_test(
18717            &handler,
18718            &module_ctx,
18719            &mut module_rx,
18720            702,
18721            2,
18722            "prov",
18723            None,
18724        )
18725        .await;
18726        let ModuleControlRequest::RouteBind {
18727            route_channel: channel,
18728            epoch: route_epoch,
18729            ..
18730        } = bind
18731        else {
18732            panic!("expected route.bind");
18733        };
18734        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18735            handler
18736                .forwarding
18737                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18738                .unwrap()
18739        else {
18740            panic!("the acknowledged route must be bound");
18741        };
18742        RouteClosedFixture {
18743            handler,
18744            #[cfg(unix)]
18745            supervisor,
18746            module_ctx,
18747            #[cfg(unix)]
18748            module_rx,
18749            client_rx,
18750            route,
18751        }
18752    }
18753
18754    impl RouteClosedFixture {
18755        #[cfg(unix)]
18756        async fn cut(&mut self) {
18757            let notices = async {
18758                let mut draining = self.module_rx.recv().await.unwrap();
18759                assert!(matches!(
18760                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18761                        &draining.body
18762                    )
18763                    .unwrap(),
18764                    subc_protocol::session::ModuleControlCommand::Draining {
18765                        reason: RouteCloseReason::Disable,
18766                        ..
18767                    }
18768                ));
18769                draining.flushed.take().unwrap().send(()).unwrap();
18770                let mut closing = self.client_rx.recv().await.unwrap();
18771                assert!(matches!(
18772                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18773                    ClientControlPush::RouteClosing {
18774                        reason: RouteCloseReason::Restart,
18775                        ..
18776                    }
18777                ));
18778                closing.flushed.take().unwrap().send(()).unwrap();
18779            };
18780            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18781            result.unwrap();
18782        }
18783
18784        fn disconnect(&mut self) -> ClientControlPush {
18785            self.handler
18786                .cleanup_connection(self.module_ctx.connection_id)
18787                .unwrap();
18788            let closed = self.client_rx.try_recv().unwrap();
18789            assert_eq!(closed.header.ty, FrameType::Push);
18790            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18791            assert!(matches!(
18792                &push,
18793                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18794                    if channels == &[self.route.client_channel]
18795            ));
18796            assert_eq!(
18797                self.client_rx.try_recv().unwrap().header.ty,
18798                FrameType::Goodbye
18799            );
18800            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18801            push
18802        }
18803    }
18804
18805    #[cfg(unix)]
18806    #[tokio::test(start_paused = true)]
18807    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18808        let mut fixture = route_closed_fixture().await;
18809        fixture.cut().await;
18810        assert!(matches!(
18811            fixture.disconnect(),
18812            ClientControlPush::RouteClosed {
18813                reason: RouteCloseReason::Restart,
18814                drained: true,
18815                ..
18816            }
18817        ));
18818    }
18819
18820    #[cfg(unix)]
18821    #[tokio::test(start_paused = true)]
18822    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18823        let mut fixture = route_closed_fixture().await;
18824        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18825        let started = tokio::time::Instant::now();
18826        fixture.cut().await;
18827        assert!(started.elapsed() >= Duration::from_secs(2));
18828        assert_eq!(fixture.route.flow.in_flight(), 1);
18829        assert!(matches!(
18830            fixture.disconnect(),
18831            ClientControlPush::RouteClosed {
18832                reason: RouteCloseReason::Restart,
18833                drained: false,
18834                ..
18835            }
18836        ));
18837    }
18838
18839    #[tokio::test]
18840    async fn module_connection_crash_reports_crash_and_not_drained() {
18841        let mut fixture = route_closed_fixture().await;
18842        // The server calls cleanup_connection on module EOF. Without a planned
18843        // daemon shutdown, that disconnect must remain a crash with no prior
18844        // route.closing notice, even when the route has no in-flight calls.
18845        assert!(matches!(
18846            fixture.disconnect(),
18847            ClientControlPush::RouteClosed {
18848                reason: RouteCloseReason::Crash,
18849                drained: false,
18850                ..
18851            }
18852        ));
18853    }
18854
18855    #[tokio::test]
18856    async fn dropping_router_connection_releases_registration() {
18857        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18858        let registry = Arc::new(Registry::default());
18859        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18860        let router = Router::with_control_handler(Arc::clone(&control));
18861        let connection = router.begin_connection();
18862        let connection_id = connection.id();
18863        let (ctx, mut rx) = route_ctx(connection_id);
18864
18865        router
18866            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18867            .await
18868            .unwrap();
18869        let response = rx.recv().await.unwrap();
18870        let ack = parse_ack(&response);
18871        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18872        assert!(registry.get_module("aft").unwrap().is_some());
18873
18874        drop(connection);
18875
18876        assert!(registry.get_module("aft").unwrap().is_none());
18877        assert_eq!(registry.active_registration_count().unwrap(), 0);
18878
18879        control
18880            .cleanup_connection(ConnectionId::new(u64::MAX))
18881            .unwrap();
18882        let captured = crate::router::test_log::captured_logs(&logs);
18883        println!("captured registry lifecycle logs:\n{captured}");
18884        let events: Vec<_> = captured
18885            .lines()
18886            .filter(|line| {
18887                line.contains("module registered module_id=aft ")
18888                    || line.contains("module registration ended")
18889            })
18890            .collect();
18891        assert_eq!(
18892            events.len(),
18893            2,
18894            "unexpected registry lifecycle logs: {captured}"
18895        );
18896        assert!(events[0].contains("module registered module_id=aft "));
18897        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18898        assert!(events[1].contains(&format!(
18899            "module_id=aft connection_id={}",
18900            connection_id.get()
18901        )));
18902        assert!(events[1].contains("reason=connection_closed"));
18903        assert!(events[1].contains("module registration ended"));
18904        assert_eq!(
18905            captured
18906                .lines()
18907                .filter(|line| line.contains("module registered module_id=aft "))
18908                .count(),
18909            1,
18910            "legacy registration admission line must appear once: {captured}"
18911        );
18912    }
18913
18914    #[tokio::test]
18915    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18916        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18917        let registry = Arc::new(Registry::default());
18918        let control = ControlHandler::new(Arc::clone(&registry));
18919        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18920        hello_via_sink(
18921            &control,
18922            &ctx,
18923            &mut rx,
18924            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18925        )
18926        .await;
18927
18928        let captured = crate::router::test_log::captured_logs(&logs);
18929        let admissions: Vec<_> = captured
18930            .lines()
18931            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18932            .collect();
18933        assert_eq!(
18934            admissions.len(),
18935            1,
18936            "legacy admission line must remain exactly once: {captured}"
18937        );
18938        assert!(admissions[0].contains("routable_provider=true"));
18939        assert!(admissions[0].contains("connection_id=777"));
18940    }
18941
18942    fn capability_manifest(
18943        module_id: &str,
18944        provides: &[&str],
18945        must_never_reach: &[&str],
18946    ) -> ModuleManifest {
18947        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18948        manifest.capabilities = Some(CapabilityDeclarations {
18949            provides: provides
18950                .iter()
18951                .map(|capability| (*capability).to_string())
18952                .collect(),
18953            requires: Vec::new(),
18954            must_never_reach: must_never_reach
18955                .iter()
18956                .map(|capability| (*capability).to_string())
18957                .collect(),
18958        });
18959        manifest
18960    }
18961
18962    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18963        Frame::build(
18964            FrameType::Hello,
18965            control_flags(),
18966            0,
18967            0,
18968            corr,
18969            serde_json::to_vec(&ModuleHelloBody {
18970                protocol_ver: manifest.protocol_ver,
18971                manifest,
18972                control_ops: None,
18973                launch_nonce: None,
18974            })
18975            .expect("capability test HELLO serializes"),
18976        )
18977        .expect("capability test HELLO frame builds")
18978    }
18979
18980    fn catalog_update_with_capabilities_frame(
18981        corr: u64,
18982        capabilities: CapabilityDeclarations,
18983    ) -> Frame {
18984        Frame::build(
18985            FrameType::Request,
18986            control_flags(),
18987            0,
18988            0,
18989            corr,
18990            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18991                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18992                capabilities: Some(capabilities),
18993                ready: None,
18994            })
18995            .expect("capability catalog.update serializes"),
18996        )
18997        .expect("capability catalog.update frame builds")
18998    }
18999
19000    async fn register_capability_manifest(
19001        handler: &ControlHandler,
19002        ctx: &RouteCtx,
19003        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
19004        manifest: ModuleManifest,
19005        corr: u64,
19006    ) {
19007        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
19008    }
19009
19010    async fn open_route_for_capability_test(
19011        handler: &ControlHandler,
19012        target_ctx: &RouteCtx,
19013        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
19014        client_connection_id: u64,
19015        corr: u64,
19016        target_module_id: &str,
19017        consumer_identity: Option<ConsumerIdentity>,
19018    ) -> (
19019        mpsc::Receiver<crate::router::OutboundFrame>,
19020        ModuleControlRequest,
19021    ) {
19022        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
19023        let route_handler = handler.clone();
19024        let target_module_id = target_module_id.to_string();
19025        let route_task = tokio::spawn(async move {
19026            route_handler
19027                .handle_control_frame(
19028                    &client_ctx,
19029                    route_open_frame_with_admission_facts(
19030                        corr,
19031                        &target_module_id,
19032                        unique_project_root("admission-facts"),
19033                        consumer_identity,
19034                        None,
19035                    ),
19036                )
19037                .await
19038                .expect("capability test route.open succeeds")
19039        });
19040        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
19041            .await
19042            .expect("capability test route.open must reach route.bind")
19043            .expect("target control receiver stays open");
19044        let bind_request: ModuleControlRequest =
19045            serde_json::from_slice(&bind.body).expect("route.bind decodes");
19046        handler
19047            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
19048            .await
19049            .expect("capability test route.bind ACK succeeds");
19050        assert!(route_task.await.expect("route.open task joins").is_empty());
19051        let opened = client_rx
19052            .recv()
19053            .await
19054            .expect("successful route.open publishes a response");
19055        assert!(matches!(
19056            serde_json::from_slice::<ClientControlResponse>(&opened.body),
19057            Ok(ClientControlResponse::RouteOpen { .. })
19058        ));
19059        (client_rx, bind_request)
19060    }
19061
19062    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
19063        assert_eq!(frame.header.ty, FrameType::Push);
19064        assert_eq!(frame.header.channel, 0);
19065        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
19066            .expect("route.closed control push decodes");
19067        let ClientControlPush::RouteClosed { channels, .. } = &push else {
19068            panic!("expected route.closed");
19069        };
19070        assert_eq!(channels.len(), 1, "exactly one violating route closed");
19071        let closed_channel = channels[0];
19072        let channels = channels.clone();
19073        assert_eq!(
19074            push,
19075            ClientControlPush::RouteClosed {
19076                module_id: target_module_id.to_string(),
19077                channels,
19078                reason: RouteCloseReason::CapabilityDenied,
19079                drained: false,
19080                abandoned: 0,
19081                excluded_subscriptions: 0,
19082                terminal: Some(false),
19083            }
19084        );
19085        closed_channel
19086    }
19087
19088    #[tokio::test]
19089    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
19090        let registry = Arc::new(Registry::default());
19091        let forwarding = Arc::new(ForwardingTable::default());
19092        let supervisor = SupervisorHandle::new();
19093        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19094        let handler =
19095            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19096                .with_supervisor(supervisor);
19097        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
19098        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
19099        register_capability_manifest(
19100            &handler,
19101            &target_ctx,
19102            &mut target_rx,
19103            capability_manifest("target", &["credentials-provider/v1"], &[]),
19104            1,
19105        )
19106        .await;
19107        register_capability_manifest(
19108            &handler,
19109            &opener_ctx,
19110            &mut opener_rx,
19111            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19112            2,
19113        )
19114        .await;
19115
19116        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
19117        let replies = handler
19118            .handle_control_frame(
19119                &client_ctx,
19120                route_open_frame_with_admission_facts(
19121                    3,
19122                    "target",
19123                    unique_project_root("admission-facts"),
19124                    Some(ConsumerIdentity {
19125                        module_id: "opener".to_string(),
19126                        launch_nonce: "opener-nonce".to_string(),
19127                    }),
19128                    None,
19129                ),
19130            )
19131            .await
19132            .expect("denied route.open returns a typed frame");
19133        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19134        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19135        assert!(
19136            target_rx.try_recv().is_err(),
19137            "forbidden route.open must not relay route.bind"
19138        );
19139    }
19140
19141    #[tokio::test]
19142    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19143        let registry = Arc::new(Registry::default());
19144        let forwarding = Arc::new(ForwardingTable::default());
19145        let supervisor = SupervisorHandle::new();
19146        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19147        let handler =
19148            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19149                .with_supervisor(supervisor);
19150        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19151        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19152        register_capability_manifest(
19153            &handler,
19154            &target_ctx,
19155            &mut target_rx,
19156            capability_manifest("target", &["credentials-provider/v1"], &[]),
19157            1,
19158        )
19159        .await;
19160        register_capability_manifest(
19161            &handler,
19162            &old_opener_ctx,
19163            &mut old_opener_rx,
19164            capability_manifest("opener", &[], &[]),
19165            2,
19166        )
19167        .await;
19168        let (mut client_rx, _) = open_route_for_capability_test(
19169            &handler,
19170            &target_ctx,
19171            &mut target_rx,
19172            712,
19173            3,
19174            "target",
19175            Some(ConsumerIdentity {
19176                module_id: "opener".to_string(),
19177                launch_nonce: "opener-nonce".to_string(),
19178            }),
19179        )
19180        .await;
19181        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19182
19183        handler
19184            .cleanup_connection(old_opener_ctx.connection_id)
19185            .expect("old opener registration cleans up");
19186        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19187        register_capability_manifest(
19188            &handler,
19189            &new_opener_ctx,
19190            &mut new_opener_rx,
19191            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19192            4,
19193        )
19194        .await;
19195
19196        let closed_channel = assert_capability_denied_push(
19197            client_rx
19198                .try_recv()
19199                .expect("HELLO deny addition must emit route.closed")
19200                .frame,
19201            "target",
19202        );
19203        let goodbye = client_rx
19204            .try_recv()
19205            .expect("HELLO deny addition must send the client a route GOODBYE")
19206            .frame;
19207        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19208        assert_eq!(goodbye.header.channel, closed_channel);
19209        assert_ne!(goodbye.header.channel, 0);
19210        assert_ne!(goodbye.header.epoch, 0);
19211        assert!(client_rx.try_recv().is_err());
19212        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19213        assert!(matches!(
19214            target_rx.try_recv(),
19215            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19216        ));
19217    }
19218
19219    #[tokio::test]
19220    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19221        let registry = Arc::new(Registry::default());
19222        let forwarding = Arc::new(ForwardingTable::default());
19223        let supervisor = SupervisorHandle::new();
19224        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19225        let handler =
19226            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19227                .with_supervisor(supervisor);
19228        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19229        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19230        register_capability_manifest(
19231            &handler,
19232            &target_ctx,
19233            &mut target_rx,
19234            capability_manifest("target", &[], &[]),
19235            1,
19236        )
19237        .await;
19238        register_capability_manifest(
19239            &handler,
19240            &opener_ctx,
19241            &mut opener_rx,
19242            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19243            2,
19244        )
19245        .await;
19246        let (mut client_rx, _) = open_route_for_capability_test(
19247            &handler,
19248            &target_ctx,
19249            &mut target_rx,
19250            722,
19251            3,
19252            "target",
19253            Some(ConsumerIdentity {
19254                module_id: "opener".to_string(),
19255                launch_nonce: "opener-nonce".to_string(),
19256            }),
19257        )
19258        .await;
19259        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19260
19261        let replies = handler
19262            .handle_control_frame(
19263                &target_ctx,
19264                catalog_update_with_capabilities_frame(
19265                    4,
19266                    CapabilityDeclarations {
19267                        provides: vec!["credentials-provider/v1".to_string()],
19268                        requires: Vec::new(),
19269                        must_never_reach: Vec::new(),
19270                    },
19271                ),
19272            )
19273            .await
19274            .expect("claim catalog.update succeeds");
19275        assert!(matches!(
19276            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19277            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19278        ));
19279        let closed_channel = assert_capability_denied_push(
19280            client_rx
19281                .try_recv()
19282                .expect("claim addition must emit route.closed")
19283                .frame,
19284            "target",
19285        );
19286        let goodbye = client_rx
19287            .try_recv()
19288            .expect("claim addition must send the client a route GOODBYE")
19289            .frame;
19290        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19291        assert_eq!(goodbye.header.channel, closed_channel);
19292        assert_ne!(goodbye.header.channel, 0);
19293        assert_ne!(goodbye.header.epoch, 0);
19294        assert!(client_rx.try_recv().is_err());
19295        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19296        assert!(matches!(
19297            target_rx.try_recv(),
19298            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19299        ));
19300    }
19301
19302    #[tokio::test]
19303    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19304        let registry = Arc::new(Registry::default());
19305        let forwarding = Arc::new(ForwardingTable::default());
19306        let supervisor = SupervisorHandle::new();
19307        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19308        let handler =
19309            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19310                .with_supervisor(supervisor);
19311        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19312        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19313        register_capability_manifest(
19314            &handler,
19315            &target_ctx,
19316            &mut target_rx,
19317            capability_manifest("target", &["credentials-provider/v1"], &[]),
19318            1,
19319        )
19320        .await;
19321        register_capability_manifest(
19322            &handler,
19323            &opener_ctx,
19324            &mut opener_rx,
19325            capability_manifest("opener", &[], &[]),
19326            2,
19327        )
19328        .await;
19329        let (mut client_rx, _) = open_route_for_capability_test(
19330            &handler,
19331            &target_ctx,
19332            &mut target_rx,
19333            732,
19334            3,
19335            "target",
19336            Some(ConsumerIdentity {
19337                module_id: "opener".to_string(),
19338                launch_nonce: "opener-nonce".to_string(),
19339            }),
19340        )
19341        .await;
19342        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19343
19344        handler
19345            .handle_control_frame(
19346                &target_ctx,
19347                catalog_update_with_capabilities_frame(
19348                    4,
19349                    CapabilityDeclarations {
19350                        provides: Vec::new(),
19351                        requires: Vec::new(),
19352                        must_never_reach: Vec::new(),
19353                    },
19354                ),
19355            )
19356            .await
19357            .expect("claim removal catalog.update succeeds");
19358        assert_eq!(
19359            forwarding.active_binding_count().unwrap(),
19360            1,
19361            "removing an attested target claim must leave the route census unchanged"
19362        );
19363        assert!(
19364            client_rx.try_recv().is_err(),
19365            "claim removal must not emit route.closed or a client route GOODBYE"
19366        );
19367        assert!(
19368            target_rx.try_recv().is_err(),
19369            "claim removal must not send the target a route GOODBYE"
19370        );
19371    }
19372
19373    /// A direct client may open a route to a denied capability provider; this
19374    /// policy applies only to attested supervised module origins, not to direct clients.
19375    #[tokio::test]
19376    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19377        let registry = Arc::new(Registry::default());
19378        let forwarding = Arc::new(ForwardingTable::default());
19379        let supervisor = SupervisorHandle::new();
19380        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19381        let handler =
19382            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19383                .with_supervisor(supervisor);
19384        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19385        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19386        register_capability_manifest(
19387            &handler,
19388            &target_ctx,
19389            &mut target_rx,
19390            capability_manifest("target", &["credentials-provider/v1"], &[]),
19391            1,
19392        )
19393        .await;
19394        register_capability_manifest(
19395            &handler,
19396            &opener_ctx,
19397            &mut opener_rx,
19398            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19399            2,
19400        )
19401        .await;
19402
19403        let (_client_rx, bind) = open_route_for_capability_test(
19404            &handler,
19405            &target_ctx,
19406            &mut target_rx,
19407            742,
19408            3,
19409            "target",
19410            None,
19411        )
19412        .await;
19413        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19414            panic!("direct scope-honesty route must bind");
19415        };
19416        assert_eq!(principal, Some(Principal::Direct));
19417        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19418    }
19419
19420    /// A module that denies a capability receives no self-route exemption when it
19421    /// also attestedly provides that capability.
19422    #[tokio::test]
19423    async fn must_never_reach_self_route_is_capability_forbidden() {
19424        let registry = Arc::new(Registry::default());
19425        let forwarding = Arc::new(ForwardingTable::default());
19426        let supervisor = SupervisorHandle::new();
19427        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19428        let handler =
19429            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19430                .with_supervisor(supervisor);
19431        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19432        register_capability_manifest(
19433            &handler,
19434            &self_ctx,
19435            &mut self_rx,
19436            capability_manifest(
19437                "self-provider",
19438                &["credentials-provider/v1"],
19439                &["credentials-provider/v1"],
19440            ),
19441            1,
19442        )
19443        .await;
19444
19445        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19446        let replies = handler
19447            .handle_control_frame(
19448                &client_ctx,
19449                route_open_frame_with_admission_facts(
19450                    2,
19451                    "self-provider",
19452                    unique_project_root("admission-facts"),
19453                    Some(ConsumerIdentity {
19454                        module_id: "self-provider".to_string(),
19455                        launch_nonce: "self-nonce".to_string(),
19456                    }),
19457                    None,
19458                ),
19459            )
19460            .await
19461            .expect("self-route refusal returns a typed frame");
19462        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19463        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19464        assert!(
19465            self_rx.try_recv().is_err(),
19466            "self denial must not relay route.bind"
19467        );
19468    }
19469
19470    #[test]
19471    fn unsupported_channel_zero_frame_returns_error() {
19472        let handler = ControlHandler::default();
19473        let request = Frame::build(
19474            FrameType::Request,
19475            control_flags(),
19476            0,
19477            0,
19478            21,
19479            b"opaque".to_vec(),
19480        )
19481        .unwrap();
19482
19483        let response = handler
19484            .handle_control(ConnectionId::new(1), request)
19485            .unwrap();
19486
19487        assert_eq!(response[0].header.ty, FrameType::Error);
19488        assert_eq!(
19489            parse_error(&response[0])["code"],
19490            "unsupported_control_frame"
19491        );
19492    }
19493
19494    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19495    /// a swap is not wired yet, so the candidate is registered here directly
19496    /// into the registry and forwarding candidate slots, the way the swap's
19497    /// HELLO admission will.
19498    mod swap {
19499        use super::*;
19500
19501        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19502        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19503
19504        struct Swap {
19505            registry: Arc<Registry>,
19506            forwarding: Arc<ForwardingTable>,
19507            handler: ControlHandler,
19508            incumbent_ctx: RouteCtx,
19509            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19510            candidate_ctx: RouteCtx,
19511            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19512        }
19513
19514        async fn swap_with_incumbent() -> Swap {
19515            let registry = Arc::new(Registry::default());
19516            let forwarding = Arc::new(ForwardingTable::default());
19517            let handler =
19518                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19519            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19520            hello_via_sink(
19521                &handler,
19522                &incumbent_ctx,
19523                &mut incumbent_rx,
19524                hello_frame("aft", PROTOCOL_VERSION, 7),
19525            )
19526            .await;
19527            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19528            Swap {
19529                registry,
19530                forwarding,
19531                handler,
19532                incumbent_ctx,
19533                incumbent_rx,
19534                candidate_ctx,
19535                candidate_rx,
19536            }
19537        }
19538
19539        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19540            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19541            candidate_manifest.ready = ready;
19542            let registration = swap
19543                .registry
19544                .register_candidate_with_control_ops(
19545                    candidate_manifest,
19546                    PROTOCOL_VERSION,
19547                    CANDIDATE,
19548                    module_baseline_control_ops(),
19549                )
19550                .unwrap();
19551            swap.forwarding
19552                .register_candidate_module_connection(
19553                    CANDIDATE,
19554                    "aft".to_string(),
19555                    PROTOCOL_VERSION,
19556                    manifest_concurrency(&registration.manifest),
19557                    swap.candidate_ctx.egress.clone(),
19558                )
19559                .unwrap();
19560        }
19561
19562        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19563            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19564            swap.registry.promote_candidate("aft").unwrap().unwrap();
19565            cutover.incumbent.unwrap()
19566        }
19567
19568        /// A swap candidate's HELLO reserves its candidate registry entry
19569        /// before installing its candidate forwarding endpoint. The swap
19570        /// supervisor promotes a ready candidate as soon as it reads it as
19571        /// registered, and promotion cuts forwarding over to the candidate
19572        /// endpoint, so the lookup the supervisor reads
19573        /// (`Registry::published_registration`) must not return the candidate
19574        /// until that endpoint exists. Otherwise the cutover finds no candidate
19575        /// endpoint and the swap fails as if the candidate had disconnected.
19576        #[tokio::test]
19577        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19578            let mut swap = swap_with_incumbent().await;
19579            let hold = Arc::new(std::sync::Barrier::new(2));
19580            let handler = swap
19581                .handler
19582                .clone()
19583                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19584            handler
19585                .supervisor
19586                .open_swap("aft", "candidate-nonce".to_string());
19587            let hello = {
19588                let handler = handler.clone();
19589                let candidate_ctx = swap.candidate_ctx.clone();
19590                std::thread::spawn(move || {
19591                    handler
19592                        .handle_hello(
19593                            candidate_ctx.connection_id,
19594                            Some(candidate_ctx.egress.clone()),
19595                            hello_frame_with_nonce(
19596                                "aft",
19597                                PROTOCOL_VERSION,
19598                                8,
19599                                Some("candidate-nonce"),
19600                            ),
19601                        )
19602                        .unwrap()
19603                })
19604            };
19605
19606            hold.wait();
19607            // Parked: the candidate slot is claimed but not published, and
19608            // forwarding has no candidate endpoint.
19609            assert!(swap
19610                .registry
19611                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19612                .unwrap()
19613                .is_some());
19614            assert!(swap
19615                .registry
19616                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19617                .unwrap()
19618                .is_none());
19619            assert!(swap
19620                .forwarding
19621                .module_endpoint_for_connection(CANDIDATE)
19622                .unwrap()
19623                .is_none());
19624
19625            hold.wait();
19626            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19627            assert_eq!(
19628                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19629                FrameType::HelloAck
19630            );
19631            let published = swap
19632                .registry
19633                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19634                .unwrap()
19635                .expect("candidate is published once its HELLO completes");
19636            assert_eq!(published.connection_id, CANDIDATE);
19637            assert!(swap
19638                .forwarding
19639                .module_endpoint_for_connection(CANDIDATE)
19640                .unwrap()
19641                .is_some());
19642        }
19643
19644        #[tokio::test]
19645        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19646            let mut swap = swap_with_incumbent().await;
19647            let hold = Arc::new(std::sync::Barrier::new(2));
19648            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19649            swap.handler
19650                .supervisor
19651                .open_swap("aft", "candidate-nonce".to_string());
19652            let hello = {
19653                let handler = swap.handler.clone();
19654                let candidate_ctx = swap.candidate_ctx.clone();
19655                std::thread::spawn(move || {
19656                    handler
19657                        .handle_hello(
19658                            CANDIDATE,
19659                            Some(candidate_ctx.egress),
19660                            hello_frame_with_nonce(
19661                                "aft",
19662                                PROTOCOL_VERSION,
19663                                8,
19664                                Some("candidate-nonce"),
19665                            ),
19666                        )
19667                        .unwrap()
19668                })
19669            };
19670            hold.wait();
19671            assert_eq!(
19672                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19673                FrameType::HelloAck
19674            );
19675            let reader_registry = Arc::clone(&swap.registry);
19676            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19677                reader_registry
19678                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19679                    .unwrap()
19680            });
19681            assert!(hello.join().unwrap().is_empty());
19682            assert_eq!(
19683                published
19684                    .expect("ACK makes candidate publication visible")
19685                    .connection_id,
19686                CANDIDATE
19687            );
19688            assert_eq!(
19689                swap.registry.generation().unwrap(),
19690                1,
19691                "candidate is not a second catalog entry"
19692            );
19693        }
19694
19695        #[tokio::test]
19696        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19697            let mut swap = swap_with_incumbent().await;
19698            let hold = Arc::new(std::sync::Barrier::new(2));
19699            let handler = swap
19700                .handler
19701                .clone()
19702                .with_hello_registry_to_forwarding_hold(hold.clone());
19703            handler
19704                .supervisor
19705                .open_swap("aft", "candidate-nonce".into());
19706            let hello = {
19707                let handler = handler.clone();
19708                let ctx = swap.candidate_ctx.clone();
19709                std::thread::spawn(move || {
19710                    handler
19711                        .handle_hello(
19712                            CANDIDATE,
19713                            Some(ctx.egress),
19714                            hello_frame_with_nonce(
19715                                "aft",
19716                                PROTOCOL_VERSION,
19717                                8,
19718                                Some("candidate-nonce"),
19719                            ),
19720                        )
19721                        .unwrap()
19722                })
19723            };
19724            hold.wait();
19725            assert_eq!(
19726                swap.registry
19727                    .deregister_connection(CANDIDATE)
19728                    .unwrap()
19729                    .len(),
19730                1
19731            );
19732            hold.wait();
19733            assert!(hello.join().unwrap().is_empty());
19734            assert_eq!(
19735                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19736                FrameType::HelloAck
19737            );
19738            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19739            assert_eq!(
19740                handler
19741                    .supervisor
19742                    .swap_hello_admission("aft", Some("candidate-nonce")),
19743                SwapHelloAdmission::Candidate,
19744                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19745            );
19746            handler.supervisor.close_swap("aft");
19747        }
19748
19749        fn keyed_total(counters: &Value, key: &str) -> u64 {
19750            counters[key]
19751                .as_object()
19752                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19753                .unwrap_or(0)
19754        }
19755
19756        #[tokio::test]
19757        async fn replacement_logs_old_end_and_new_admission_once() {
19758            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19759            let mut swap = swap_with_incumbent().await;
19760            swap.handler
19761                .supervisor
19762                .open_swap("aft", "candidate-nonce".to_string());
19763            hello_via_sink(
19764                &swap.handler,
19765                &swap.candidate_ctx,
19766                &mut swap.candidate_rx,
19767                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19768            )
19769            .await;
19770            cutover(&swap);
19771            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19772
19773            let captured = crate::router::test_log::captured_logs(&logs);
19774            println!("captured replacement registry logs:\n{captured}");
19775            let new_admissions: Vec<_> = captured
19776                .lines()
19777                .filter(|line| {
19778                    line.contains("connection_id=40")
19779                        && line.contains("swap candidate registered; not routable until cutover")
19780                })
19781                .collect();
19782            assert_eq!(
19783                new_admissions.len(),
19784                1,
19785                "unexpected admission logs: {captured}"
19786            );
19787            assert!(new_admissions[0].contains("module_id=aft"));
19788            assert!(new_admissions[0].contains("connection_id=40"));
19789            assert!(
19790                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19791            );
19792            assert!(new_admissions[0].contains("ready=true"));
19793
19794            let old_admissions: Vec<_> = captured
19795                .lines()
19796                .filter(|line| {
19797                    line.contains("module registered module_id=aft ")
19798                        && line.contains("connection_id=30")
19799                })
19800                .collect();
19801            assert_eq!(
19802                old_admissions.len(),
19803                1,
19804                "unexpected incumbent admission: {captured}"
19805            );
19806
19807            let old_ends: Vec<_> = captured
19808                .lines()
19809                .filter(|line| {
19810                    line.contains("connection_id=30") && line.contains("module registration ended")
19811                })
19812                .collect();
19813            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19814            assert!(old_ends[0].contains("module_id=aft"));
19815            assert!(old_ends[0].contains("connection_id=30"));
19816            assert!(old_ends[0].contains("reason=replaced"));
19817            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19818            assert_eq!(
19819                captured
19820                    .lines()
19821                    .filter(|line| line.contains("module registration promoted"))
19822                    .count(),
19823                1,
19824                "unexpected promotion logs: {captured}"
19825            );
19826        }
19827
19828        /// An ack from the incumbent for a bind it was sent before cutover,
19829        /// arriving before the incumbent is drained. The incumbent is the live
19830        /// connection carrying every other client's routes, so the ack must
19831        /// not end it: the waiting client is told to retry, the reservation is
19832        /// given back, and the incumbent is told to drop just that binding.
19833        #[tokio::test]
19834        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19835            let mut swap = swap_with_incumbent().await;
19836            let handler = swap.handler.clone();
19837
19838            // A co-tenant route, bound on the incumbent before the swap.
19839            let cotenant = ConnectionId::new(31);
19840            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19841            let (cotenant_task, cotenant_bind) = relay_route_open(
19842                &handler,
19843                cotenant,
19844                &cotenant_ctx.egress,
19845                &mut swap.incumbent_rx,
19846                100,
19847                "aft",
19848                "swap-cotenant",
19849            )
19850            .await;
19851            handler
19852                .handle_control_frame(
19853                    &swap.incumbent_ctx,
19854                    route_bind_ack(cotenant_bind.header.corr),
19855                )
19856                .await
19857                .unwrap();
19858            assert!(cotenant_task.await.unwrap().is_empty());
19859            let (cotenant_channel, cotenant_epoch) =
19860                published_route(&cotenant_rx.recv().await.unwrap());
19861
19862            // A second route.open, relayed to the incumbent and not yet acked.
19863            let caller = ConnectionId::new(32);
19864            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19865            let (caller_task, caller_bind) = relay_route_open(
19866                &handler,
19867                caller,
19868                &caller_ctx.egress,
19869                &mut swap.incumbent_rx,
19870                101,
19871                "aft",
19872                "swap-caller",
19873            )
19874            .await;
19875            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19876
19877            register_candidate(&swap, None);
19878            cutover(&swap);
19879
19880            // The incumbent acks after promotion and before any drain.
19881            let ack = handler
19882                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19883                .await;
19884            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19885            if module_loop_error.is_some() {
19886                // What the connection loop does with an untranslated router
19887                // error: end the connection, releasing every route on it.
19888                handler.cleanup_connection(INCUMBENT).unwrap();
19889            }
19890
19891            // 1. The incumbent's other routes survive.
19892            assert!(
19893                cotenant_rx.try_recv().is_err(),
19894                "the co-tenant route on the incumbent was torn down by one late ack: \
19895                 {module_loop_error:?}"
19896            );
19897            assert!(matches!(
19898                swap.forwarding
19899                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19900                    .unwrap(),
19901                DataRoute::Client(DataRouteState::Bound(_))
19902            ));
19903            assert_eq!(module_loop_error, None);
19904            assert!(swap
19905                .registry
19906                .get_module_by_connection(INCUMBENT)
19907                .unwrap()
19908                .is_some());
19909
19910            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19911            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19912                .await
19913                .expect("the incumbent is told to drop the abandoned binding")
19914                .unwrap()
19915                .frame;
19916            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19917            assert_eq!(goodbye.header.channel, abandoned_channel);
19918            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19919            assert!(swap.incumbent_rx.try_recv().is_err());
19920
19921            // 3. The waiting client gets a retryable refusal and no route.
19922            let response = caller_task.await.unwrap();
19923            assert_eq!(response.len(), 1);
19924            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19925            assert!(caller_rx.try_recv().is_err());
19926
19927            // 4. The reservation pair is given back, and the pending bind
19928            //    settled exactly once: one accepted open (the co-tenant) and one
19929            //    refused open (the caller), nothing counted twice.
19930            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19931            let counters = handler.counters().snapshot();
19932            assert_eq!(
19933                keyed_total(&counters, "route_open_accepted_by_principal"),
19934                1
19935            );
19936            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19937            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19938        }
19939
19940        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19941        /// id would resolve to the promoted candidate and every new route.open
19942        /// would be refused as reloading, leaving neither process routable.
19943        #[tokio::test]
19944        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19945            let mut swap = swap_with_incumbent().await;
19946            register_candidate(&swap, None);
19947            let incumbent = cutover(&swap);
19948            swap.forwarding
19949                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19950                .unwrap()
19951                .expect("the incumbent is still registered");
19952
19953            let client = ConnectionId::new(33);
19954            let (client_ctx, mut client_rx) = route_ctx(client);
19955            let route_handler = swap.handler.clone();
19956            let open_ctx = RouteCtx {
19957                connection_id: client,
19958                egress: client_ctx.egress.clone(),
19959            };
19960            let mut route_task = tokio::spawn(async move {
19961                route_handler
19962                    .handle_control_frame(
19963                        &open_ctx,
19964                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19965                    )
19966                    .await
19967                    .unwrap()
19968            });
19969            let bind = tokio::select! {
19970                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19971                response = &mut route_task => {
19972                    let response = response.unwrap();
19973                    panic!(
19974                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19975                        parse_error(&response[0])["code"]
19976                    );
19977                }
19978            };
19979            swap.handler
19980                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19981                .await
19982                .unwrap();
19983            assert!(route_task.await.unwrap().is_empty());
19984            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19985            match swap
19986                .forwarding
19987                .lookup_data_route(client, channel, epoch)
19988                .unwrap()
19989            {
19990                DataRoute::Client(DataRouteState::Bound(route)) => {
19991                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19992                }
19993                other => panic!("expected a bound route on the candidate, got {other:?}"),
19994            }
19995            assert!(swap.incumbent_rx.try_recv().is_err());
19996        }
19997
19998        /// A candidate declares itself ready with `catalog.update` on its own
19999        /// connection. If the connection-keyed registry lookups searched only the
20000        /// active slot, this would answer `not_registered` and the candidate
20001        /// would never become ready.
20002        #[tokio::test]
20003        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
20004            let swap = swap_with_incumbent().await;
20005            register_candidate(&swap, Some(false));
20006            let update = Frame::build(
20007                FrameType::Request,
20008                control_flags(),
20009                0,
20010                0,
20011                55,
20012                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
20013                    provides: manifest("aft", PROTOCOL_VERSION).provides,
20014                    capabilities: None,
20015                    ready: Some(true),
20016                })
20017                .unwrap(),
20018            )
20019            .unwrap();
20020
20021            let replies = swap
20022                .handler
20023                .handle_control_frame(&swap.candidate_ctx, update)
20024                .await
20025                .unwrap();
20026
20027            assert_eq!(replies.len(), 1);
20028            assert_eq!(
20029                replies[0].header.ty,
20030                FrameType::Response,
20031                "candidate catalog.update was refused: {:?}",
20032                serde_json::from_slice::<Value>(&replies[0].body).ok()
20033            );
20034            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
20035            assert_eq!(
20036                swap.registry
20037                    .get_module("aft")
20038                    .unwrap()
20039                    .unwrap()
20040                    .connection_id,
20041                INCUMBENT
20042            );
20043        }
20044    }
20045
20046    /// The HELLO gate while the supervisor has a swap open: only the nonce it
20047    /// minted for the candidate admits a second process, into the candidate
20048    /// slot, and that check runs ahead of the reserved-module gate.
20049    mod swap_admission {
20050        use super::*;
20051
20052        const INCUMBENT_NONCE: &str = "incumbent-nonce";
20053        const CANDIDATE_NONCE: &str = "candidate-nonce";
20054
20055        fn handler_with_incumbent(
20056            module_id: &str,
20057            reserved: bool,
20058        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
20059            let registry = Arc::new(Registry::default());
20060            let supervisor = SupervisorHandle::new();
20061            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
20062            if reserved {
20063                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
20064            }
20065            let handler =
20066                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
20067            let incumbent = handler
20068                .handle_control(
20069                    ConnectionId::new(1),
20070                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
20071                )
20072                .unwrap();
20073            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
20074            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
20075            (registry, supervisor, handler)
20076        }
20077
20078        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
20079        /// admits every nonce, so while a swap is open the swap gate is the only
20080        /// thing between a key-holder and the candidate slot. A nonce the
20081        /// supervisor did not mint, or none at all, is refused, and neither the
20082        /// incumbent's registration nor the candidate slot moves.
20083        #[test]
20084        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
20085            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
20086
20087            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
20088                let replies = handler
20089                    .handle_control(
20090                        ConnectionId::new(connection),
20091                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
20092                    )
20093                    .unwrap();
20094                assert_eq!(replies[0].header.ty, FrameType::Error);
20095                assert_eq!(
20096                    parse_error(&replies[0])["code"],
20097                    "swap_token_invalid",
20098                    "nonce {nonce:?}"
20099                );
20100            }
20101            assert!(registry.get_candidate("aft").unwrap().is_none());
20102            assert_eq!(
20103                registry.get_module("aft").unwrap().unwrap().connection_id,
20104                ConnectionId::new(1)
20105            );
20106
20107            // Control: the minted token is admitted, into the candidate slot,
20108            // and only once.
20109            let admitted = handler
20110                .handle_control(
20111                    ConnectionId::new(4),
20112                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
20113                )
20114                .unwrap();
20115            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
20116            assert_eq!(
20117                registry
20118                    .get_candidate("aft")
20119                    .unwrap()
20120                    .unwrap()
20121                    .connection_id,
20122                ConnectionId::new(4)
20123            );
20124            assert_eq!(
20125                registry.get_module("aft").unwrap().unwrap().connection_id,
20126                ConnectionId::new(1),
20127                "the candidate must not take the active slot"
20128            );
20129            let replayed = handler
20130                .handle_control(
20131                    ConnectionId::new(5),
20132                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
20133                )
20134                .unwrap();
20135            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
20136
20137            // The case only this gate covers: the incumbent has died mid-swap,
20138            // so its duplicate refusal is gone too, and without the gate a
20139            // key-holder would take the id's ACTIVE slot.
20140            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20141            let squatter = handler
20142                .handle_control(
20143                    ConnectionId::new(6),
20144                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20145                )
20146                .unwrap();
20147            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20148            assert!(
20149                registry.get_module("aft").unwrap().is_none(),
20150                "a squatter took the active slot of an id being swapped"
20151            );
20152        }
20153
20154        /// Design mutation arm (iii). A reserved module's candidate presents a
20155        /// nonce the reserved gate has never seen (that gate holds the
20156        /// incumbent's), so the swap gate must run first or the candidate is
20157        /// refused `reserved_module` and a reserved module can never be swapped.
20158        #[test]
20159        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20160            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20161
20162            let replies = handler
20163                .handle_control(
20164                    ConnectionId::new(2),
20165                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20166                )
20167                .unwrap();
20168
20169            assert_eq!(
20170                replies[0].header.ty,
20171                FrameType::HelloAck,
20172                "reserved candidate refused: {:?}",
20173                serde_json::from_slice::<Value>(&replies[0].body).ok()
20174            );
20175            assert_eq!(
20176                registry
20177                    .get_candidate("vault")
20178                    .unwrap()
20179                    .unwrap()
20180                    .connection_id,
20181                ConnectionId::new(2)
20182            );
20183        }
20184
20185        /// With no swap open the gate is inert: the incumbent's reserved gate
20186        /// and duplicate refusal behave exactly as before.
20187        #[test]
20188        fn without_an_open_swap_the_ordinary_gates_decide() {
20189            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20190            supervisor.close_swap("vault");
20191
20192            let candidate = handler
20193                .handle_control(
20194                    ConnectionId::new(2),
20195                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20196                )
20197                .unwrap();
20198            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20199            let duplicate = handler
20200                .handle_control(
20201                    ConnectionId::new(3),
20202                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20203                )
20204                .unwrap();
20205            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20206            assert!(registry.get_candidate("vault").unwrap().is_none());
20207        }
20208    }
20209
20210    /// `scope.sync` and `scope.describe` through the real control handler: who
20211    /// may sync is decided by the registration and launch nonce of the module
20212    /// connection, never by the request body.
20213    mod scopes {
20214        mod close_reasons {
20215            include!("route_close_reason_tests.rs");
20216        }
20217        mod idle_tests {
20218            use super::*;
20219            include!("scope_idle_tests.rs");
20220        }
20221        mod route_open_timings {
20222            use super::*;
20223            include!("route_open_timing_tests.rs");
20224        }
20225        mod route_open_refusal_log {
20226            use super::*;
20227            include!("route_open_refusal_log_tests.rs");
20228        }
20229        mod activity {
20230            include!("activity_scope_tests.rs");
20231        }
20232        mod delta {
20233            include!("scope_handler_delta_tests.rs");
20234        }
20235        mod watch {
20236            include!("scope_watch_tests.rs");
20237        }
20238        mod call_modes {
20239            include!("scope_call_mode_tests.rs");
20240        }
20241        mod federated {
20242            include!("scope_federated_tests.rs");
20243        }
20244        mod authorize {
20245            include!("route_authorize_tests.rs");
20246        }
20247        #[tokio::test]
20248        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20249            let rig = rig().await;
20250            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20251                "s".into(),
20252                1,
20253                "tool".into(),
20254            ))
20255            .unwrap();
20256            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20257            let (direct, _rx) = wide_ctx(999);
20258            for (ctx, expected) in [
20259                (&rig.owner, FrameType::Response),
20260                (&direct, FrameType::Error),
20261            ] {
20262                let frame =
20263                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20264                        .unwrap();
20265                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20266                assert_eq!(replies[0].header.ty, expected);
20267                if expected == FrameType::Response {
20268                    let reply: subc_control::ScopeServedByReply =
20269                        serde_json::from_slice(&replies[0].body).unwrap();
20270                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20271                } else {
20272                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20273                }
20274            }
20275            let reply = call(
20276                &rig.handler,
20277                &rig.owner,
20278                &ModuleControlRequestFromModule::ScopeDescribe {
20279                    owner: Principal::Reserved {
20280                        module_id: OWNER.into(),
20281                    },
20282                    scope_ref: "s".into(),
20283                },
20284            )
20285            .await;
20286            assert!(matches!(
20287                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20288                ModuleControlResponseToModule::ScopeDescribe { .. }
20289            ));
20290        }
20291
20292        use subc_protocol::scope::{
20293            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20294            ScopeStatus,
20295        };
20296
20297        use super::*;
20298
20299        const OWNER: &str = "prefrontal-core";
20300
20301        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20302            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20303        }
20304
20305        async fn call(
20306            handler: &ControlHandler,
20307            ctx: &RouteCtx,
20308            request: &ModuleControlRequestFromModule,
20309        ) -> Frame {
20310            let body = serde_json::to_vec(request).unwrap();
20311            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20312            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20313            assert_eq!(replies.len(), 1, "{replies:?}");
20314            replies.pop().unwrap()
20315        }
20316
20317        async fn sync(
20318            handler: &ControlHandler,
20319            ctx: &RouteCtx,
20320            generation: u64,
20321            scopes: Vec<ScopeRecord>,
20322        ) -> Result<ModuleControlResponseToModule, String> {
20323            let reply = call(
20324                handler,
20325                ctx,
20326                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20327            )
20328            .await;
20329            match reply.header.ty {
20330                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20331                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20332            }
20333        }
20334
20335        async fn describe(
20336            handler: &ControlHandler,
20337            ctx: &RouteCtx,
20338            owner: &str,
20339            scope_ref: &str,
20340        ) -> ModuleControlResponseToModule {
20341            let reply = call(
20342                handler,
20343                ctx,
20344                &ModuleControlRequestFromModule::ScopeDescribe {
20345                    owner: Principal::Reserved {
20346                        module_id: owner.to_string(),
20347                    },
20348                    scope_ref: scope_ref.to_string(),
20349                },
20350            )
20351            .await;
20352            assert_eq!(
20353                reply.header.ty,
20354                FrameType::Response,
20355                "{:?}",
20356                parse_error(&reply)
20357            );
20358            serde_json::from_slice(&reply.body).unwrap()
20359        }
20360
20361        #[tokio::test]
20362        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20363            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20364            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20365            let mut rig = rig().await;
20366            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20367                .await;
20368            let _bound = rig
20369                .bound(
20370                    Some(AFT),
20371                    PLEXUS,
20372                    Some(
20373                        rig.selector("s", Some(1))
20374                            .with_bind_proof(Some(PROOF.into())),
20375                    ),
20376                )
20377                .await;
20378            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20379            let output = serde_json::to_string(&reply).unwrap();
20380            assert!(output.contains("\"status\":\"live\""));
20381            assert!(!output.contains(PROOF));
20382            assert!(!output.contains(HASH));
20383        }
20384
20385        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20386        async fn module(
20387            handler: &ControlHandler,
20388            connection: u64,
20389            module_id: &str,
20390            nonce: Option<&str>,
20391        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20392            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20393            hello_via_sink(
20394                handler,
20395                &ctx,
20396                &mut rx,
20397                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20398            )
20399            .await;
20400            (ctx, rx)
20401        }
20402
20403        /// `direct` and every other client connection has no registration, so
20404        /// it can neither sync nor own a scope.
20405        #[tokio::test]
20406        async fn a_client_connection_cannot_sync_or_describe() {
20407            let handler = ControlHandler::new(Arc::new(Registry::default()));
20408            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20409            for request in [
20410                ModuleControlRequestFromModule::ScopeSync {
20411                    generation: 1,
20412                    scopes: vec![head("s", 1)],
20413                },
20414                ModuleControlRequestFromModule::ScopeDescribe {
20415                    owner: Principal::Direct,
20416                    scope_ref: "s".to_string(),
20417                },
20418            ] {
20419                let reply = call(&handler, &ctx, &request).await;
20420                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20421            }
20422            assert!(
20423                !handler
20424                    .scopes
20425                    .read()
20426                    .unwrap()
20427                    .describe(
20428                        &Principal::Reserved {
20429                            module_id: OWNER.to_string()
20430                        },
20431                        "s"
20432                    )
20433                    .owner_synced
20434            );
20435        }
20436
20437        /// A module the supervisor did not spawn registers without a launch
20438        /// nonce, so it is never an owner's current launch.
20439        #[tokio::test]
20440        async fn a_module_without_a_supervised_launch_cannot_sync() {
20441            let handler = ControlHandler::new(Arc::new(Registry::default()));
20442            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20443            assert_eq!(
20444                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20445                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20446            );
20447        }
20448
20449        #[tokio::test]
20450        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20451            let supervisor = SupervisorHandle::new();
20452            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20453            let handler = ControlHandler::new(Arc::new(Registry::default()))
20454                .with_supervisor(supervisor.clone());
20455            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20456            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20457                .await
20458                .expect("the current launch syncs");
20459
20460            // A swap candidate registers with the swap token and is refused
20461            // while the incumbent keeps syncing.
20462            supervisor.open_swap(OWNER, "n2".to_string());
20463            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20464            assert_eq!(
20465                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20466                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20467            );
20468            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20469                .await
20470                .expect("the serving owner syncs during the swap");
20471
20472            // The swap fails and is rolled back. The candidate never held sync
20473            // authority, and still cannot sync.
20474            supervisor.close_swap(OWNER);
20475            assert_eq!(
20476                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20477                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20478            );
20479            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20480                .await
20481                .expect("the serving owner syncs after the rollback");
20482            handler.cleanup_connection(candidate.connection_id).unwrap();
20483
20484            // A swap that cuts over. Promotion records the candidate's nonce as
20485            // the module's spawn nonce, which is what `set_spawn_nonce` does
20486            // here; the promoted connection then takes authority at any
20487            // generation and the superseded incumbent is refused.
20488            supervisor.open_swap(OWNER, "n3".to_string());
20489            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20490            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20491            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20492                .await
20493                .expect("the promoted launch takes authority");
20494            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20495                panic!("unexpected reply {reply:?}");
20496            };
20497            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20498            assert_eq!(
20499                sync(&handler, &incumbent, 4, Vec::new()).await,
20500                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20501            );
20502        }
20503
20504        /// Authority dies with its connection: the cleanup path releases it,
20505        /// so the owner's next connection takes it at any generation.
20506        #[tokio::test]
20507        async fn closing_the_authority_connection_frees_sync_authority() {
20508            let supervisor = SupervisorHandle::new();
20509            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20510            let handler = ControlHandler::new(Arc::new(Registry::default()))
20511                .with_supervisor(supervisor.clone());
20512            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20513            sync(&handler, &first, 10, vec![head("s", 1)])
20514                .await
20515                .unwrap();
20516            handler.cleanup_connection(first.connection_id).unwrap();
20517
20518            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20519            sync(&handler, &second, 1, vec![head("s", 1)])
20520                .await
20521                .expect("the next connection takes the released authority");
20522        }
20523
20524        #[tokio::test]
20525        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20526            let supervisor = SupervisorHandle::new();
20527            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20528            let handler =
20529                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20530            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20531            sync(&handler, &first, 10, vec![head("s", 1)])
20532                .await
20533                .unwrap();
20534            handler
20535                .handle_control_frame(
20536                    &first,
20537                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20538                )
20539                .await
20540                .unwrap();
20541            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20542            sync(&handler, &second, 1, vec![head("s", 1)])
20543                .await
20544                .expect("GOODBYE releases authority even if the old socket remains open");
20545        }
20546
20547        #[tokio::test]
20548        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20549            let registry = Arc::new(Registry::default());
20550            let supervisor_handle = SupervisorHandle::new();
20551            let supervisor =
20552                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20553                    .with_handle(supervisor_handle.clone())
20554                    .with_daemon_incarnation("incarnation-7".to_string());
20555            // Configured with enabled: false, so the supervisor lists the
20556            // module without spawning a process for it.
20557            supervisor
20558                .supervise_configured(
20559                    ModuleSpec {
20560                        script: None,
20561                        carry_containment: false,
20562                        module_id: OWNER.to_string(),
20563                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20564                        args: Vec::new(),
20565                        env: Vec::new(),
20566                        reserved: false,
20567                        reserved_prefixes: Vec::new(),
20568                        protocol: ModuleProtocol::Subc,
20569                        overlap: Default::default(),
20570                    },
20571                    false,
20572                )
20573                .unwrap();
20574            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20575            let handler =
20576                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20577            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20578
20579            // Configured but not yet synced: a reader waits for the owner.
20580            let ModuleControlResponseToModule::ScopeDescribe {
20581                status,
20582                daemon_incarnation,
20583                owner_synced,
20584                owner_configured,
20585                scope,
20586                ..
20587            } = describe(&handler, &reader, OWNER, "s").await
20588            else {
20589                panic!("not a describe reply");
20590            };
20591            assert_eq!(status, ScopeStatus::NotLive);
20592            assert_eq!(daemon_incarnation, "incarnation-7");
20593            assert!(!owner_synced);
20594            assert!(owner_configured);
20595            assert!(scope.is_none());
20596
20597            // Not a supervised module: the owner will never sync, and a reader
20598            // refuses rather than waits.
20599            let ModuleControlResponseToModule::ScopeDescribe {
20600                status,
20601                owner_configured,
20602                ..
20603            } = describe(&handler, &reader, "ghost", "s").await
20604            else {
20605                panic!("not a describe reply");
20606            };
20607            assert_eq!(status, ScopeStatus::NotLive);
20608            assert!(!owner_configured);
20609
20610            // Live, with the stamp fields and the computed owner_authorized.
20611            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20612            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20613            let ModuleControlResponseToModule::ScopeDescribe {
20614                status,
20615                scope_epoch,
20616                owner_synced,
20617                scope,
20618                ..
20619            } = describe(&handler, &reader, OWNER, "s").await
20620            else {
20621                panic!("not a describe reply");
20622            };
20623            assert_eq!(status, ScopeStatus::Live);
20624            assert_eq!(scope_epoch, Some(4));
20625            assert!(owner_synced);
20626            let stamp = scope.expect("a live scope carries its stamp");
20627            assert!(
20628                stamp.owner_authorized,
20629                "prefrontal-core is the default authority"
20630            );
20631            assert_eq!(stamp.kind, ScopeKind::Head);
20632        }
20633
20634        #[tokio::test]
20635        async fn scope_authority_owners_decides_owner_authorized() {
20636            let supervisor = SupervisorHandle::new();
20637            supervisor.set_spawn_nonce("broca", "b1".to_string());
20638            let handler = ControlHandler::new(Arc::new(Registry::default()))
20639                .with_supervisor(supervisor)
20640                .with_scope_authority_owners(vec!["broca".to_string()]);
20641            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20642            let mut gated = head("s", 1);
20643            gated.attributes.agent_id = Some("agent".to_string());
20644            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20645            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20646                describe(&handler, &broca, "broca", "s").await
20647            else {
20648                panic!("not a describe reply");
20649            };
20650            assert!(scope.unwrap().owner_authorized);
20651        }
20652
20653        /// With route admission, the stamp, the commit re-check and drains in
20654        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20655        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20656        #[tokio::test]
20657        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20658            let handler = ControlHandler::new(Arc::new(Registry::default()));
20659            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20660            let ack = hello_via_sink(
20661                &handler,
20662                &ctx,
20663                &mut rx,
20664                hello_frame("m", PROTOCOL_VERSION, 1),
20665            )
20666            .await;
20667            let ack = parse_ack(&ack);
20668            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20669                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20670            }
20671            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20672
20673            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20674            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20675            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20676            let reply = handler
20677                .handle_control_frame(&client, frame)
20678                .await
20679                .unwrap()
20680                .pop()
20681                .unwrap();
20682            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20683                serde_json::from_slice(&reply.body).unwrap()
20684            else {
20685                panic!("not a server.describe reply");
20686            };
20687            assert!(
20688                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20689                "{capabilities:?}"
20690            );
20691        }
20692
20693        // ---- route admission, stamps, commit re-check and drains ----------
20694
20695        const PLEXUS: &str = "plexus";
20696        const OTHER: &str = "other";
20697        const AFT: &str = "aft";
20698        const BROCA: &str = "broca";
20699        const MAGIC: &str = "magic-context";
20700
20701        fn nonce(module_id: &str) -> String {
20702            format!("nonce-{module_id}")
20703        }
20704
20705        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20706            let (tx, rx) = mpsc::channel(64);
20707            (
20708                RouteCtx {
20709                    connection_id: ConnectionId::new(connection),
20710                    egress: FrameSink::new(tx),
20711                },
20712                rx,
20713            )
20714        }
20715
20716        /// A daemon with a configured owner (prefrontal-core) registered on its
20717        /// own module connection, two routable targets (plexus, other), and
20718        /// launch nonces minted for the modules that open routes as carriers.
20719        struct Rig {
20720            handler: ControlHandler,
20721            forwarding: Arc<ForwardingTable>,
20722            owner: RouteCtx,
20723            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20724            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20725            generation: u64,
20726            next_connection: u64,
20727            _supervisor: Supervisor,
20728        }
20729
20730        async fn rig() -> Rig {
20731            rig_with_flow_support(true).await
20732        }
20733
20734        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20735            rig_with_scope_capabilities(flow_support, false).await
20736        }
20737
20738        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20739            let mut provides = Vec::new();
20740            if flow_support {
20741                provides.push("flow-scopes/v1");
20742            }
20743            if run_support {
20744                provides.push("agent-run-scopes/v1");
20745            }
20746            rig_with_target_capabilities(&provides).await
20747        }
20748
20749        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20750            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20751            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20752            // Decoder versions alone cannot admit scoped calls: only a capability
20753            // declaration promises the required run or flow behaviour.
20754            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20755            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20756            Frame::build(
20757                FrameType::Hello,
20758                control_flags(),
20759                0,
20760                0,
20761                connection,
20762                serde_json::to_vec(&body).unwrap(),
20763            )
20764            .unwrap()
20765        }
20766
20767        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20768            let registry = Arc::new(Registry::default());
20769            let forwarding = Arc::new(ForwardingTable::default());
20770            let supervisor_handle = SupervisorHandle::new();
20771            let supervisor =
20772                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20773                    .with_handle(supervisor_handle.clone());
20774            supervisor
20775                .supervise_configured(
20776                    ModuleSpec {
20777                        script: None,
20778                        carry_containment: false,
20779                        module_id: OWNER.to_string(),
20780                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20781                        args: Vec::new(),
20782                        env: Vec::new(),
20783                        reserved: false,
20784                        reserved_prefixes: Vec::new(),
20785                        protocol: ModuleProtocol::Subc,
20786                        overlap: Default::default(),
20787                    },
20788                    false,
20789                )
20790                .unwrap();
20791            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20792                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20793            }
20794            let handler =
20795                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20796                    .with_supervisor(supervisor_handle);
20797            let (owner, mut owner_rx) = wide_ctx(1);
20798            hello_via_sink(
20799                &handler,
20800                &owner,
20801                &mut owner_rx,
20802                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20803            )
20804            .await;
20805            let mut modules = BTreeMap::new();
20806            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20807                let (ctx, mut rx) = wide_ctx(connection);
20808                let hello = hello_with_capabilities(module_id, connection, provides);
20809                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20810                modules.insert(module_id.to_string(), (ctx, rx));
20811            }
20812            Rig {
20813                handler,
20814                forwarding,
20815                owner,
20816                _owner_rx: owner_rx,
20817                modules,
20818                generation: 0,
20819                next_connection: 100,
20820                _supervisor: supervisor,
20821            }
20822        }
20823
20824        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20825            ScopeCarrier::new(Principal::Reserved {
20826                module_id: module_id.to_string(),
20827            })
20828            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20829        }
20830
20831        /// The scope most tests open under: aft carries to any module, broca
20832        /// only to plexus and other, and the owner delegates as agent-1.
20833        fn session(scope_epoch: u64) -> ScopeRecord {
20834            let mut record = head("s", scope_epoch);
20835            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20836            record.attributes.agent_id = Some("agent-1".to_string());
20837            record.attributes.delegates = true;
20838            record
20839        }
20840
20841        impl Rig {
20842            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20843                self.generation += 1;
20844                sync(&self.handler, &self.owner, self.generation, scopes)
20845                    .await
20846                    .expect("the owner's sync is accepted");
20847            }
20848
20849            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20850                ScopeSelector::new(
20851                    Principal::Reserved {
20852                        module_id: OWNER.to_string(),
20853                    },
20854                    scope_ref.to_string(),
20855                    scope_epoch,
20856                )
20857            }
20858
20859            fn open_frame(
20860                &mut self,
20861                opener: Option<&str>,
20862                target: &str,
20863                scope: Option<ScopeSelector>,
20864            ) -> (
20865                RouteCtx,
20866                mpsc::Receiver<crate::router::OutboundFrame>,
20867                Frame,
20868            ) {
20869                self.next_connection += 1;
20870                let (ctx, rx) = wide_ctx(self.next_connection);
20871                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20872                    busy_refusals: None,
20873                    target: RouteTarget::ToolProvider {
20874                        module_id: target.to_string(),
20875                    },
20876                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20877                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20878                        module_id: module_id.to_string(),
20879                        launch_nonce: nonce(module_id),
20880                    }),
20881                    consumer_capabilities: None,
20882                    role_versions: None,
20883                    admission_facts: None,
20884                    scope,
20885                })
20886                .unwrap();
20887                let frame = Frame::build(
20888                    FrameType::Request,
20889                    control_flags(),
20890                    0,
20891                    0,
20892                    self.next_connection,
20893                    body,
20894                )
20895                .unwrap();
20896                (ctx, rx, frame)
20897            }
20898
20899            /// Open and expect a refusal before anything is relayed.
20900            async fn refused(
20901                &mut self,
20902                opener: Option<&str>,
20903                target: &str,
20904                scope: Option<ScopeSelector>,
20905            ) -> String {
20906                self.refusal_body(opener, target, scope).await["code"]
20907                    .as_str()
20908                    .unwrap()
20909                    .to_string()
20910            }
20911
20912            async fn refusal_body(
20913                &mut self,
20914                opener: Option<&str>,
20915                target: &str,
20916                scope: Option<ScopeSelector>,
20917            ) -> Value {
20918                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20919                let replies = tokio::time::timeout(
20920                    Duration::from_secs(2),
20921                    self.handler.handle_control_frame(&ctx, frame),
20922                )
20923                .await
20924                .expect("the open must be refused before waiting for a bind ack")
20925                .unwrap();
20926                assert_eq!(replies.len(), 1, "{replies:?}");
20927                assert_eq!(replies[0].header.ty, FrameType::Error);
20928                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20929                assert!(
20930                    module_rx.try_recv().is_err(),
20931                    "a refused open relays nothing"
20932                );
20933                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20934                parse_error(&replies[0])
20935            }
20936
20937            /// Start an open and return its task and the bind the target got.
20938            async fn relayed(
20939                &mut self,
20940                opener: Option<&str>,
20941                target: &str,
20942                scope: Option<ScopeSelector>,
20943            ) -> Relayed {
20944                self.relayed_with_legacy_root(opener, target, scope, None)
20945                    .await
20946            }
20947
20948            async fn relayed_with_legacy_root(
20949                &mut self,
20950                opener: Option<&str>,
20951                target: &str,
20952                scope: Option<ScopeSelector>,
20953                legacy_root: Option<&std::path::Path>,
20954            ) -> Relayed {
20955                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20956                if let Some(root) = legacy_root {
20957                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20958                    body["identity"]["project_root"] = serde_json::json!(root);
20959                    frame.body = serde_json::to_vec(&body).unwrap();
20960                }
20961                let handler = self.handler.clone();
20962                let task_ctx = ctx.clone();
20963                let task = tokio::spawn(async move {
20964                    handler
20965                        .handle_control_frame(&task_ctx, frame)
20966                        .await
20967                        .unwrap()
20968                });
20969                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20970                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20971                    .await
20972                    .expect("the target receives the relayed route.bind")
20973                    .unwrap()
20974                    .frame;
20975                Relayed {
20976                    target: target.to_string(),
20977                    client: ctx,
20978                    client_rx: rx,
20979                    task,
20980                    bind,
20981                }
20982            }
20983
20984            async fn ack(&self, relayed: &Relayed) {
20985                let (module, _) = &self.modules[&relayed.target];
20986                self.handler
20987                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20988                    .await
20989                    .unwrap();
20990            }
20991
20992            /// Open, ack and return the bound route.
20993            async fn bound(
20994                &mut self,
20995                opener: Option<&str>,
20996                target: &str,
20997                scope: Option<ScopeSelector>,
20998            ) -> Bound {
20999                let relayed = self.relayed(opener, target, scope).await;
21000                self.commit_relayed(relayed).await
21001            }
21002
21003            async fn bound_with_legacy_root(
21004                &mut self,
21005                opener: Option<&str>,
21006                target: &str,
21007                scope: Option<ScopeSelector>,
21008                root: &std::path::Path,
21009            ) -> Bound {
21010                let relayed = self
21011                    .relayed_with_legacy_root(opener, target, scope, Some(root))
21012                    .await;
21013                self.commit_relayed(relayed).await
21014            }
21015
21016            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
21017                self.ack(&relayed).await;
21018                let Relayed {
21019                    target,
21020                    client,
21021                    mut client_rx,
21022                    task,
21023                    bind,
21024                } = relayed;
21025                assert!(
21026                    task.await.unwrap().is_empty(),
21027                    "the open is answered by commit"
21028                );
21029                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
21030                Bound {
21031                    target,
21032                    client,
21033                    client_rx,
21034                    channel,
21035                    epoch,
21036                    bind,
21037                }
21038            }
21039
21040            fn live(&self, route: &Bound) -> bool {
21041                matches!(
21042                    self.forwarding
21043                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21044                        .unwrap(),
21045                    DataRoute::Client(DataRouteState::Bound(_))
21046                )
21047            }
21048        }
21049
21050        struct Relayed {
21051            target: String,
21052            client: RouteCtx,
21053            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21054            task: tokio::task::JoinHandle<Vec<Frame>>,
21055            bind: Frame,
21056        }
21057
21058        struct Bound {
21059            target: String,
21060            client: RouteCtx,
21061            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
21062            channel: u16,
21063            epoch: u32,
21064            bind: Frame,
21065        }
21066
21067        impl Bound {
21068            /// The reason of the `route.closed` this client was sent, after
21069            /// checking it also got a GOODBYE on exactly this route.
21070            fn closed_reason(&mut self) -> RouteCloseReason {
21071                let mut reason = None;
21072                let mut goodbye = false;
21073                while let Ok(outbound) = self.client_rx.try_recv() {
21074                    let frame = outbound.frame;
21075                    match frame.header.ty {
21076                        FrameType::Goodbye => {
21077                            assert_eq!(
21078                                (frame.header.channel, frame.header.epoch),
21079                                (self.channel, self.epoch)
21080                            );
21081                            goodbye = true;
21082                        }
21083                        FrameType::Push => {
21084                            let ClientControlPush::RouteClosed {
21085                                reason: r,
21086                                module_id,
21087                                ..
21088                            } = serde_json::from_slice(&frame.body).unwrap()
21089                            else {
21090                                panic!("unexpected push");
21091                            };
21092                            assert_eq!(module_id, self.target);
21093                            reason = Some(r);
21094                        }
21095                        other => panic!("unexpected frame {other:?}"),
21096                    }
21097                }
21098                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
21099                reason.expect("the client is told why the route closed")
21100            }
21101
21102            fn untouched(&mut self) -> bool {
21103                self.client_rx.try_recv().is_err()
21104            }
21105
21106            fn stamp(&self) -> Option<ScopeStamp> {
21107                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
21108                    ModuleControlRequest::RouteBind { scope, .. } => scope,
21109                    other => panic!("expected a route.bind, got {other:?}"),
21110                }
21111            }
21112        }
21113
21114        #[tokio::test]
21115        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
21116        ) {
21117            let mut rig = rig().await;
21118            let mut record = session(1);
21119            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
21120            record.child_owners = vec![Principal::Reserved {
21121                module_id: MAGIC.to_string(),
21122            }];
21123            rig.sync(vec![record]).await;
21124            let scope = || Some(rig_selector("s", Some(1)));
21125
21126            // Admitted: the owner, a bare carrier to any module, a targeted
21127            // carrier to its listed module.
21128            rig.bound(Some(OWNER), PLEXUS, scope()).await;
21129            rig.bound(Some(AFT), OTHER, scope()).await;
21130            rig.bound(Some(BROCA), PLEXUS, scope()).await;
21131
21132            // Refused scope_not_carrier: a targeted carrier to an unlisted
21133            // module, a module that is not listed at all (a child owner is not
21134            // a carrier), and a direct key-holder.
21135            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21136                assert_eq!(
21137                    rig.refused(opener, target, scope()).await,
21138                    error_codes::SCOPE_NOT_CARRIER,
21139                    "{opener:?} -> {target}"
21140                );
21141            }
21142        }
21143
21144        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21145            ScopeSelector::new(
21146                Principal::Reserved {
21147                    module_id: OWNER.to_string(),
21148                },
21149                scope_ref.to_string(),
21150                scope_epoch,
21151            )
21152        }
21153
21154        #[tokio::test]
21155        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21156            let mut rig = rig().await;
21157            rig.sync(vec![session(1)]).await;
21158            for opener in [OWNER, AFT] {
21159                assert_eq!(
21160                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21161                        .await,
21162                    error_codes::SCOPE_EPOCH_REQUIRED,
21163                    "{opener}"
21164                );
21165            }
21166        }
21167
21168        #[tokio::test]
21169        async fn admission_separates_not_synced_not_live_and_ended() {
21170            let mut rig = rig().await;
21171            // Before the configured owner's first sync: retryable.
21172            let code = rig
21173                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21174                .await;
21175            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21176            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21177
21178            // An owner that is not configured will never sync: terminal.
21179            let ghost = ScopeSelector::new(
21180                Principal::Reserved {
21181                    module_id: "ghost".to_string(),
21182                },
21183                "s".to_string(),
21184                Some(1),
21185            );
21186            assert_eq!(
21187                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21188                error_codes::SCOPE_NOT_LIVE
21189            );
21190
21191            rig.sync(vec![session(2)]).await;
21192            assert_eq!(
21193                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21194                    .await,
21195                error_codes::SCOPE_NOT_LIVE
21196            );
21197            for epoch in [1, 3] {
21198                assert_eq!(
21199                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21200                        .await,
21201                    error_codes::SCOPE_ENDED,
21202                    "epoch {epoch}"
21203                );
21204            }
21205            // Control: the live epoch is admitted.
21206            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21207                .await;
21208        }
21209
21210        #[tokio::test]
21211        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21212            let mut rig = rig().await;
21213            rig.sync(vec![session(1)]).await;
21214            let route = rig
21215                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21216                .await;
21217            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21218            assert_eq!(stamp.scope_ref, "s");
21219            assert_eq!(stamp.scope_epoch, 1);
21220            assert_eq!(stamp.kind, ScopeKind::Head);
21221            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21222            assert!(stamp.attributes.delegates);
21223            assert!(stamp.owner_authorized);
21224            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21225            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21226
21227            // broca owns a scope of its own on its own module connection; it is
21228            // not in scope_authority_owners, so its stamp is not authorized.
21229            let (broca, mut broca_rx) = wide_ctx(50);
21230            hello_via_sink(
21231                &rig.handler,
21232                &broca,
21233                &mut broca_rx,
21234                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21235            )
21236            .await;
21237            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21238                .await
21239                .unwrap();
21240            let own = ScopeSelector::new(
21241                Principal::Reserved {
21242                    module_id: BROCA.to_string(),
21243                },
21244                "b".to_string(),
21245                Some(1),
21246            );
21247            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21248            assert!(!route.stamp().unwrap().owner_authorized);
21249        }
21250
21251        #[tokio::test]
21252        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21253            let mut rig = rig().await;
21254            let mut record = head("s", 1);
21255            record.carriers = vec![carrier(AFT, None)];
21256            let flow_id = "Flow:run-7/step_2!~";
21257            record.attributes.flow_id = Some(flow_id.to_string());
21258            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21259                .await
21260                .unwrap();
21261            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21262                panic!("not a sync reply");
21263            };
21264            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21265            let route = rig
21266                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21267                .await;
21268            assert!(rig.live(&route), "the stamped bind committed");
21269            let stamp = route.stamp().expect("a flow scope carries a stamp");
21270            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21271            assert_eq!(stamp.attributes.agent_id, None);
21272            assert!(!stamp.attributes.delegates);
21273            assert!(stamp.owner_authorized);
21274            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21275            assert_eq!(unscoped.stamp(), None);
21276        }
21277
21278        #[tokio::test]
21279        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21280            let mut rig = rig_with_flow_support(false).await;
21281            let mut record = session(1);
21282            record.attributes.flow_id = Some("flow:7".to_string());
21283            rig.sync(vec![record]).await;
21284            for opener in [OWNER, AFT] {
21285                let body = rig
21286                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21287                    .await;
21288                assert_eq!(body["code"], "target_flow_unsupported");
21289                let message = body["message"].as_str().unwrap();
21290                for required in [PLEXUS, "flow-scopes/v1"] {
21291                    assert!(message.contains(required), "{message}");
21292                }
21293            }
21294        }
21295
21296        #[tokio::test]
21297        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21298            let mut rig = rig_with_flow_support(true).await;
21299            let mut record = session(1);
21300            record.attributes.flow_id = Some("flow:7".to_string());
21301            rig.sync(vec![record]).await;
21302            for opener in [OWNER, AFT] {
21303                let route = rig
21304                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21305                    .await;
21306                assert!(rig.live(&route));
21307                assert_eq!(
21308                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21309                    Some("flow:7")
21310                );
21311            }
21312        }
21313
21314        #[tokio::test]
21315        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21316            use std::future::Future;
21317
21318            let mut rig = rig_with_flow_support(true).await;
21319            let mut record = session(1);
21320            record.attributes.flow_id = Some("flow:7".to_string());
21321            rig.sync(vec![record]).await;
21322            let (client, mut client_rx, frame) =
21323                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21324            // Hold the route-open response permit so admission sees the first
21325            // target but relay reservation cannot capture an endpoint yet.
21326            for _ in 0..64 {
21327                client.egress.try_send(route_bind_ack(1)).unwrap();
21328            }
21329            let handler = rig.handler.clone();
21330            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21331            std::future::poll_fn(|cx| {
21332                assert!(open.as_mut().poll(cx).is_pending());
21333                std::task::Poll::Ready(())
21334            })
21335            .await;
21336            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21337
21338            let old_connection = rig.modules[PLEXUS].0.connection_id;
21339            rig.handler.cleanup_connection(old_connection).unwrap();
21340            let (replacement, mut replacement_rx) = wide_ctx(200);
21341            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21342            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21343            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21344            let hello = Frame::build(
21345                FrameType::Hello,
21346                control_flags(),
21347                0,
21348                0,
21349                200,
21350                serde_json::to_vec(&body).unwrap(),
21351            )
21352            .unwrap();
21353            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21354
21355            client_rx.try_recv().unwrap();
21356            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21357                .await
21358                .expect("the replacement is refused without waiting for a bind ack")
21359                .unwrap();
21360            assert_eq!(replies.len(), 1);
21361            let body = parse_error(&replies[0]);
21362            assert_eq!(body["code"], "target_flow_unsupported");
21363            for required in [PLEXUS, "flow-scopes/v1"] {
21364                assert!(body["message"].as_str().unwrap().contains(required));
21365            }
21366            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21367            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21368            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21369            assert!(rig
21370                .handler
21371                .registry
21372                .get_module_by_connection(replacement.connection_id)
21373                .unwrap()
21374                .is_some());
21375        }
21376
21377        #[tokio::test]
21378        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21379            use std::future::Future;
21380            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21381            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21382            const NEXT_HASH: &str =
21383                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21384            let mut rig = rig().await;
21385            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21386            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21387            rig.sync(vec![record.clone()]).await;
21388            let (client, mut rx, frame) = rig.open_frame(
21389                None,
21390                PLEXUS,
21391                Some(
21392                    rig.selector("s", Some(1))
21393                        .with_bind_proof(Some(PROOF.into())),
21394                ),
21395            );
21396            // Hold egress reservation while the scope owner changes its bind-proof
21397            // hash, so a proof valid at admission must be checked again at relay.
21398            for _ in 0..64 {
21399                client.egress.try_send(route_bind_ack(1)).unwrap();
21400            }
21401            let handler = rig.handler.clone();
21402            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21403            std::future::poll_fn(|cx| {
21404                assert!(open.as_mut().poll(cx).is_pending());
21405                std::task::Poll::Ready(())
21406            })
21407            .await;
21408            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21409            rig.sync(vec![record]).await;
21410            rx.try_recv().unwrap();
21411            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21412                .await
21413                .unwrap()
21414                .unwrap();
21415            assert_eq!(
21416                parse_error(&replies[0])["code"],
21417                error_codes::SCOPE_BIND_PROOF_MISMATCH
21418            );
21419            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21420            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21421            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21422        }
21423
21424        #[tokio::test]
21425        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21426            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21427            let mut rig = rig().await;
21428            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21429                .await;
21430            for opener in [OWNER, AFT] {
21431                for proof in [None, Some("malformed+proof=")] {
21432                    let route = rig
21433                        .bound(
21434                            Some(opener),
21435                            PLEXUS,
21436                            Some(
21437                                rig.selector("s", Some(1))
21438                                    .with_bind_proof(proof.map(str::to_string)),
21439                            ),
21440                        )
21441                        .await;
21442                    assert!(rig.live(&route));
21443                }
21444            }
21445        }
21446
21447        #[tokio::test]
21448        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21449            use std::future::Future;
21450            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21451            const NEXT_HASH: &str =
21452                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21453            let mut rig = rig().await;
21454            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21455                .await;
21456            let (client, mut rx, frame) =
21457                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21458            for _ in 0..64 {
21459                client.egress.try_send(route_bind_ack(1)).unwrap();
21460            }
21461            let handler = rig.handler.clone();
21462            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21463            std::future::poll_fn(|cx| {
21464                assert!(open.as_mut().poll(cx).is_pending());
21465                std::task::Poll::Ready(())
21466            })
21467            .await;
21468            rig.sync(vec![
21469                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21470            ])
21471            .await;
21472            rx.try_recv().unwrap();
21473            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21474            let bind = std::future::poll_fn(|cx| {
21475                assert!(open.as_mut().poll(cx).is_pending());
21476                module_rx.poll_recv(cx)
21477            })
21478            .await
21479            .unwrap()
21480            .frame;
21481            handler
21482                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21483                .await
21484                .unwrap();
21485            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21486                .await
21487                .unwrap()
21488                .unwrap();
21489            assert_eq!(replies.len(), 1);
21490            // Proof rechecking allowed the relay. Independent tag settlement
21491            // still asks the opener to retry after any same-epoch content change.
21492            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21493            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21494            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21495            let route = rig
21496                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21497                .await;
21498            assert!(rig.live(&route));
21499        }
21500
21501        #[tokio::test]
21502        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21503        {
21504            let mut rig = rig_with_flow_support(false).await;
21505            rig.sync(vec![session(1)]).await;
21506            let route = rig
21507                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21508                .await;
21509            assert!(rig.live(&route));
21510            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21511            let mut record = session(1);
21512            record.attributes.flow_id = Some("flow:7".to_string());
21513            rig.sync(vec![record]).await;
21514            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21515            assert!(rig.live(&unscoped));
21516            assert_eq!(unscoped.stamp(), None);
21517        }
21518
21519        #[tokio::test]
21520        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21521            let mut rig = rig().await;
21522            let mut record = session(1);
21523            record.attributes.flow_id = Some("flow:7".to_string());
21524            rig.sync(vec![record.clone()]).await;
21525            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21526            let mut owner_route = rig
21527                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21528                .await;
21529            let mut carrier_route = rig
21530                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21531                .await;
21532            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21533            rig.sync(vec![record.clone()]).await;
21534            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21535            assert!(rig.live(&owner_route) && owner_route.untouched());
21536            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21537
21538            record.attributes.flow_id = Some("flow:8".to_string());
21539            rig.sync(vec![record]).await;
21540            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21541            let before = before.unwrap();
21542            assert_eq!(after.scope_epoch, before.scope_epoch);
21543            assert!(after.version > before.version);
21544            for route in [&mut owner_route, &mut carrier_route] {
21545                assert!(!rig.live(route));
21546                assert_eq!(
21547                    route.closed_reason(),
21548                    RouteCloseReason::ScopeDelegationChanged
21549                );
21550            }
21551            assert!(rig.live(&unscoped) && unscoped.untouched());
21552            // Each provider also receives a GOODBYE for its drained route;
21553            // consume it before expecting the next route.bind on that sink.
21554            for target in [PLEXUS, OTHER] {
21555                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21556                let goodbye = module_rx
21557                    .try_recv()
21558                    .expect("the provider sees the drain")
21559                    .frame;
21560                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21561                assert!(module_rx.try_recv().is_err());
21562            }
21563            let rebound = rig
21564                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21565                .await;
21566            assert_eq!(
21567                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21568                Some("flow:8")
21569            );
21570        }
21571
21572        /// The owner's sync lands between admission and the module's ack. The
21573        /// open is refused by name, the module's other routes stay up, and the
21574        /// reserved pair is released. Changed content is retryable; an ended
21575        /// scope is not.
21576        #[tokio::test]
21577        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21578            let mut rig = rig().await;
21579            rig.sync(vec![session(1)]).await;
21580            let mut cotenant = rig
21581                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21582                .await;
21583
21584            let mut changed = session(1);
21585            changed.child_owners.push(Principal::Reserved {
21586                module_id: MAGIC.to_string(),
21587            });
21588            let mut ended = None;
21589            for (code, next) in [
21590                (error_codes::SCOPE_CHANGED, vec![changed]),
21591                (error_codes::SCOPE_ENDED, Vec::new()),
21592            ] {
21593                let relayed = rig
21594                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21595                    .await;
21596                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21597                ended = Some(next.is_empty());
21598                rig.sync(next).await;
21599                rig.ack(&relayed).await;
21600                let replies = relayed.task.await.unwrap();
21601                assert_eq!(replies.len(), 1, "{replies:?}");
21602                assert_eq!(parse_error(&replies[0])["code"], code);
21603                assert_eq!(
21604                    subc_protocol::error_codes::is_retryable_route_open(code),
21605                    code == error_codes::SCOPE_CHANGED
21606                );
21607                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21608                // The module is told to drop just the binding it created.
21609                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21610                // Collected, because ending the scope also closes the co-tenant
21611                // route, whose GOODBYE comes first.
21612                let mut goodbyes = Vec::new();
21613                while let Ok(outbound) = plexus_rx.try_recv() {
21614                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21615                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21616                }
21617                assert!(
21618                    goodbyes.contains(&(bind_channel, bind_epoch)),
21619                    "{goodbyes:?}"
21620                );
21621                assert!(rig
21622                    .handler
21623                    .registry
21624                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21625                    .unwrap()
21626                    .is_some());
21627            }
21628            assert_eq!(ended, Some(true));
21629            // The co-tenant stayed up through the change, and closed only when
21630            // the scope ended, by the drain rule rather than by the commit.
21631            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21632        }
21633
21634        /// Each row of the drain table on one set of routes: the owner's, a
21635        /// bare carrier's, and a targeted carrier's to each of its targets.
21636        #[tokio::test]
21637        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21638            struct Case {
21639                name: &'static str,
21640                change: fn(&mut ScopeRecord),
21641                /// Closed routes by index: owner->plexus, aft->plexus,
21642                /// broca->plexus, broca->other.
21643                closed: [Option<RouteCloseReason>; 4],
21644            }
21645            use RouteCloseReason::*;
21646            let cases = [
21647                Case {
21648                    name: "a carrier entry removed",
21649                    change: |r| {
21650                        r.carriers.retain(|c| {
21651                            c.principal
21652                                != Principal::Reserved {
21653                                    module_id: AFT.to_string(),
21654                                }
21655                        })
21656                    },
21657                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21658                },
21659                Case {
21660                    name: "a target removed from a carrier",
21661                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21662                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21663                },
21664                Case {
21665                    name: "a bare carrier narrowed to targets",
21666                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21667                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21668                },
21669                Case {
21670                    name: "delegates turned off",
21671                    change: |r| r.attributes.delegates = false,
21672                    closed: [Some(ScopeDelegationChanged); 4],
21673                },
21674                Case {
21675                    name: "agent_id changed",
21676                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21677                    closed: [Some(ScopeDelegationChanged); 4],
21678                },
21679                Case {
21680                    name: "a carrier added, child owners changed, the record re-sent",
21681                    change: |r| {
21682                        r.carriers.push(carrier(MAGIC, None));
21683                        r.child_owners.push(Principal::Reserved {
21684                            module_id: MAGIC.to_string(),
21685                        });
21686                    },
21687                    closed: [None; 4],
21688                },
21689                Case {
21690                    name: "a target added",
21691                    change: |r| {
21692                        r.carriers[1]
21693                            .targets
21694                            .as_mut()
21695                            .unwrap()
21696                            .push("third".to_string())
21697                    },
21698                    closed: [None; 4],
21699                },
21700                Case {
21701                    name: "delegates turned on",
21702                    change: |r| r.attributes.delegates = true,
21703                    closed: [None; 4],
21704                },
21705            ];
21706            for case in cases {
21707                let mut rig = rig().await;
21708                rig.sync(vec![session(1)]).await;
21709                let scope = || Some(rig_selector("s", Some(1)));
21710                let mut routes = [
21711                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21712                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21713                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21714                    rig.bound(Some(BROCA), OTHER, scope()).await,
21715                ];
21716                let mut record = session(1);
21717                (case.change)(&mut record);
21718                rig.sync(vec![record]).await;
21719                for (index, expected) in case.closed.iter().enumerate() {
21720                    let route = &mut routes[index];
21721                    match expected {
21722                        Some(reason) => {
21723                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21724                            assert_eq!(
21725                                route.closed_reason(),
21726                                *reason,
21727                                "{}: route {index}",
21728                                case.name
21729                            );
21730                        }
21731                        None => {
21732                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21733                            assert!(
21734                                route.untouched(),
21735                                "{}: route {index} was told something",
21736                                case.name
21737                            );
21738                        }
21739                    }
21740                }
21741            }
21742        }
21743
21744        #[tokio::test]
21745        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21746            // Removed, and replaced by a higher epoch.
21747            for next in [Vec::new(), vec![session(2)]] {
21748                let mut rig = rig().await;
21749                rig.sync(vec![session(1)]).await;
21750                let mut route = rig
21751                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21752                    .await;
21753                rig.sync(next).await;
21754                assert!(!rig.live(&route));
21755                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21756            }
21757
21758            // A child whose parent ends: its routes close as parent-ended, the
21759            // child stays live, and routes under the parent close as ended.
21760            let mut rig = rig().await;
21761            let mut child = session(1);
21762            child.scope_ref = "child".to_string();
21763            child.kind = ScopeKind::Worker;
21764            child.parent = Some(ScopeParent::new(
21765                Principal::Reserved {
21766                    module_id: OWNER.to_string(),
21767                },
21768                "s".to_string(),
21769                1,
21770            ));
21771            rig.sync(vec![session(1), child.clone()]).await;
21772            let mut child_route = rig
21773                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21774                .await;
21775            assert_eq!(
21776                child_route.stamp().unwrap().parent_state,
21777                Some(ParentState::Linked)
21778            );
21779            rig.sync(vec![child]).await;
21780            assert!(!rig.live(&child_route));
21781            assert_eq!(
21782                child_route.closed_reason(),
21783                RouteCloseReason::ScopeParentEnded
21784            );
21785        }
21786
21787        #[tokio::test]
21788        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21789        ) {
21790            let mut rig = rig().await;
21791            rig.sync(vec![session(1)]).await;
21792            let mut route = rig
21793                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21794                .await;
21795            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21796            rig.sync(vec![session(1)]).await;
21797            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21798            assert!(rig.live(&route) && route.untouched());
21799
21800            // A call in flight on the route when another carrier is added. A
21801            // forwarded REQUEST holds one credit on the route's flow until the
21802            // module answers; the router takes it exactly like this.
21803            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21804                .forwarding
21805                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21806                .unwrap()
21807            else {
21808                panic!("the route is bound");
21809            };
21810            binding.flow.acquire_tagged(9, false).await.unwrap();
21811            let mut widened = session(1);
21812            widened.carriers.push(carrier(MAGIC, None));
21813            rig.sync(vec![widened]).await;
21814            assert!(rig.live(&route) && route.untouched());
21815            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21816            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21817            // The call's credit is still held on an open flow, so its answer
21818            // will be delivered: closing the route would have closed the flow.
21819            assert_eq!(binding.flow.in_flight(), 1);
21820            binding
21821                .flow
21822                .acquire_tagged(10, false)
21823                .await
21824                .expect("the flow is still open");
21825        }
21826
21827        /// A swap's superseded endpoint keeps its routes until drained; ending
21828        /// the scope closes them there too.
21829        #[tokio::test]
21830        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21831            let mut rig = rig().await;
21832            rig.sync(vec![session(1)]).await;
21833            let mut on_incumbent = rig
21834                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21835                .await;
21836
21837            // Swap plexus: register a candidate and cut over, leaving the
21838            // incumbent superseded with the route still on it.
21839            let (candidate, _candidate_rx) = wide_ctx(9);
21840            let registration = rig
21841                .handler
21842                .registry
21843                .register_candidate_with_control_ops(
21844                    manifest(PLEXUS, PROTOCOL_VERSION),
21845                    PROTOCOL_VERSION,
21846                    candidate.connection_id,
21847                    module_baseline_control_ops(),
21848                )
21849                .unwrap();
21850            rig.forwarding
21851                .register_candidate_module_connection(
21852                    candidate.connection_id,
21853                    PLEXUS.to_string(),
21854                    PROTOCOL_VERSION,
21855                    manifest_concurrency(&registration.manifest),
21856                    candidate.egress.clone(),
21857                )
21858                .unwrap();
21859            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21860            rig.handler
21861                .registry
21862                .promote_candidate(PLEXUS)
21863                .unwrap()
21864                .unwrap();
21865            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21866
21867            rig.sync(Vec::new()).await;
21868            assert!(!rig.live(&on_incumbent));
21869            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21870            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21871            let goodbye = incumbent_rx
21872                .try_recv()
21873                .expect("the superseded endpoint is told")
21874                .frame;
21875            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21876        }
21877    }
21878}
21879
21880#[cfg(test)]
21881mod concurrency_default_exposure_tests {
21882    use super::*;
21883
21884    fn hello_body(role_json: &str) -> Vec<u8> {
21885        format!(
21886            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":[]}}}}}}}}"#
21887        )
21888        .into_bytes()
21889    }
21890
21891    fn manifest_from(body: &[u8]) -> ModuleManifest {
21892        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21893        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21894            .expect("manifest parses")
21895    }
21896
21897    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21898
21899    #[test]
21900    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21901        let body = hello_body(&format!(
21902            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21903        ));
21904        let manifest = manifest_from(&body);
21905        // Precondition: serde really resolved it to the default, so the typed
21906        // manifest alone cannot answer the question this probe exists for.
21907        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21908        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21909    }
21910
21911    #[test]
21912    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21913        let body = hello_body(&format!(
21914            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21915        ));
21916        let manifest = manifest_from(&body);
21917        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21918        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21919    }
21920
21921    #[test]
21922    fn non_management_roles_are_never_reported() {
21923        let body = hello_body(
21924            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21925        );
21926        let manifest = manifest_from(&body);
21927        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21928    }
21929}