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