Skip to main content

subc_daemon/control/
config_gate.rs

1use subc_control::config::{ConfigControlRequest, ConfigControlResponse};
2
3use super::*;
4mod admission;
5mod daemon_readers;
6pub(super) use daemon_readers::preview_approved_daemon;
7mod delivery_worker;
8mod phone;
9mod recovery;
10mod route_policy;
11mod settings;
12mod widening;
13
14/// Settings reads and user-layer edit plans are served together.
15pub(super) const CONFIG_SETTINGS_SURFACE_ENABLED: bool = true;
16
17/// Bound each immutable module review so an unanswered request cannot approve a plan.
18const CONFIG_REVIEW_TIMEOUT: Duration = Duration::from_secs(30);
19
20/// After a phone answer, lock waits and freshness work have thirty seconds to
21/// reach durable publication. Publication already started returns its real result.
22const CONFIG_APPROVAL_COMMIT_TIMEOUT: Duration = Duration::from_secs(30);
23use crate::config_gate::{
24    ApprovalChallenge, ApprovalFacts, ApprovalReply, GateError, PlanKind, PresenceDecision,
25};
26
27pub(super) fn is_config_op(op: &str) -> bool {
28    matches!(
29        op,
30        "config.status"
31            | "config.modules"
32            | "config.schema"
33            | "config.show"
34            | "config.watch"
35            | "config.plan"
36            | "config.plan_get"
37            | "config.plan_discard"
38            | "config.apply"
39            | "config.stamp"
40            | "config.unstamp"
41            | "config.history"
42            | "config.rollback"
43            | "config.place_program"
44    )
45}
46
47pub(super) fn is_module_config_op(op: &str) -> bool {
48    matches!(op, "config.declare" | "config.get" | "config.applied")
49}
50
51impl PrivilegedRequest for ConfigControlRequest {
52    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
53        // The config gate binds trusted review and presence to its digest. The
54        // generic operator prompt would run twice, and its log/shortcut modes
55        // cannot substitute for config approval.
56        match self {
57            Self::Status {} => None,
58            Self::Plan { .. } => None,
59            Self::Apply { .. } => None,
60            Self::Stamp {} => None,
61            Self::Unstamp {} => None,
62            Self::History {} => None,
63            Self::Rollback { .. } => None,
64            Self::PlaceProgram { .. } => None,
65            _ => None,
66        }
67    }
68}
69
70impl ControlHandler {
71    #[cfg(feature = "test-support")]
72    pub(crate) fn with_config_os_prompt_policy_for_tests(self) -> Self {
73        if let Some(owner) = self.config_runtime.as_ref() {
74            owner.set_os_prompt_policy_for_tests();
75        }
76        self
77    }
78    fn config_delivery_target_current(
79        &self,
80        module: &str,
81        connection: ConnectionId,
82        active: bool,
83        correlation: u64,
84    ) -> Result<bool, RouterError> {
85        if active {
86            Ok(self
87                .registry
88                .get_module(module)
89                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
90                .is_some_and(|target| target.connection_id == connection)
91                && self
92                    .forwarding
93                    .active_module_endpoint(module)
94                    .map_err(RouterError::Forwarding)?
95                    .is_some_and(|target| target.connection_id == connection))
96        } else {
97            Ok(self
98                .registry
99                .get_candidate(module)
100                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))?
101                .is_some_and(|target| target.connection_id == connection))
102        }
103    }
104
105    pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
106        frame.header.channel == 0
107            && frame.header.ty == FrameType::Request
108            && matches!(
109                serde_json::from_slice::<ConfigControlRequest>(&frame.body),
110                Ok(ConfigControlRequest::Apply { .. })
111            )
112    }
113
114    pub(crate) fn reserve_config_approval(
115        &self,
116        ctx: &RouteCtx,
117        frame: &Frame,
118    ) -> std::result::Result<Option<crate::config_gate::runtime::ApprovalRequestGuard>, GateError>
119    {
120        if self.defers_config_approval(frame) {
121            if let Some(owner) = &self.config_runtime {
122                return owner
123                    .reserve_approval_request(ctx.connection_id, frame.header.corr)
124                    .map(Some);
125            }
126        }
127        Ok(None)
128    }
129
130    pub(super) fn cancel_config_approval(&self, caller: ConnectionId, correlation: u64) -> bool {
131        use crate::config_gate::runtime::CancelApprovalRequest;
132        let Some(owner) = &self.config_runtime else {
133            return false;
134        };
135        match owner.cancel_approval_request_outcome(caller, correlation) {
136            CancelApprovalRequest::Unknown => false,
137            CancelApprovalRequest::Withdrawn | CancelApprovalRequest::AlreadyReported => true,
138            CancelApprovalRequest::TooLate => {
139                if let Some(activity) = &self.activity {
140                    activity.config_cancel_too_late(caller, correlation);
141                }
142                true
143            }
144        }
145    }
146
147    pub(super) async fn handle_module_config_request(
148        &self,
149        ctx: &RouteCtx,
150        frame: Frame,
151        op: &str,
152    ) -> Result<Vec<Frame>, RouterError> {
153        let Some(runtime) = self.config_runtime.clone() else {
154            return Ok(vec![control_error_frame(
155                &frame,
156                "config_gate_inactive",
157                "no config store configured",
158            )?]);
159        };
160        let registration = self
161            .registry
162            .get_module_by_connection(ctx.connection_id)
163            .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
164        let Some(registration) = registration else {
165            return Ok(vec![control_error_frame(
166                &frame,
167                "not_registered",
168                "module config operations require a registered connection",
169            )?]);
170        };
171        let module = registration.manifest.module_id.clone();
172        let gate = runtime
173            .module_gate(&module)
174            .map_err(|e| RouterError::backend(0, frame.header.corr, e.to_string()))?;
175        let mut module_guard = Some(gate.lock().await);
176        let active = self
177            .registry
178            .get_module(&module)
179            .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
180            .is_some_and(|r| r.connection_id == ctx.connection_id)
181            && self
182                .forwarding
183                .active_module_endpoint(&module)
184                .map_err(RouterError::Forwarding)?
185                .is_some_and(|target| target.connection_id == ctx.connection_id);
186        let candidate = self
187            .registry
188            .get_candidate(&module)
189            .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?
190            .is_some_and(|r| r.connection_id == ctx.connection_id);
191        if !active && !candidate {
192            return Ok(vec![control_error_frame(
193                &frame,
194                "not_delivery_target",
195                "connection is no longer the active or candidate delivery target",
196            )?]);
197        }
198        let body = frame.body.clone();
199        let connection = ctx.connection_id;
200        let mut delivered_view = None;
201        let result = match op {
202            "config.declare" => {
203                let declaration = serde_json::from_slice(&body).map_err(|_| {
204                    GateError::new("invalid_control_body", "malformed config.declare request")
205                });
206                match declaration {
207                    Ok(declaration) => {
208                        config_work(runtime.clone(), ConfigWake::None, move |owner| {
209                            owner.declare(connection, &module, declaration, active)?;
210                            Ok(serde_json::json!({"op":"config.declare"}))
211                        })
212                        .await
213                    }
214                    Err(error) => Err(error),
215                }
216            }
217            "config.get" => {
218                let request =
219                    serde_json::from_slice::<subc_protocol::config::ConfigGetRequest>(&body)
220                        .map_err(|_| {
221                            GateError::new("invalid_control_body", "malformed config.get request")
222                        });
223                match request {
224                    Ok(request) => {
225                        let module_id = module.clone();
226                        let get = async {
227                            if runtime.project_settings_enabled() && request.project_id.is_some() {
228                                let request = request.clone();
229                                let module = module_id.clone();
230                                let read = runtime
231                                    .on_blocking(move |owner| {
232                                        owner.begin_unstamped_project_get(
233                                            connection, module, request,
234                                        )
235                                    })
236                                    .await?;
237                                if let Some(read) = read {
238                                    // No delivery or module gate may wait on a repository mount.
239                                    drop(module_guard.take());
240                                    let reply = runtime.read_unstamped_project(read).await?;
241                                    module_guard = Some(gate.lock().await);
242                                    return Ok(reply);
243                                }
244                            }
245                            config_work(runtime.clone(), ConfigWake::None, move |owner| {
246                                owner.module_get_for_rpc(connection, &module_id, request)
247                            })
248                            .await
249                        };
250                        match get.await {
251                            Ok(reply) => {
252                                let encoded = serde_json::to_value(&reply).map_err(|_| {
253                                    GateError::new(
254                                        "config_unavailable",
255                                        "could not encode config view",
256                                    )
257                                });
258                                delivered_view = Some(reply);
259                                encoded
260                            }
261                            Err(error) => Err(error),
262                        }
263                    }
264                    Err(error) => Err(error),
265                }
266            }
267            "config.applied" => {
268                match serde_json::from_slice::<subc_protocol::config::ConfigAppliedRequest>(&body) {
269                    Ok(request) => {
270                        config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
271                            owner.module_applied(connection, &module, request)?;
272                            Ok(serde_json::json!({"op":"config.applied"}))
273                        })
274                        .await
275                    }
276                    Err(_) => Err(GateError::new(
277                        "invalid_control_body",
278                        "malformed config.applied request",
279                    )),
280                }
281            }
282            _ => Err(GateError::new(
283                "invalid_control_body",
284                "unsupported module configuration operation",
285            )),
286        };
287        match result {
288            Ok(response) => {
289                let response =
290                    control_response_body_frame(&frame, &response, "module config response")?;
291                if let Some(view) = delivered_view {
292                    use crate::config_gate::runtime::delivery::CONFIG_LIVE_ACK_TIMEOUT;
293                    let project = view
294                        .pending
295                        .as_ref()
296                        .or(view.active.as_ref())
297                        .and_then(|view| view.project_id.clone());
298                    let selected = view
299                        .pending
300                        .as_ref()
301                        .or(view
302                            .active
303                            .as_ref()
304                            .filter(|_| view.declaration_pending.is_some()))
305                        .and_then(|view| view.attempt.map(|attempt| (view.generation, attempt)));
306                    let writing_project = project.clone();
307                    let window = runtime
308                        .on_blocking(move |owner| {
309                            if active {
310                                if let Some((generation, attempt)) = selected {
311                                    owner.delivery_write_started_for(
312                                        connection,
313                                        writing_project.as_deref(),
314                                        generation,
315                                        attempt,
316                                        tokio::time::Instant::now(),
317                                    )?;
318                                }
319                            }
320                            owner.delivery_window_for(connection, writing_project.as_deref())
321                        })
322                        .await
323                        .map_err(|error| {
324                            RouterError::backend(0, frame.header.corr, error.to_string())
325                        })?;
326                    let write_deadline = window
327                        .filter(|window| selected == Some((window.generation, window.attempt)))
328                        .and_then(|window| window.deadline)
329                        .map_or(
330                            tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT,
331                            |deadline| {
332                                deadline.min(tokio::time::Instant::now() + CONFIG_LIVE_ACK_TIMEOUT)
333                            },
334                        );
335                    if view.active.as_ref().is_some_and(|view| {
336                        view.project_id.is_some()
337                            && view.status == subc_protocol::config::ConfigStatus::Unstamped
338                    }) && !self.config_delivery_target_current(
339                        &registration.manifest.module_id,
340                        connection,
341                        active,
342                        frame.header.corr,
343                    )? {
344                        return Ok(vec![]);
345                    }
346                    drop(module_guard.take());
347                    let flushed =
348                        tokio::time::timeout_at(write_deadline, ctx.egress.send_flushed(response))
349                            .await;
350                    let flushed_at = tokio::time::Instant::now();
351                    let _gate = gate.lock().await;
352                    let current_project = project.clone();
353                    let current_window = runtime
354                        .on_blocking(move |owner| {
355                            owner.delivery_window_for(connection, current_project.as_deref())
356                        })
357                        .await
358                        .ok()
359                        .flatten();
360                    // A slow writer may finish after cutover or supersession.
361                    // Its receipt must not advance the replacement's attempt.
362                    if !self.config_delivery_target_current(
363                        &registration.manifest.module_id,
364                        connection,
365                        active,
366                        frame.header.corr,
367                    )? || selected.is_some_and(|selected| {
368                        current_window
369                            .is_none_or(|window| selected != (window.generation, window.attempt))
370                    }) {
371                        return Ok(vec![]);
372                    }
373                    match flushed {
374                        Ok(Ok(())) => {}
375                        failed => {
376                            if active {
377                                if let Some((generation, attempt)) = selected {
378                                    let module = registration.manifest.module_id.clone();
379                                    let _ = config_work(
380                                        runtime.clone(),
381                                        ConfigWake::Delivery,
382                                        move |owner| {
383                                            owner.delivery_timeout_for(
384                                                connection, &module, project, generation, attempt,
385                                            )
386                                        },
387                                    )
388                                    .await;
389                                }
390                            }
391                            return match failed {
392                                Ok(Err(error)) => Err(error),
393                                _ => Ok(vec![]),
394                            };
395                        }
396                    }
397                    let module = registration.manifest.module_id.clone();
398                    let delivered = config_work(runtime.clone(), ConfigWake::None, move |owner| {
399                        owner.module_view_delivered(connection, &module, &view, flushed_at, active)
400                    })
401                    .await;
402                    if let Err(error) = delivered {
403                        if matches!(
404                            error.code.as_str(),
405                            "delivery_superseded" | "not_delivery_target"
406                        ) {
407                            return Ok(vec![]);
408                        }
409                        if error.code == "delivery_expired" {
410                            if active {
411                                if let Some((generation, attempt)) = selected {
412                                    let module = registration.manifest.module_id.clone();
413                                    let _ = config_work(
414                                        runtime.clone(),
415                                        ConfigWake::Delivery,
416                                        move |owner| {
417                                            owner.delivery_timeout_for(
418                                                connection, &module, project, generation, attempt,
419                                            )
420                                        },
421                                    )
422                                    .await;
423                                }
424                            }
425                        } else {
426                            return Err(RouterError::backend(
427                                0,
428                                frame.header.corr,
429                                error.to_string(),
430                            ));
431                        }
432                    }
433                    Ok(vec![])
434                } else {
435                    Ok(vec![response])
436                }
437            }
438            Err(error) => {
439                if error.code == "anchor_pending" {
440                    let _ = config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
441                        owner.anchor_pending_served(connection)
442                    })
443                    .await;
444                }
445                Ok(vec![config_error_frame(&frame, error)?])
446            }
447        }
448    }
449    pub(super) fn capabilities_with_settings(&self) -> Vec<String> {
450        let mut capabilities = self.subc_capabilities.to_vec();
451        if CONFIG_SETTINGS_SURFACE_ENABLED {
452            if let Some(owner) = &self.config_runtime {
453                capabilities.push(subc_control::config::CONFIG_SETTINGS_CAPABILITY.to_owned());
454                if owner.project_settings_enabled() {
455                    capabilities
456                        .push(subc_control::config::CONFIG_SETTINGS_PROJECTS_CAPABILITY.to_owned());
457                }
458            }
459        }
460        capabilities
461    }
462
463    pub fn with_config_runtime(
464        mut self,
465        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
466    ) -> Self {
467        self.supervisor.install_binding_retirement(&runtime);
468        let _ = runtime.set_activity(self.activity.clone());
469        runtime.install_module_route_authority(Arc::new(route_policy::ModuleRouteAuthority(
470            self.clone(),
471            Arc::downgrade(&runtime),
472        )));
473        runtime.install_mark_publisher(Arc::new(caller_attestation::ControlMarkPublisher(
474            self.clone(),
475        )));
476        self.config_runtime = Some(runtime);
477        self
478    }
479
480    /// Only bootstrap's explicit store-root path advertises configuration authority.
481    pub(crate) fn with_explicit_config_store(
482        self,
483        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
484    ) -> Self {
485        let mut handler = self.with_config_runtime(runtime);
486        let capability = subc_protocol::config::CONFIG_GATE_CAPABILITY;
487        if !handler
488            .subc_capabilities
489            .iter()
490            .any(|present| present == capability)
491        {
492            let mut capabilities = handler.subc_capabilities.to_vec();
493            capabilities.push(capability.to_owned());
494            handler.subc_capabilities = capabilities.into();
495        }
496        handler
497    }
498
499    async fn config_desktop_identity(
500        &self,
501        connection: ConnectionId,
502    ) -> std::result::Result<bool, GateError> {
503        if !self.config_owner_connection(connection) {
504            return Ok(false);
505        }
506        #[cfg(feature = "dev-desktop-approval")]
507        {
508            // Requesting and receiving the complete immutable review is the
509            // development caller's desktop presentation, not app attestation.
510            Ok(self
511                .local_connections
512                .lock()
513                .unwrap_or_else(|p| p.into_inner())
514                .contains(&connection))
515        }
516        #[cfg(not(feature = "dev-desktop-approval"))]
517        {
518            Ok(self.has_current_config_desktop_stamp(connection).await)
519        }
520    }
521
522    pub(crate) fn config_desktop_review_request(&self, request: &Frame) -> bool {
523        self.config_runtime.is_some()
524            && request.header.ty == FrameType::Request
525            && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
526                matches!(
527                    probe.op.as_str(),
528                    "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
529                )
530            })
531    }
532
533    pub(crate) async fn config_desktop_review_response(
534        &self,
535        connection: ConnectionId,
536        response: &Frame,
537    ) -> Option<subc_control::config::ConfigPlanView> {
538        if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
539            return None;
540        }
541        let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
542        if !matches!(
543            probe.op.as_str(),
544            "config.plan"
545                | "config.plan_get"
546                | "config.stamp"
547                | "config.unstamp"
548                | "config.rollback"
549        ) || !matches!(self.config_desktop_identity(connection).await, Ok(true))
550        {
551            return None;
552        }
553        match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
554            ConfigControlResponse::Plan { view }
555            | ConfigControlResponse::PlanGet { view }
556            | ConfigControlResponse::Stamp { view }
557            | ConfigControlResponse::Unstamp { view }
558            | ConfigControlResponse::Rollback { view } => Some(view),
559            _ => None,
560        }
561    }
562
563    pub(crate) async fn config_desktop_review_delivered(
564        &self,
565        connection: ConnectionId,
566        view: subc_control::config::ConfigPlanView,
567    ) {
568        if !matches!(self.config_desktop_identity(connection).await, Ok(true)) {
569            return;
570        }
571        let Some(runtime) = self.config_runtime.clone() else {
572            return;
573        };
574        let peers = self.captured_peers.clone();
575        let _ = config_work(runtime, ConfigWake::Delivery, move |owner| {
576            owner.desktop_view_delivered_when(connection, &view, || {
577                peers
578                    .lock()
579                    .unwrap_or_else(|p| p.into_inner())
580                    .contains_key(&connection)
581            })
582        })
583        .await;
584    }
585
586    pub(crate) async fn deliver_config_desktop_review(
587        &self,
588        ctx: &RouteCtx,
589        response: Frame,
590        view: subc_control::config::ConfigPlanView,
591    ) -> Result<(), RouterError> {
592        ctx.egress.send_flushed(response).await?;
593        self.config_desktop_review_delivered(ctx.connection_id, view)
594            .await;
595        Ok(())
596    }
597
598    pub fn with_config_review_admission(
599        mut self,
600        admission: Arc<dyn crate::config_gate::ReviewAdmission>,
601    ) -> Self {
602        self.config_review_admission = admission;
603        self.config_review_admission_is_default = false;
604        self
605    }
606
607    pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
608        if self.config_runtime.is_some() && self.config_review_admission_is_default {
609            Arc::new(admission::SupervisedReviewAdmission(self.clone()))
610        } else {
611            self.config_review_admission.clone()
612        }
613    }
614
615    /// Config operations are channel-0 only, so callers are unscoped. Scoped
616    /// access rules must be enforced if a scoped path to these operations is added.
617    pub(super) async fn handle_config_gate_request(
618        &self,
619        ctx: &RouteCtx,
620        frame: Frame,
621    ) -> Result<Vec<Frame>, RouterError> {
622        let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
623            Ok(request) => request,
624            Err(error) => {
625                return Ok(vec![control_error_frame(
626                    &frame,
627                    "invalid_control_body",
628                    format!("malformed config control body: {error}"),
629                )?])
630            }
631        };
632        debug_assert!(privileged_operation(&request).is_none());
633        let Some(runtime) = self.config_runtime.clone() else {
634            return Ok(vec![control_error_frame(
635                &frame,
636                "config_gate_inactive",
637                "no config store configured",
638            )?]);
639        };
640        if !self.config_owner_connection(ctx.connection_id) {
641            return Ok(vec![control_error_frame(
642                &frame,
643                "owner_required",
644                "configuration control requires a kernel-observed owner-user connection",
645            )?]);
646        }
647        if let ConfigControlRequest::Watch { modules, projects } = request {
648            let projects = projects == Some(true) && runtime.project_settings_enabled();
649            return self
650                .handle_config_settings_watch(ctx, frame, runtime, modules, projects)
651                .await;
652        }
653        let result = self
654            .execute_config_request(ctx, &frame, runtime, request)
655            .await;
656        match result {
657            Ok(response) => Ok(vec![control_response_body_frame(
658                &frame,
659                &response,
660                "ConfigControlResponse",
661            )?]),
662            Err(error) => Ok(vec![config_error_frame(&frame, error)?]),
663        }
664    }
665
666    pub(super) fn config_owner_connection(&self, connection: ConnectionId) -> bool {
667        let peers = self
668            .observed_peers
669            .lock()
670            .unwrap_or_else(|p| p.into_inner());
671        let Some(peer) = peers.get(&connection) else {
672            return false;
673        };
674        #[cfg(unix)]
675        {
676            peer.uid == Some(subc_os::effective_uid())
677        }
678        #[cfg(windows)]
679        {
680            subc_os::named_pipe::current_user_sid_string()
681                .ok()
682                .as_ref()
683                .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
684        }
685        #[cfg(not(any(unix, windows)))]
686        {
687            let _ = peer;
688            false
689        }
690    }
691
692    async fn execute_config_request(
693        &self,
694        ctx: &RouteCtx,
695        frame: &Frame,
696        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
697        request: ConfigControlRequest,
698    ) -> std::result::Result<ConfigControlResponse, GateError> {
699        match request {
700            ConfigControlRequest::Modules {} => {
701                let known = self.config_settings_known_modules()?;
702                config_work(runtime, ConfigWake::None, move |owner| {
703                    owner.settings_modules(known)
704                })
705                .await
706            }
707            ConfigControlRequest::Schema { module_id } => {
708                let known = self.config_settings_known_modules()?;
709                config_work(runtime, ConfigWake::None, move |owner| {
710                    owner.settings_schema(known, module_id)
711                })
712                .await
713            }
714            ConfigControlRequest::Show {
715                module_id,
716                project_id,
717                through,
718            } => {
719                let known = self.config_settings_known_modules()?;
720                if let Some(project) = project_id {
721                    return runtime
722                        .settings_show_project(known, module_id, project, through)
723                        .await;
724                }
725                config_work(runtime, ConfigWake::None, move |owner| {
726                    owner.settings_show(known, module_id, through)
727                })
728                .await
729            }
730            ConfigControlRequest::PlanGet { digest } => {
731                let view = config_work(runtime, ConfigWake::None, move |owner| {
732                    owner.plan_get(&digest)
733                })
734                .await?;
735                Ok(ConfigControlResponse::PlanGet { view })
736            }
737            ConfigControlRequest::PlanDiscard { digest } => {
738                config_work(runtime, ConfigWake::Delivery, move |owner| {
739                    owner.plan_discard(&digest)
740                })
741                .await?;
742                Ok(ConfigControlResponse::PlanDiscard {})
743            }
744            ConfigControlRequest::PlaceProgram {
745                module_id,
746                path,
747                sha256,
748                manifest,
749            } => {
750                let gate = runtime.module_gate(&module_id)?;
751                let _guard = gate.lock().await;
752                let generation = config_work(runtime, ConfigWake::Delivery, move |owner| {
753                    owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
754                })
755                .await?;
756                Ok(ConfigControlResponse::ProgramPlaced { generation })
757            }
758            ConfigControlRequest::Status {} => {
759                let snapshot = runtime.polled_snapshot()?;
760                let mut status = runtime.polled_status_from(snapshot.clone()).await?;
761                let phone = self
762                    .config_phone_surface_checked(false, Some(&snapshot))
763                    .await;
764                let facts = self.config_approval_facts_with_phone(ctx, phone).await;
765                status
766                    .missing_approval_surfaces
767                    .extend(crate::config_gate::missing_surfaces(
768                        &facts,
769                        matches!(status.state.as_str(), "store_missing" | "store_unverified"),
770                    ));
771                self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
772                    .await?;
773                if let Some(problem) = runtime
774                    .on_blocking(move |owner| {
775                        Ok(owner.policy_root_problem(&snapshot.approved_daemon))
776                    })
777                    .await?
778                {
779                    status.warnings.push(problem);
780                }
781                Ok(ConfigControlResponse::Status { status })
782            }
783            ConfigControlRequest::History {} => {
784                let (generations, pruned) =
785                    config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
786                Ok(ConfigControlResponse::History {
787                    generations,
788                    pruned,
789                })
790            }
791            ConfigControlRequest::Apply { digest } => {
792                if let Some(result) = self
793                    .apply_unstamped_policy_root(ctx, frame, &runtime, &digest)
794                    .await?
795                {
796                    return Ok(result);
797                }
798                let apply_digest = digest.clone();
799                if let Some(generation) = runtime.apply_control_edits(apply_digest).await? {
800                    return Ok(ConfigControlResponse::Applied {
801                        generation,
802                        restart_required: false,
803                    });
804                }
805                let connection = ctx.connection_id;
806                let corr = frame.header.corr;
807                #[cfg(all(test, unix))]
808                runtime.pause_approval_claim_for_test().await;
809                let request_guard = runtime.claim_approval_request(connection, corr)?;
810                if self.rescan.is_none() {
811                    return Err(GateError::new(
812                        "supervisor_reconcile_unavailable",
813                        "configuration commit requires the supervisor owner",
814                    ));
815                }
816                let facts = self.config_approval_facts(ctx).await;
817                let cancellation = request_guard.request.clone();
818                let (challenge, mut attempt_guard) =
819                    config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
820                        let challenge = owner.begin_approval_for_request(
821                            &digest,
822                            &facts,
823                            Some(&cancellation),
824                        )?;
825                        // The job owns slot cleanup even if its async caller drops
826                        // before this blocking result can be delivered.
827                        let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
828                        owner.track_reserved_approval_request(
829                            challenge.attempt(),
830                            connection,
831                            corr,
832                            &cancellation,
833                        )?;
834                        Ok((challenge, guard))
835                    })
836                    .await?;
837                request_guard.request.ensure_live()?;
838                let reply = match &challenge {
839                    ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
840                        ApprovalReply::Presence(
841                            self.confirm_config_gate_presence(ctx, frame, &challenge)
842                                .await,
843                        )
844                    }
845                    ApprovalChallenge::Phone {
846                        attempt,
847                        connection,
848                        deadline,
849                        request,
850                    } => {
851                        self.config_phone_rpc(
852                            &runtime,
853                            *attempt,
854                            ConnectionId::new(*connection),
855                            *deadline,
856                            request,
857                        )
858                        .await?
859                    }
860                };
861                let attempt = challenge.attempt();
862                let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
863                    Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
864                        Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
865                    ))
866                });
867                attempt_guard.commit_window = window.clone();
868                let checked_phone = self.config_phone_surface().await;
869                let locks = async {
870                    // A registry root can keep its worker busy until the I/O
871                    // returns. Do not hold supervisor or module gates while
872                    // waiting for that registry check.
873                    let project_apply = runtime.recheck_capture_apply(attempt).await?;
874                    let operation = self.supervisor.operation_lock().lock_owned().await;
875                    let module_gates = runtime.approval_commit_gates(attempt).await?;
876                    let current_phone = self.config_phone_surface_snapshot().await;
877                    let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
878                    let facts = self.config_approval_facts_with_phone(ctx, phone).await;
879                    Ok::<_, GateError>((operation, module_gates, facts, project_apply))
880                };
881                let (operation, module_gates, facts, project_apply) = if let Some(window) = &window
882                {
883                    timeout_at(window.deadline, locks)
884                        .await
885                        .map_err(|_| GateError::commit_timeout())??
886                } else {
887                    locks.await?
888                };
889                let now = now_ms();
890                let publish_window = window.clone();
891                let publication_request = request_guard.request.clone();
892                let exit_runtime = runtime.clone();
893                let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
894                    let _owned_gates = (operation, module_gates);
895                    let write_authority = project_apply.clone();
896                    let generation = owner.finish_approval_with_commit_window(
897                        attempt,
898                        &facts,
899                        reply,
900                        now,
901                        publish_window,
902                        publication_request,
903                        project_apply,
904                    )?;
905                    if let Some(authority) = write_authority {
906                        // The publication job can finish after the control
907                        // request disconnects. It still owns this write-back.
908                        tokio::spawn(async move {
909                            owner
910                                .write_approved_project_files(generation, authority)
911                                .await
912                        });
913                    }
914                    Ok(generation)
915                });
916                tokio::pin!(work);
917                let generation = if let Some(window) = window {
918                    tokio::select! {
919                        result = &mut work => result?,
920                        _ = tokio::time::sleep_until(window.deadline) => {
921                            if window.expire() { return Err(GateError::commit_timeout()); }
922                            work.await?
923                        }
924                    }
925                } else {
926                    work.await?
927                };
928                let approval_runtime = exit_runtime.clone();
929                if let Some(approval) =
930                    config_work(approval_runtime, ConfigWake::None, move |owner| {
931                        owner.development_approval(generation)
932                    })
933                    .await?
934                {
935                    self.publish_development_approval(&approval);
936                    return Ok(ConfigControlResponse::Applied {
937                        generation,
938                        restart_required: false,
939                    });
940                }
941                #[cfg(test)]
942                self.pause_before_apply_reconcile_for_test().await;
943                self.reconcile_authority_exit(exit_runtime.clone(), generation)
944                    .await?;
945                let restart_required = self
946                    .daemon_restart_required(&exit_runtime, generation)
947                    .await?;
948                Ok(ConfigControlResponse::Applied {
949                    generation,
950                    restart_required,
951                })
952            }
953            request => {
954                let (kind, edits) = match request {
955                    ConfigControlRequest::Plan {
956                        base_generations,
957                        edits,
958                    } => {
959                        if edits.is_none() && base_generations.is_some() {
960                            return Err(GateError::new(
961                                "invalid_params",
962                                "base_generations requires edits",
963                            ));
964                        }
965                        let edits = edits
966                            .map(|edits| {
967                                base_generations.map(|base| (base, edits)).ok_or_else(|| {
968                                    GateError::new(
969                                        "invalid_params",
970                                        "edits requires base_generations",
971                                    )
972                                })
973                            })
974                            .transpose()?;
975                        (PlanKind::Change, edits)
976                    }
977                    ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
978                    ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
979                    ConfigControlRequest::Rollback { generation } => {
980                        (PlanKind::Rollback(generation), None)
981                    }
982                    _ => {
983                        return Err(GateError::new(
984                            "unsupported_control_frame",
985                            "unknown configuration operation",
986                        ))
987                    }
988                };
989                let mut prepared = match edits {
990                    Some((base, edits)) => runtime.prepare_control_edits(base, edits).await?,
991                    None => {
992                        let prepared = runtime.prepare_capture(kind).await?;
993                        // Preparing a plan can record observations that delivery reads.
994                        runtime.notify_delivery_changed();
995                        prepared
996                    }
997                };
998                if prepared.capture_refused() {
999                    let view = config_work(runtime, ConfigWake::None, move |owner| {
1000                        owner.capture_refusal(&prepared)?.ok_or_else(|| {
1001                            GateError::new("module_review_invalid", "project refusal is absent")
1002                        })
1003                    })
1004                    .await?;
1005                    return Ok(ConfigControlResponse::Plan { view });
1006                }
1007                let mut fields = Vec::new();
1008                let mut edit_refusals = Vec::new();
1009                let mut unavailable_rereviews = Vec::new();
1010                for (module, captured) in &prepared.candidate.modules {
1011                    if !prepared.review_modules.contains(module) {
1012                        continue;
1013                    }
1014                    let base = prepared.bases.get(module);
1015                    let reply = self
1016                        .review_config_tuple(&runtime, module, base, &captured.view)
1017                        .await;
1018                    let reply = match reply {
1019                        Ok(reply) => reply,
1020                        // A re-review the new program cannot answer now stays
1021                        // pending in status; it does not hold up this plan.
1022                        Err(_) if prepared.rereview_modules.contains(module) => {
1023                            unavailable_rereviews.push(module.clone());
1024                            continue;
1025                        }
1026                        Err(error) => return Err(error),
1027                    };
1028                    let reply: subc_protocol::config::ConfigReviewReply =
1029                        serde_json::from_slice(&reply).map_err(|_| {
1030                            GateError::new(
1031                                "module_review_invalid",
1032                                format!("{module}: malformed config.review reply"),
1033                            )
1034                        })?;
1035                    if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1036                        let before = edit_refusals.len();
1037                        for refusal in &reply.refusals {
1038                            for path in refusal
1039                                .paths
1040                                .iter()
1041                                .filter(|path| path.starts_with('/') && path.len() <= 1024)
1042                            {
1043                                edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1044                                    module_id: module.clone(),
1045                                    path: path.clone(),
1046                                    code: "module_review_refused".into(),
1047                                    message: "the module refused this field".into(),
1048                                    project_id: None,
1049                                    workspace_id: None,
1050                                });
1051                            }
1052                        }
1053                        if edit_refusals.len() == before {
1054                            edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1055                                module_id: module.clone(),
1056                                path: String::new(),
1057                                code: "module_review_refused".into(),
1058                                message: "the module refused the edits".into(),
1059                                project_id: None,
1060                                workspace_id: None,
1061                            });
1062                        }
1063                        fields.extend(prepared.refused_fields(module)?);
1064                        continue;
1065                    }
1066                    fields.extend(crate::config_gate::review::checked_fields(
1067                        module,
1068                        &captured.schema,
1069                        base,
1070                        prepared.base_schemas.get(module),
1071                        &captured.view,
1072                        reply,
1073                    )?);
1074                }
1075                for module in unavailable_rereviews {
1076                    prepared.review_modules.remove(&module);
1077                    prepared.rereview_modules.remove(&module);
1078                }
1079                let mut project_replies = Vec::new();
1080                for (tuple, review) in prepared.project_reviews() {
1081                    let bytes = self
1082                        .review_config_tuple(
1083                            &runtime,
1084                            &tuple.module,
1085                            review.base.as_ref(),
1086                            &review.approval.view,
1087                        )
1088                        .await?;
1089                    let reply: subc_protocol::config::ConfigReviewReply =
1090                        serde_json::from_slice(&bytes).map_err(|_| {
1091                            GateError::new(
1092                                "module_review_invalid",
1093                                format!("{}: malformed project config.review reply", tuple.module),
1094                            )
1095                        })?;
1096                    project_replies.push((tuple.clone(), reply));
1097                }
1098                for (tuple, reply) in project_replies {
1099                    if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1100                        prepared.refuse_project_review(&tuple, &reply);
1101                    } else {
1102                        fields.extend(prepared.accept_project_review(&tuple, reply)?);
1103                    }
1104                }
1105                if prepared.capture_refused() {
1106                    let view = runtime
1107                        .on_blocking(move |owner| {
1108                            owner.capture_refusal(&prepared)?.ok_or_else(|| {
1109                                GateError::new("module_review_invalid", "project refusal is absent")
1110                            })
1111                        })
1112                        .await?;
1113                    return Ok(ConfigControlResponse::Plan { view });
1114                }
1115                prepared.add_edit_refusals(edit_refusals);
1116                let view = config_work(runtime, ConfigWake::Delivery, move |owner| {
1117                    owner.finish_plan(prepared, move |old, new| {
1118                        let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1119                        changeset.fields = fields;
1120                        let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1121                        for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1122                            let kind = serde_json::to_value(field.apply).map_err(|_| GateError::new("schema_invalid", "could not encode apply kind"))?.as_str().ok_or_else(|| GateError::new("schema_invalid","apply kind is not a string"))?.to_owned();
1123                            effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1124                        }
1125                        if changeset.fields.iter().any(|field| field.project_id.is_none() && field.apply != subc_config::ApplyKind::Live) {
1126                            changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1127                        }
1128                        Ok(changeset)
1129                    })
1130                })
1131                .await?;
1132                Ok(match kind {
1133                    PlanKind::Change => ConfigControlResponse::Plan { view },
1134                    PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1135                    PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1136                    PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1137                })
1138            }
1139        }
1140    }
1141
1142    async fn review_config_tuple(
1143        &self,
1144        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1145        module: &str,
1146        base: Option<&subc_protocol::config::ConfigView>,
1147        candidate: &subc_protocol::config::ConfigView,
1148    ) -> Result<Vec<u8>, GateError> {
1149        #[cfg(test)]
1150        if let Some(reply) = &self.config_review_test_reply {
1151            return serde_json::to_vec(reply).map_err(|_| {
1152                GateError::new(
1153                    "module_review_invalid",
1154                    "could not encode the fixture review",
1155                )
1156            });
1157        }
1158        let registration = self
1159            .registry
1160            .get_module(module)
1161            .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1162            .ok_or_else(|| {
1163                GateError::new(
1164                    "module_review_unavailable",
1165                    format!("{module}: no active reviewer"),
1166                )
1167            })?;
1168        let admission = self.review_admission();
1169        let reviewer = registration.clone();
1170        config_work(runtime.clone(), ConfigWake::None, move |_| {
1171            admission.check(&reviewer)
1172        })
1173        .await?;
1174        if !registration
1175            .control_ops
1176            .iter()
1177            .any(|op| op == "config.review")
1178        {
1179            return Err(GateError::new(
1180                "module_review_unavailable",
1181                format!("{module}: config.review is not opted in"),
1182            ));
1183        }
1184        let request = subc_protocol::config::ConfigReviewRequest::new(
1185            base.map_or(0, |view| view.generation),
1186            candidate.layers.clone(),
1187            base.cloned(),
1188        );
1189        let bytes = serde_json::to_vec(&request).map_err(|_| {
1190            GateError::new("config_unavailable", "could not encode immutable review")
1191        })?;
1192        self.config_rpc(
1193            runtime,
1194            module,
1195            registration.connection_id,
1196            "config.review",
1197            bytes,
1198        )
1199        .await
1200    }
1201
1202    async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1203        let phone = self.config_phone_surface().await;
1204        self.config_approval_facts_with_phone(ctx, phone).await
1205    }
1206
1207    async fn config_approval_facts_with_phone(
1208        &self,
1209        ctx: &RouteCtx,
1210        phone: Option<crate::config_gate::PhoneSurface>,
1211    ) -> ApprovalFacts {
1212        let os_policy = crate::config_gate::os_prompt_policy_present();
1213        #[cfg(any(test, feature = "test-support"))]
1214        let os_policy = os_policy
1215            || self
1216                .config_runtime
1217                .as_ref()
1218                .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1219        let desktop = self
1220            .config_desktop_identity(ctx.connection_id)
1221            .await
1222            .unwrap_or(false);
1223        ApprovalFacts {
1224            connection: ctx.connection_id.get(),
1225            owner_uid: self.config_owner_connection(ctx.connection_id),
1226            desktop_app: desktop,
1227            attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1228            os_prompt_available: config_os_prompt_available(
1229                self.forwarding.operator_confirms().config_gate_ready(),
1230                os_policy,
1231            ),
1232            phone,
1233            caller: self.resolve_caller(ctx.connection_id).await,
1234        }
1235    }
1236
1237    // The caller holds Callosum's module gate while allocating its RPC or
1238    // committing approval. This snapshot grants nothing until revalidated there.
1239    async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1240        self.config_phone_surface_checked(true, None).await
1241    }
1242
1243    async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1244        self.config_phone_surface_checked(false, None).await
1245    }
1246
1247    async fn config_phone_surface_checked(
1248        &self,
1249        content: bool,
1250        publication: Option<&crate::config_gate::runtime::Published>,
1251    ) -> Option<crate::config_gate::PhoneSurface> {
1252        if self.config_runtime.as_ref().is_some_and(|owner| {
1253            publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1254        }) {
1255            return None;
1256        }
1257        if !self.operator_app_policy.phone_enabled {
1258            return None;
1259        }
1260        let runtime = self.config_runtime.as_ref()?;
1261        let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1262        let (registration, verified) = registrations
1263            .into_iter()
1264            .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1265        if !verified
1266            || !registration.ready
1267            || !registration
1268                .control_ops
1269                .iter()
1270                .any(|op| op == subc_protocol::consent::CONSENT_V1)
1271        {
1272            return None;
1273        }
1274        let _spawn = self
1275            .supervisor
1276            .registration_spawn(registration.connection_id)?;
1277        if !self
1278            .forwarding
1279            .active_module_endpoint("callosum")
1280            .ok()
1281            .flatten()
1282            .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1283        {
1284            return None;
1285        }
1286        // Configuration approval requires a channel-bound phone launch.
1287        // Enabling configuration gating invalidates legacy launch nonces,
1288        // including an old registration whose process is still draining.
1289        let module = self.supervisor.get("callosum")?;
1290        let status = module.status().ok()?;
1291        let (spec, _) = module.configuration().ok()?;
1292        if !self.supervisor.registration_snapshot_is_current_live(
1293            &self.registry,
1294            "callosum",
1295            registration.connection_id,
1296            None,
1297        ) || !spec.reserved
1298            || !status.enabled
1299            || !status.process_alive
1300            || !status.registration_active
1301        {
1302            return None;
1303        }
1304        let connection = registration.connection_id;
1305        let approved = if content {
1306            runtime
1307                .on_blocking(move |owner| owner.approved_phone_entry(connection))
1308                .await
1309                .ok()??
1310        } else {
1311            if let Some(snapshot) = publication {
1312                runtime.polled_phone_entry_from(snapshot, connection)?
1313            } else {
1314                runtime.polled_phone_entry(connection)?
1315            }
1316        };
1317        if !approved.enabled || approved.module_spec() != spec {
1318            return None;
1319        }
1320        if content {
1321            let supervisor = self.supervisor.clone();
1322            let registry = self.registry.clone();
1323            if !runtime
1324                .on_blocking(move |_| {
1325                    Ok(supervisor
1326                        .registration_is_current_live(&registry, "callosum", connection, None))
1327                })
1328                .await
1329                .ok()?
1330            {
1331                return None;
1332            }
1333        }
1334        if !self.supervisor.registration_snapshot_is_current_live(
1335            &self.registry,
1336            "callosum",
1337            registration.connection_id,
1338            None,
1339        ) {
1340            return None;
1341        }
1342        Some(crate::config_gate::PhoneSurface {
1343            module_id: "callosum".into(),
1344            connection: connection.get(),
1345            spawn_generation: status.spawn_generation,
1346            enabled_by_policy: true,
1347            opted_in: true,
1348            approved_declaration: true,
1349            reserved: true,
1350            channel_registered: true,
1351            program_admitted: true,
1352            active_registration: true,
1353        })
1354    }
1355
1356    async fn config_rpc(
1357        &self,
1358        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1359        module: &str,
1360        expected_connection: ConnectionId,
1361        op: &str,
1362        bytes: Vec<u8>,
1363    ) -> std::result::Result<Vec<u8>, GateError> {
1364        let gate = runtime.module_gate(module)?;
1365        let pending = {
1366            let _gate = gate.lock().await;
1367            let registration = self
1368                .registry
1369                .get_module(module)
1370                .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1371                .ok_or_else(|| {
1372                    GateError::new(
1373                        "module_review_unavailable",
1374                        format!("{module}: no active target"),
1375                    )
1376                })?;
1377            let pending = self
1378                .forwarding
1379                .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1380                .map_err(|_| {
1381                    GateError::new(
1382                        "module_review_unavailable",
1383                        format!("{module}: target unavailable"),
1384                    )
1385                })?;
1386            if pending.endpoint.connection_id != registration.connection_id
1387                || registration.connection_id != expected_connection
1388            {
1389                let _ = self
1390                    .forwarding
1391                    .cancel_module_control_rpc(pending.endpoint, pending.corr);
1392                return Err(GateError::new(
1393                    "not_delivery_target",
1394                    "registry and forwarding targets differ",
1395                ));
1396            }
1397            pending
1398        };
1399        let PendingModuleControlRpc {
1400            endpoint,
1401            module_sink,
1402            negotiated_ver,
1403            corr,
1404            receiver,
1405        } = pending;
1406        let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1407        let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1408        let frame = Frame::build_with_version(
1409            negotiated_ver,
1410            FrameType::Request,
1411            control_flags(),
1412            0,
1413            0,
1414            corr,
1415            bytes,
1416        )
1417        .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1418        timeout_at(deadline, module_sink.send(frame))
1419            .await
1420            .map_err(|_| {
1421                GateError::new(
1422                    "config_review_timeout",
1423                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1424                )
1425            })?
1426            .map_err(|_| {
1427                GateError::new(
1428                    "module_review_unavailable",
1429                    format!("{module}: target disconnected"),
1430                )
1431            })?;
1432        let outcome = timeout_at(deadline, receiver)
1433            .await
1434            .map_err(|_| {
1435                GateError::new(
1436                    "config_review_timeout",
1437                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1438                )
1439            })?
1440            .map_err(|_| {
1441                GateError::new(
1442                    "module_review_unavailable",
1443                    format!("{module}: target disconnected"),
1444                )
1445            })?;
1446        guard.disarm();
1447        match outcome {
1448            ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1449            ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1450            _ => Err(GateError::new(
1451                "module_review_unavailable",
1452                format!("{module}: config request was not answered"),
1453            )),
1454        }
1455    }
1456
1457    /// Execute only the presence part of an engine-selected challenge. The
1458    /// runtime owner still rechecks the inputs and surface before committing.
1459    pub async fn confirm_config_gate_presence(
1460        &self,
1461        ctx: &RouteCtx,
1462        frame: &Frame,
1463        challenge: &ApprovalChallenge,
1464    ) -> PresenceDecision {
1465        let Some(text) = challenge.prompt() else {
1466            return PresenceDecision::Unavailable;
1467        };
1468        let caller = self.resolve_caller(ctx.connection_id).await;
1469        let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1470        // Neither privileged_operator_prompt nor operator-app shortcut policy
1471        // is consulted: every desktop gate review requires OS presence.
1472        let outcome = self
1473            .forwarding
1474            .operator_confirms()
1475            .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1476            .await;
1477        PresenceDecision::from_operator_outcome(&outcome)
1478    }
1479}
1480
1481fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1482    provider_ready && policy_present
1483}
1484
1485enum ConfigWake {
1486    None,
1487    Delivery,
1488}
1489
1490async fn config_work<T: Send + 'static>(
1491    runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1492    wake: ConfigWake,
1493    work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1494        + Send
1495        + 'static,
1496) -> std::result::Result<T, GateError> {
1497    runtime
1498        .on_blocking(move |owner| {
1499            let result = work(owner.clone());
1500            if matches!(wake, ConfigWake::Delivery) {
1501                owner.notify_delivery_changed();
1502            }
1503            result
1504        })
1505        .await
1506}
1507
1508pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1509    control_error_body_frame(
1510        frame,
1511        ErrorBody {
1512            code: error.code,
1513            message: error.detail,
1514            detail: None,
1515        },
1516    )
1517}
1518
1519pub(super) fn now_ms() -> u64 {
1520    std::time::SystemTime::now()
1521        .duration_since(std::time::UNIX_EPOCH)
1522        .unwrap_or_default()
1523        .as_millis()
1524        .min(u128::from(u64::MAX)) as u64
1525}
1526
1527#[cfg(test)]
1528mod tests;
1529
1530#[cfg(test)]
1531mod desktop_tests;