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 fn with_config_runtime(
450        mut self,
451        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
452    ) -> Self {
453        self.supervisor.install_binding_retirement(&runtime);
454        let _ = runtime.set_activity(self.activity.clone());
455        runtime.install_module_route_authority(Arc::new(route_policy::ModuleRouteAuthority(
456            self.clone(),
457            Arc::downgrade(&runtime),
458        )));
459        runtime.install_mark_publisher(Arc::new(caller_attestation::ControlMarkPublisher(
460            self.clone(),
461        )));
462        self.config_runtime = Some(runtime);
463        self
464    }
465
466    /// Only bootstrap's explicit store-root path advertises configuration authority.
467    pub(crate) fn with_explicit_config_store(
468        self,
469        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
470    ) -> Self {
471        let mut handler = self.with_config_runtime(runtime);
472        let capability = subc_protocol::config::CONFIG_GATE_CAPABILITY;
473        if !handler
474            .subc_capabilities
475            .iter()
476            .any(|present| present == capability)
477        {
478            let mut capabilities = handler.subc_capabilities.to_vec();
479            capabilities.push(capability.to_owned());
480            handler.subc_capabilities = capabilities.into();
481        }
482        handler
483    }
484
485    async fn config_desktop_identity(
486        &self,
487        connection: ConnectionId,
488    ) -> std::result::Result<bool, GateError> {
489        if !self.config_owner_connection(connection) {
490            return Ok(false);
491        }
492        #[cfg(feature = "dev-desktop-approval")]
493        {
494            // Requesting and receiving the complete immutable review is the
495            // development caller's desktop presentation, not app attestation.
496            Ok(self
497                .local_connections
498                .lock()
499                .unwrap_or_else(|p| p.into_inner())
500                .contains(&connection))
501        }
502        #[cfg(not(feature = "dev-desktop-approval"))]
503        {
504            Ok(self.has_current_config_desktop_stamp(connection).await)
505        }
506    }
507
508    pub(crate) fn config_desktop_review_request(&self, request: &Frame) -> bool {
509        self.config_runtime.is_some()
510            && request.header.ty == FrameType::Request
511            && serde_json::from_slice::<ControlOpProbe>(&request.body).is_ok_and(|probe| {
512                matches!(
513                    probe.op.as_str(),
514                    "config.plan" | "config.stamp" | "config.unstamp" | "config.rollback"
515                )
516            })
517    }
518
519    pub(crate) async fn config_desktop_review_response(
520        &self,
521        connection: ConnectionId,
522        response: &Frame,
523    ) -> Option<subc_control::config::ConfigPlanView> {
524        if self.config_runtime.is_none() || response.header.ty != FrameType::Response {
525            return None;
526        }
527        let probe: ControlOpProbe = serde_json::from_slice(&response.body).ok()?;
528        if !matches!(
529            probe.op.as_str(),
530            "config.plan"
531                | "config.plan_get"
532                | "config.stamp"
533                | "config.unstamp"
534                | "config.rollback"
535        ) || !matches!(self.config_desktop_identity(connection).await, Ok(true))
536        {
537            return None;
538        }
539        match serde_json::from_slice::<ConfigControlResponse>(&response.body).ok()? {
540            ConfigControlResponse::Plan { view }
541            | ConfigControlResponse::PlanGet { view }
542            | ConfigControlResponse::Stamp { view }
543            | ConfigControlResponse::Unstamp { view }
544            | ConfigControlResponse::Rollback { view } => Some(view),
545            _ => None,
546        }
547    }
548
549    pub(crate) async fn config_desktop_review_delivered(
550        &self,
551        connection: ConnectionId,
552        view: subc_control::config::ConfigPlanView,
553    ) {
554        if !matches!(self.config_desktop_identity(connection).await, Ok(true)) {
555            return;
556        }
557        let Some(runtime) = self.config_runtime.clone() else {
558            return;
559        };
560        let peers = self.captured_peers.clone();
561        let _ = config_work(runtime, ConfigWake::Delivery, move |owner| {
562            owner.desktop_view_delivered_when(connection, &view, || {
563                peers
564                    .lock()
565                    .unwrap_or_else(|p| p.into_inner())
566                    .contains_key(&connection)
567            })
568        })
569        .await;
570    }
571
572    pub(crate) async fn deliver_config_desktop_review(
573        &self,
574        ctx: &RouteCtx,
575        response: Frame,
576        view: subc_control::config::ConfigPlanView,
577    ) -> Result<(), RouterError> {
578        ctx.egress.send_flushed(response).await?;
579        self.config_desktop_review_delivered(ctx.connection_id, view)
580            .await;
581        Ok(())
582    }
583
584    pub fn with_config_review_admission(
585        mut self,
586        admission: Arc<dyn crate::config_gate::ReviewAdmission>,
587    ) -> Self {
588        self.config_review_admission = admission;
589        self.config_review_admission_is_default = false;
590        self
591    }
592
593    pub(super) fn review_admission(&self) -> Arc<dyn crate::config_gate::ReviewAdmission> {
594        if self.config_runtime.is_some() && self.config_review_admission_is_default {
595            Arc::new(admission::SupervisedReviewAdmission(self.clone()))
596        } else {
597            self.config_review_admission.clone()
598        }
599    }
600
601    /// Config operations are channel-0 only, so callers are unscoped. Scoped
602    /// access rules must be enforced if a scoped path to these operations is added.
603    pub(super) async fn handle_config_gate_request(
604        &self,
605        ctx: &RouteCtx,
606        frame: Frame,
607    ) -> Result<Vec<Frame>, RouterError> {
608        let request = match serde_json::from_slice::<ConfigControlRequest>(&frame.body) {
609            Ok(request) => request,
610            Err(error) => {
611                return Ok(vec![control_error_frame(
612                    &frame,
613                    "invalid_control_body",
614                    format!("malformed config control body: {error}"),
615                )?])
616            }
617        };
618        debug_assert!(privileged_operation(&request).is_none());
619        let Some(runtime) = self.config_runtime.clone() else {
620            return Ok(vec![control_error_frame(
621                &frame,
622                "config_gate_inactive",
623                "no config store configured",
624            )?]);
625        };
626        if !self.config_owner_connection(ctx.connection_id) {
627            return Ok(vec![control_error_frame(
628                &frame,
629                "owner_required",
630                "configuration control requires a kernel-observed owner-user connection",
631            )?]);
632        }
633        if let ConfigControlRequest::Watch { modules, projects } = request {
634            let projects = projects == Some(true) && runtime.project_settings_enabled();
635            return self
636                .handle_config_settings_watch(ctx, frame, runtime, modules, projects)
637                .await;
638        }
639        let result = self
640            .execute_config_request(ctx, &frame, runtime, request)
641            .await;
642        match result {
643            Ok(response) => Ok(vec![control_response_body_frame(
644                &frame,
645                &response,
646                "ConfigControlResponse",
647            )?]),
648            Err(error) => Ok(vec![config_error_frame(&frame, error)?]),
649        }
650    }
651
652    pub(super) fn config_owner_connection(&self, connection: ConnectionId) -> bool {
653        let peers = self
654            .observed_peers
655            .lock()
656            .unwrap_or_else(|p| p.into_inner());
657        let Some(peer) = peers.get(&connection) else {
658            return false;
659        };
660        #[cfg(unix)]
661        {
662            peer.uid == Some(subc_os::effective_uid())
663        }
664        #[cfg(windows)]
665        {
666            subc_os::named_pipe::current_user_sid_string()
667                .ok()
668                .as_ref()
669                .is_some_and(|sid| peer.sid.as_ref() == Some(sid))
670        }
671        #[cfg(not(any(unix, windows)))]
672        {
673            let _ = peer;
674            false
675        }
676    }
677
678    async fn execute_config_request(
679        &self,
680        ctx: &RouteCtx,
681        frame: &Frame,
682        runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
683        request: ConfigControlRequest,
684    ) -> std::result::Result<ConfigControlResponse, GateError> {
685        match request {
686            ConfigControlRequest::Modules {} => {
687                let known = self.config_settings_known_modules()?;
688                config_work(runtime, ConfigWake::None, move |owner| {
689                    owner.settings_modules(known)
690                })
691                .await
692            }
693            ConfigControlRequest::Schema { module_id } => {
694                let known = self.config_settings_known_modules()?;
695                config_work(runtime, ConfigWake::None, move |owner| {
696                    owner.settings_schema(known, module_id)
697                })
698                .await
699            }
700            ConfigControlRequest::Show {
701                module_id,
702                project_id,
703                through,
704            } => {
705                let known = self.config_settings_known_modules()?;
706                if let Some(project) = project_id {
707                    return runtime
708                        .settings_show_project(known, module_id, project, through)
709                        .await;
710                }
711                config_work(runtime, ConfigWake::None, move |owner| {
712                    owner.settings_show(known, module_id, through)
713                })
714                .await
715            }
716            ConfigControlRequest::PlanGet { digest } => {
717                let view = config_work(runtime, ConfigWake::None, move |owner| {
718                    owner.plan_get(&digest)
719                })
720                .await?;
721                Ok(ConfigControlResponse::PlanGet { view })
722            }
723            ConfigControlRequest::PlanDiscard { digest } => {
724                config_work(runtime, ConfigWake::Delivery, move |owner| {
725                    owner.plan_discard(&digest)
726                })
727                .await?;
728                Ok(ConfigControlResponse::PlanDiscard {})
729            }
730            ConfigControlRequest::PlaceProgram {
731                module_id,
732                path,
733                sha256,
734                manifest,
735            } => {
736                let gate = runtime.module_gate(&module_id)?;
737                let _guard = gate.lock().await;
738                let generation = config_work(runtime, ConfigWake::Delivery, move |owner| {
739                    owner.place_program_with_manifest(&module_id, &path, &sha256, manifest.as_ref())
740                })
741                .await?;
742                Ok(ConfigControlResponse::ProgramPlaced { generation })
743            }
744            ConfigControlRequest::Status {} => {
745                let snapshot = runtime.polled_snapshot()?;
746                let captured = snapshot.clone();
747                let mut status = runtime
748                    .on_blocking(move |owner| owner.polled_status_from(&captured))
749                    .await?;
750                let phone = self
751                    .config_phone_surface_checked(false, Some(&snapshot))
752                    .await;
753                let facts = self.config_approval_facts_with_phone(ctx, phone).await;
754                status
755                    .missing_approval_surfaces
756                    .extend(crate::config_gate::missing_surfaces(
757                        &facts,
758                        matches!(status.state.as_str(), "store_missing" | "store_unverified"),
759                    ));
760                self.report_daemon_configuration(&snapshot.approved_daemon, &mut status)
761                    .await?;
762                if let Some(problem) = runtime
763                    .on_blocking(move |owner| {
764                        Ok(owner.policy_root_problem(&snapshot.approved_daemon))
765                    })
766                    .await?
767                {
768                    status.warnings.push(problem);
769                }
770                Ok(ConfigControlResponse::Status { status })
771            }
772            ConfigControlRequest::History {} => {
773                let (generations, pruned) =
774                    config_work(runtime, ConfigWake::None, |owner| owner.history()).await?;
775                Ok(ConfigControlResponse::History {
776                    generations,
777                    pruned,
778                })
779            }
780            ConfigControlRequest::Apply { digest } => {
781                if let Some(result) = self
782                    .apply_unstamped_policy_root(ctx, frame, &runtime, &digest)
783                    .await?
784                {
785                    return Ok(result);
786                }
787                let apply_digest = digest.clone();
788                if let Some(generation) = runtime.apply_control_edits(apply_digest).await? {
789                    return Ok(ConfigControlResponse::Applied {
790                        generation,
791                        restart_required: false,
792                    });
793                }
794                let connection = ctx.connection_id;
795                let corr = frame.header.corr;
796                #[cfg(all(test, unix))]
797                runtime.pause_approval_claim_for_test().await;
798                let request_guard = runtime.claim_approval_request(connection, corr)?;
799                if self.rescan.is_none() {
800                    return Err(GateError::new(
801                        "supervisor_reconcile_unavailable",
802                        "configuration commit requires the supervisor owner",
803                    ));
804                }
805                let facts = self.config_approval_facts(ctx).await;
806                let cancellation = request_guard.request.clone();
807                let (challenge, mut attempt_guard) =
808                    config_work(runtime.clone(), ConfigWake::Delivery, move |owner| {
809                        let challenge = owner.begin_approval_for_request(
810                            &digest,
811                            &facts,
812                            Some(&cancellation),
813                        )?;
814                        // The job owns slot cleanup even if its async caller drops
815                        // before this blocking result can be delivered.
816                        let guard = phone::ApprovalAttemptGuard::new(&owner, challenge.attempt());
817                        owner.track_reserved_approval_request(
818                            challenge.attempt(),
819                            connection,
820                            corr,
821                            &cancellation,
822                        )?;
823                        Ok((challenge, guard))
824                    })
825                    .await?;
826                request_guard.request.ensure_live()?;
827                let reply = match &challenge {
828                    ApprovalChallenge::Desktop { .. } | ApprovalChallenge::OsPrompt { .. } => {
829                        ApprovalReply::Presence(
830                            self.confirm_config_gate_presence(ctx, frame, &challenge)
831                                .await,
832                        )
833                    }
834                    ApprovalChallenge::Phone {
835                        attempt,
836                        connection,
837                        deadline,
838                        request,
839                    } => {
840                        self.config_phone_rpc(
841                            &runtime,
842                            *attempt,
843                            ConnectionId::new(*connection),
844                            *deadline,
845                            request,
846                        )
847                        .await?
848                    }
849                };
850                let attempt = challenge.attempt();
851                let window = matches!(challenge, ApprovalChallenge::Phone { .. }).then(|| {
852                    Arc::new(crate::config_gate::runtime::ApprovalCommitWindow::new(
853                        Instant::now() + CONFIG_APPROVAL_COMMIT_TIMEOUT,
854                    ))
855                });
856                attempt_guard.commit_window = window.clone();
857                let checked_phone = self.config_phone_surface().await;
858                let locks = async {
859                    // A registry root can keep its worker busy until the I/O
860                    // returns. Do not hold supervisor or module gates while
861                    // waiting for that registry check.
862                    let project_apply = runtime.recheck_capture_apply(attempt).await?;
863                    let operation = self.supervisor.operation_lock().lock_owned().await;
864                    let module_gates = runtime.approval_commit_gates(attempt).await?;
865                    let current_phone = self.config_phone_surface_snapshot().await;
866                    let phone = checked_phone.filter(|phone| Some(phone) == current_phone.as_ref());
867                    let facts = self.config_approval_facts_with_phone(ctx, phone).await;
868                    Ok::<_, GateError>((operation, module_gates, facts, project_apply))
869                };
870                let (operation, module_gates, facts, project_apply) = if let Some(window) = &window
871                {
872                    timeout_at(window.deadline, locks)
873                        .await
874                        .map_err(|_| GateError::commit_timeout())??
875                } else {
876                    locks.await?
877                };
878                let now = now_ms();
879                let publish_window = window.clone();
880                let publication_request = request_guard.request.clone();
881                let exit_runtime = runtime.clone();
882                let work = config_work(runtime, ConfigWake::Delivery, move |owner| {
883                    let _owned_gates = (operation, module_gates);
884                    let write_authority = project_apply.clone();
885                    let generation = owner.finish_approval_with_commit_window(
886                        attempt,
887                        &facts,
888                        reply,
889                        now,
890                        publish_window,
891                        publication_request,
892                        project_apply,
893                    )?;
894                    if let Some(authority) = write_authority {
895                        // The publication job can finish after the control
896                        // request disconnects. It still owns this write-back.
897                        tokio::spawn(async move {
898                            owner
899                                .write_approved_project_files(generation, authority)
900                                .await
901                        });
902                    }
903                    Ok(generation)
904                });
905                tokio::pin!(work);
906                let generation = if let Some(window) = window {
907                    tokio::select! {
908                        result = &mut work => result?,
909                        _ = tokio::time::sleep_until(window.deadline) => {
910                            if window.expire() { return Err(GateError::commit_timeout()); }
911                            work.await?
912                        }
913                    }
914                } else {
915                    work.await?
916                };
917                let approval_runtime = exit_runtime.clone();
918                if let Some(approval) =
919                    config_work(approval_runtime, ConfigWake::None, move |owner| {
920                        owner.development_approval(generation)
921                    })
922                    .await?
923                {
924                    self.publish_development_approval(&approval);
925                    return Ok(ConfigControlResponse::Applied {
926                        generation,
927                        restart_required: false,
928                    });
929                }
930                #[cfg(test)]
931                self.pause_before_apply_reconcile_for_test().await;
932                self.reconcile_authority_exit(exit_runtime.clone(), generation)
933                    .await?;
934                let restart_required = self
935                    .daemon_restart_required(&exit_runtime, generation)
936                    .await?;
937                Ok(ConfigControlResponse::Applied {
938                    generation,
939                    restart_required,
940                })
941            }
942            request => {
943                let (kind, edits) = match request {
944                    ConfigControlRequest::Plan {
945                        base_generations,
946                        edits,
947                    } => {
948                        if edits.is_none() && base_generations.is_some() {
949                            return Err(GateError::new(
950                                "invalid_params",
951                                "base_generations requires edits",
952                            ));
953                        }
954                        let edits = edits
955                            .map(|edits| {
956                                base_generations.map(|base| (base, edits)).ok_or_else(|| {
957                                    GateError::new(
958                                        "invalid_params",
959                                        "edits requires base_generations",
960                                    )
961                                })
962                            })
963                            .transpose()?;
964                        (PlanKind::Change, edits)
965                    }
966                    ConfigControlRequest::Stamp {} => (PlanKind::Stamp, None),
967                    ConfigControlRequest::Unstamp {} => (PlanKind::Unstamp, None),
968                    ConfigControlRequest::Rollback { generation } => {
969                        (PlanKind::Rollback(generation), None)
970                    }
971                    _ => {
972                        return Err(GateError::new(
973                            "unsupported_control_frame",
974                            "unknown configuration operation",
975                        ))
976                    }
977                };
978                let mut prepared = match edits {
979                    Some((base, edits)) => runtime.prepare_control_edits(base, edits).await?,
980                    None => {
981                        let prepared = runtime.prepare_capture(kind).await?;
982                        // Preparing a plan can record observations that delivery reads.
983                        runtime.notify_delivery_changed();
984                        prepared
985                    }
986                };
987                if prepared.capture_refused() {
988                    let view = config_work(runtime, ConfigWake::None, move |owner| {
989                        owner.capture_refusal(&prepared)?.ok_or_else(|| {
990                            GateError::new("module_review_invalid", "project refusal is absent")
991                        })
992                    })
993                    .await?;
994                    return Ok(ConfigControlResponse::Plan { view });
995                }
996                let mut fields = Vec::new();
997                let mut edit_refusals = Vec::new();
998                let mut unavailable_rereviews = Vec::new();
999                for (module, captured) in &prepared.candidate.modules {
1000                    if !prepared.review_modules.contains(module) {
1001                        continue;
1002                    }
1003                    let base = prepared.bases.get(module);
1004                    let reply = self
1005                        .review_config_tuple(&runtime, module, base, &captured.view)
1006                        .await;
1007                    let reply = match reply {
1008                        Ok(reply) => reply,
1009                        // A re-review the new program cannot answer now stays
1010                        // pending in status; it does not hold up this plan.
1011                        Err(_) if prepared.rereview_modules.contains(module) => {
1012                            unavailable_rereviews.push(module.clone());
1013                            continue;
1014                        }
1015                        Err(error) => return Err(error),
1016                    };
1017                    let reply: subc_protocol::config::ConfigReviewReply =
1018                        serde_json::from_slice(&reply).map_err(|_| {
1019                            GateError::new(
1020                                "module_review_invalid",
1021                                format!("{module}: malformed config.review reply"),
1022                            )
1023                        })?;
1024                    if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1025                        let before = edit_refusals.len();
1026                        for refusal in &reply.refusals {
1027                            for path in refusal
1028                                .paths
1029                                .iter()
1030                                .filter(|path| path.starts_with('/') && path.len() <= 1024)
1031                            {
1032                                edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1033                                    module_id: module.clone(),
1034                                    path: path.clone(),
1035                                    code: "module_review_refused".into(),
1036                                    message: "the module refused this field".into(),
1037                                    project_id: None,
1038                                    workspace_id: None,
1039                                });
1040                            }
1041                        }
1042                        if edit_refusals.len() == before {
1043                            edit_refusals.push(subc_control::config::ConfigPlanRefusal {
1044                                module_id: module.clone(),
1045                                path: String::new(),
1046                                code: "module_review_refused".into(),
1047                                message: "the module refused the edits".into(),
1048                                project_id: None,
1049                                workspace_id: None,
1050                            });
1051                        }
1052                        fields.extend(prepared.refused_fields(module)?);
1053                        continue;
1054                    }
1055                    fields.extend(crate::config_gate::review::checked_fields(
1056                        module,
1057                        &captured.schema,
1058                        base,
1059                        prepared.base_schemas.get(module),
1060                        &captured.view,
1061                        reply,
1062                    )?);
1063                }
1064                for module in unavailable_rereviews {
1065                    prepared.review_modules.remove(&module);
1066                    prepared.rereview_modules.remove(&module);
1067                }
1068                let mut project_replies = Vec::new();
1069                for (tuple, review) in prepared.project_reviews() {
1070                    let bytes = self
1071                        .review_config_tuple(
1072                            &runtime,
1073                            &tuple.module,
1074                            review.base.as_ref(),
1075                            &review.approval.view,
1076                        )
1077                        .await?;
1078                    let reply: subc_protocol::config::ConfigReviewReply =
1079                        serde_json::from_slice(&bytes).map_err(|_| {
1080                            GateError::new(
1081                                "module_review_invalid",
1082                                format!("{}: malformed project config.review reply", tuple.module),
1083                            )
1084                        })?;
1085                    project_replies.push((tuple.clone(), reply));
1086                }
1087                for (tuple, reply) in project_replies {
1088                    if prepared.is_edit_plan() && !reply.refusals.is_empty() {
1089                        prepared.refuse_project_review(&tuple, &reply);
1090                    } else {
1091                        fields.extend(prepared.accept_project_review(&tuple, reply)?);
1092                    }
1093                }
1094                if prepared.capture_refused() {
1095                    let view = runtime
1096                        .on_blocking(move |owner| {
1097                            owner.capture_refusal(&prepared)?.ok_or_else(|| {
1098                                GateError::new("module_review_invalid", "project refusal is absent")
1099                            })
1100                        })
1101                        .await?;
1102                    return Ok(ConfigControlResponse::Plan { view });
1103                }
1104                prepared.add_edit_refusals(edit_refusals);
1105                let view = config_work(runtime, ConfigWake::Delivery, move |owner| {
1106                    owner.finish_plan(prepared, move |old, new| {
1107                        let mut changeset = crate::config_gate::runtime::daemon_review(old, new)?;
1108                        changeset.fields = fields;
1109                        let mut effects: std::collections::BTreeMap<String,std::collections::BTreeMap<String,Vec<String>>> = Default::default();
1110                        for field in changeset.fields.iter().filter(|field| field.project_id.is_none()) {
1111                            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();
1112                            effects.entry(field.module_id.clone()).or_default().entry(kind).or_default().push(field.path.clone());
1113                        }
1114                        if changeset.fields.iter().any(|field| field.project_id.is_none() && field.apply != subc_config::ApplyKind::Live) {
1115                            changeset.apply_plan = serde_json::json!({"daemon_effects":changeset.apply_plan,"modules":effects});
1116                        }
1117                        Ok(changeset)
1118                    })
1119                })
1120                .await?;
1121                Ok(match kind {
1122                    PlanKind::Change => ConfigControlResponse::Plan { view },
1123                    PlanKind::Stamp => ConfigControlResponse::Stamp { view },
1124                    PlanKind::Unstamp => ConfigControlResponse::Unstamp { view },
1125                    PlanKind::Rollback(_) => ConfigControlResponse::Rollback { view },
1126                })
1127            }
1128        }
1129    }
1130
1131    async fn review_config_tuple(
1132        &self,
1133        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1134        module: &str,
1135        base: Option<&subc_protocol::config::ConfigView>,
1136        candidate: &subc_protocol::config::ConfigView,
1137    ) -> Result<Vec<u8>, GateError> {
1138        #[cfg(test)]
1139        if let Some(reply) = &self.config_review_test_reply {
1140            return serde_json::to_vec(reply).map_err(|_| {
1141                GateError::new(
1142                    "module_review_invalid",
1143                    "could not encode the fixture review",
1144                )
1145            });
1146        }
1147        let registration = self
1148            .registry
1149            .get_module(module)
1150            .map_err(|_| GateError::new("config_unavailable", "registry is unavailable"))?
1151            .ok_or_else(|| {
1152                GateError::new(
1153                    "module_review_unavailable",
1154                    format!("{module}: no active reviewer"),
1155                )
1156            })?;
1157        let admission = self.review_admission();
1158        let reviewer = registration.clone();
1159        config_work(runtime.clone(), ConfigWake::None, move |_| {
1160            admission.check(&reviewer)
1161        })
1162        .await?;
1163        if !registration
1164            .control_ops
1165            .iter()
1166            .any(|op| op == "config.review")
1167        {
1168            return Err(GateError::new(
1169                "module_review_unavailable",
1170                format!("{module}: config.review is not opted in"),
1171            ));
1172        }
1173        let request = subc_protocol::config::ConfigReviewRequest::new(
1174            base.map_or(0, |view| view.generation),
1175            candidate.layers.clone(),
1176            base.cloned(),
1177        );
1178        let bytes = serde_json::to_vec(&request).map_err(|_| {
1179            GateError::new("config_unavailable", "could not encode immutable review")
1180        })?;
1181        self.config_rpc(
1182            runtime,
1183            module,
1184            registration.connection_id,
1185            "config.review",
1186            bytes,
1187        )
1188        .await
1189    }
1190
1191    async fn config_approval_facts(&self, ctx: &RouteCtx) -> ApprovalFacts {
1192        let phone = self.config_phone_surface().await;
1193        self.config_approval_facts_with_phone(ctx, phone).await
1194    }
1195
1196    async fn config_approval_facts_with_phone(
1197        &self,
1198        ctx: &RouteCtx,
1199        phone: Option<crate::config_gate::PhoneSurface>,
1200    ) -> ApprovalFacts {
1201        let os_policy = crate::config_gate::os_prompt_policy_present();
1202        #[cfg(any(test, feature = "test-support"))]
1203        let os_policy = os_policy
1204            || self
1205                .config_runtime
1206                .as_ref()
1207                .is_some_and(|owner| owner.os_prompt_policy_for_tests());
1208        let desktop = self
1209            .config_desktop_identity(ctx.connection_id)
1210            .await
1211            .unwrap_or(false);
1212        ApprovalFacts {
1213            connection: ctx.connection_id.get(),
1214            owner_uid: self.config_owner_connection(ctx.connection_id),
1215            desktop_app: desktop,
1216            attested_operator_app: desktop && !cfg!(feature = "dev-desktop-approval"),
1217            os_prompt_available: config_os_prompt_available(
1218                self.forwarding.operator_confirms().config_gate_ready(),
1219                os_policy,
1220            ),
1221            phone,
1222            caller: self.resolve_caller(ctx.connection_id).await,
1223        }
1224    }
1225
1226    // The caller holds Callosum's module gate while allocating its RPC or
1227    // committing approval. This snapshot grants nothing until revalidated there.
1228    async fn config_phone_surface(&self) -> Option<crate::config_gate::PhoneSurface> {
1229        self.config_phone_surface_checked(true, None).await
1230    }
1231
1232    async fn config_phone_surface_snapshot(&self) -> Option<crate::config_gate::PhoneSurface> {
1233        self.config_phone_surface_checked(false, None).await
1234    }
1235
1236    async fn config_phone_surface_checked(
1237        &self,
1238        content: bool,
1239        publication: Option<&crate::config_gate::runtime::Published>,
1240    ) -> Option<crate::config_gate::PhoneSurface> {
1241        if self.config_runtime.as_ref().is_some_and(|owner| {
1242            publication.map_or_else(|| owner.is_recovering(), |view| view.is_recovering())
1243        }) {
1244            return None;
1245        }
1246        if !self.operator_app_policy.phone_enabled {
1247            return None;
1248        }
1249        let runtime = self.config_runtime.as_ref()?;
1250        let (_, registrations) = self.registry.list_modules_with_nonce_verification().ok()?;
1251        let (registration, verified) = registrations
1252            .into_iter()
1253            .find(|(registration, _)| registration.manifest.module_id == "callosum")?;
1254        if !verified
1255            || !registration.ready
1256            || !registration
1257                .control_ops
1258                .iter()
1259                .any(|op| op == subc_protocol::consent::CONSENT_V1)
1260        {
1261            return None;
1262        }
1263        let _spawn = self
1264            .supervisor
1265            .registration_spawn(registration.connection_id)?;
1266        if !self
1267            .forwarding
1268            .active_module_endpoint("callosum")
1269            .ok()
1270            .flatten()
1271            .is_some_and(|endpoint| endpoint.connection_id == registration.connection_id)
1272        {
1273            return None;
1274        }
1275        // Configuration approval requires a channel-bound phone launch.
1276        // Enabling configuration gating invalidates legacy launch nonces,
1277        // including an old registration whose process is still draining.
1278        let module = self.supervisor.get("callosum")?;
1279        let status = module.status().ok()?;
1280        let (spec, _) = module.configuration().ok()?;
1281        if !self.supervisor.registration_snapshot_is_current_live(
1282            &self.registry,
1283            "callosum",
1284            registration.connection_id,
1285            None,
1286        ) || !spec.reserved
1287            || !status.enabled
1288            || !status.process_alive
1289            || !status.registration_active
1290        {
1291            return None;
1292        }
1293        let connection = registration.connection_id;
1294        let approved = if content {
1295            runtime
1296                .on_blocking(move |owner| owner.approved_phone_entry(connection))
1297                .await
1298                .ok()??
1299        } else {
1300            if let Some(snapshot) = publication {
1301                runtime.polled_phone_entry_from(snapshot, connection)?
1302            } else {
1303                runtime.polled_phone_entry(connection)?
1304            }
1305        };
1306        if !approved.enabled || approved.module_spec() != spec {
1307            return None;
1308        }
1309        if content {
1310            let supervisor = self.supervisor.clone();
1311            let registry = self.registry.clone();
1312            if !runtime
1313                .on_blocking(move |_| {
1314                    Ok(supervisor
1315                        .registration_is_current_live(&registry, "callosum", connection, None))
1316                })
1317                .await
1318                .ok()?
1319            {
1320                return None;
1321            }
1322        }
1323        if !self.supervisor.registration_snapshot_is_current_live(
1324            &self.registry,
1325            "callosum",
1326            registration.connection_id,
1327            None,
1328        ) {
1329            return None;
1330        }
1331        Some(crate::config_gate::PhoneSurface {
1332            module_id: "callosum".into(),
1333            connection: connection.get(),
1334            spawn_generation: status.spawn_generation,
1335            enabled_by_policy: true,
1336            opted_in: true,
1337            approved_declaration: true,
1338            reserved: true,
1339            channel_registered: true,
1340            program_admitted: true,
1341            active_registration: true,
1342        })
1343    }
1344
1345    async fn config_rpc(
1346        &self,
1347        runtime: &Arc<crate::config_gate::runtime::RuntimeOwner>,
1348        module: &str,
1349        expected_connection: ConnectionId,
1350        op: &str,
1351        bytes: Vec<u8>,
1352    ) -> std::result::Result<Vec<u8>, GateError> {
1353        let gate = runtime.module_gate(module)?;
1354        let pending = {
1355            let _gate = gate.lock().await;
1356            let registration = self
1357                .registry
1358                .get_module(module)
1359                .map_err(|_| GateError::new("config_unavailable", "registry unavailable"))?
1360                .ok_or_else(|| {
1361                    GateError::new(
1362                        "module_review_unavailable",
1363                        format!("{module}: no active target"),
1364                    )
1365                })?;
1366            let pending = self
1367                .forwarding
1368                .begin_module_control_rpc_for(module, op, Instant::now() + CONFIG_REVIEW_TIMEOUT)
1369                .map_err(|_| {
1370                    GateError::new(
1371                        "module_review_unavailable",
1372                        format!("{module}: target unavailable"),
1373                    )
1374                })?;
1375            if pending.endpoint.connection_id != registration.connection_id
1376                || registration.connection_id != expected_connection
1377            {
1378                let _ = self
1379                    .forwarding
1380                    .cancel_module_control_rpc(pending.endpoint, pending.corr);
1381                return Err(GateError::new(
1382                    "not_delivery_target",
1383                    "registry and forwarding targets differ",
1384                ));
1385            }
1386            pending
1387        };
1388        let PendingModuleControlRpc {
1389            endpoint,
1390            module_sink,
1391            negotiated_ver,
1392            corr,
1393            receiver,
1394        } = pending;
1395        let mut guard = ModuleControlRpcGuard::new(self.forwarding.clone(), endpoint, corr);
1396        let deadline = Instant::now() + CONFIG_REVIEW_TIMEOUT;
1397        let frame = Frame::build_with_version(
1398            negotiated_ver,
1399            FrameType::Request,
1400            control_flags(),
1401            0,
1402            0,
1403            corr,
1404            bytes,
1405        )
1406        .map_err(|_| GateError::new("config_unavailable", "could not encode config request"))?;
1407        timeout_at(deadline, module_sink.send(frame))
1408            .await
1409            .map_err(|_| {
1410                GateError::new(
1411                    "config_review_timeout",
1412                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1413                )
1414            })?
1415            .map_err(|_| {
1416                GateError::new(
1417                    "module_review_unavailable",
1418                    format!("{module}: target disconnected"),
1419                )
1420            })?;
1421        let outcome = timeout_at(deadline, receiver)
1422            .await
1423            .map_err(|_| {
1424                GateError::new(
1425                    "config_review_timeout",
1426                    format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"),
1427                )
1428            })?
1429            .map_err(|_| {
1430                GateError::new(
1431                    "module_review_unavailable",
1432                    format!("{module}: target disconnected"),
1433                )
1434            })?;
1435        guard.disarm();
1436        match outcome {
1437            ModuleControlRpcOutcome::RawResponse(bytes) => Ok(bytes),
1438            ModuleControlRpcOutcome::DeadlineElapsed => Err(GateError::new("config_review_timeout",format!("{module}: config.review exceeded its 30-second deadline; plan remains unapproved"))),
1439            _ => Err(GateError::new(
1440                "module_review_unavailable",
1441                format!("{module}: config request was not answered"),
1442            )),
1443        }
1444    }
1445
1446    /// Execute only the presence part of an engine-selected challenge. The
1447    /// runtime owner still rechecks the inputs and surface before committing.
1448    pub async fn confirm_config_gate_presence(
1449        &self,
1450        ctx: &RouteCtx,
1451        frame: &Frame,
1452        challenge: &ApprovalChallenge,
1453    ) -> PresenceDecision {
1454        let Some(text) = challenge.prompt() else {
1455            return PresenceDecision::Unavailable;
1456        };
1457        let caller = self.resolve_caller(ctx.connection_id).await;
1458        let key = crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1459        // Neither privileged_operator_prompt nor operator-app shortcut policy
1460        // is consulted: every desktop gate review requires OS presence.
1461        let outcome = self
1462            .forwarding
1463            .operator_confirms()
1464            .approve_config_gate(ctx, frame, text.to_owned(), caller.description(), key)
1465            .await;
1466        PresenceDecision::from_operator_outcome(&outcome)
1467    }
1468}
1469
1470fn config_os_prompt_available(provider_ready: bool, policy_present: bool) -> bool {
1471    provider_ready && policy_present
1472}
1473
1474enum ConfigWake {
1475    None,
1476    Delivery,
1477}
1478
1479async fn config_work<T: Send + 'static>(
1480    runtime: Arc<crate::config_gate::runtime::RuntimeOwner>,
1481    wake: ConfigWake,
1482    work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>) -> std::result::Result<T, GateError>
1483        + Send
1484        + 'static,
1485) -> std::result::Result<T, GateError> {
1486    runtime
1487        .on_blocking(move |owner| {
1488            let result = work(owner.clone());
1489            if matches!(wake, ConfigWake::Delivery) {
1490                owner.notify_delivery_changed();
1491            }
1492            result
1493        })
1494        .await
1495}
1496
1497pub(super) fn config_error_frame(frame: &Frame, error: GateError) -> Result<Frame, RouterError> {
1498    control_error_body_frame(
1499        frame,
1500        ErrorBody {
1501            code: error.code,
1502            message: error.detail,
1503            detail: None,
1504        },
1505    )
1506}
1507
1508pub(super) fn now_ms() -> u64 {
1509    std::time::SystemTime::now()
1510        .duration_since(std::time::UNIX_EPOCH)
1511        .unwrap_or_default()
1512        .as_millis()
1513        .min(u128::from(u64::MAX)) as u64
1514}
1515
1516#[cfg(test)]
1517mod tests;
1518
1519#[cfg(test)]
1520mod desktop_tests;