Skip to main content

merry_process/
backend.rs

1//! Local and live-swappable host-process backend implementations.
2
3use crate::{
4    ProcessBackend, ProcessBackendError, ProcessBackendMode, ProcessBackendOptions, ProcessSession,
5    ProcessSessionPermissions, ProcessSessionRequest, TokioProcessRunner,
6};
7#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
8use crate::{WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory};
9#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
10use merry_core::CapabilityPolicy;
11use merry_runtime::{
12    AcceptedLocalWorkspaceProcessAdmission, PermissionRequest, PermissionedProcessRunnerFactory,
13    ProcessRunner,
14};
15#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
16use merry_runtime::{HostIntegration, PathAccessRule};
17#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
18use std::path::Path;
19use std::{path::PathBuf, sync::Arc};
20
21/// Current local host-process backend.
22///
23/// The backend owns the current host implementation choice. Its public
24/// session contract is intentionally independent of that choice, so adding a
25/// platform-specific backend does not change coding profile or runtime APIs.
26#[derive(Clone)]
27pub struct LocalProcessBackend {
28    new_session: Arc<dyn Fn() -> ProcessSession + Send + Sync>,
29    new_session_with: Arc<
30        dyn Fn(ProcessSessionRequest) -> Result<ProcessSession, ProcessBackendError> + Send + Sync,
31    >,
32}
33
34impl LocalProcessBackend {
35    /// Creates a fixed backend from one already constructed session.
36    ///
37    /// This is intended for trusted adapters and deterministic test fixtures.
38    /// Platform-selected production backends should use [`Self::new`] so the
39    /// admission is created together with the concrete enforcement strategy.
40    #[must_use]
41    pub fn from_session(session: ProcessSession) -> Self {
42        let child_session = session.clone();
43        let scoped_session = session;
44        Self {
45            new_session: Arc::new(move || child_session.clone()),
46            new_session_with: Arc::new(move |_request| Ok(scoped_session.clone())),
47        }
48    }
49
50    #[cfg(test)]
51    pub(crate) fn from_parts(
52        admission: AcceptedLocalWorkspaceProcessAdmission,
53        runner: Arc<dyn ProcessRunner>,
54        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
55    ) -> Self {
56        Self::from_session(ProcessSession::from_parts(
57            admission,
58            runner,
59            permissioned_factory,
60        ))
61    }
62
63    /// Creates a platform-selected local process backend.
64    ///
65    /// # Errors
66    ///
67    /// Returns a [`ProcessBackendError`] when the selected backend cannot be
68    /// configured or the requested isolated behavior is unavailable.
69    pub fn new(
70        workspace_root: impl Into<PathBuf>,
71        mode: ProcessBackendMode,
72        options: ProcessBackendOptions,
73    ) -> Result<Self, ProcessBackendError> {
74        Self::new_with_shared_state(workspace_root, mode, options, None, None)
75    }
76
77    fn new_with_shared_state(
78        workspace_root: impl Into<PathBuf>,
79        mode: ProcessBackendMode,
80        options: ProcessBackendOptions,
81        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
82        shared_permissions: Option<ProcessSessionPermissions>,
83    ) -> Result<Self, ProcessBackendError> {
84        match mode {
85            ProcessBackendMode::Host => Self::unrestricted_with_shared_state(
86                workspace_root,
87                options,
88                shared_background,
89                shared_permissions,
90            ),
91            ProcessBackendMode::Isolated => Self::sandboxed_with_shared_state(
92                workspace_root,
93                options,
94                shared_background,
95                shared_permissions,
96            ),
97        }
98    }
99
100    /// Creates the current host-process implementation without an inner
101    /// operating-system sandbox.
102    ///
103    /// # Errors
104    ///
105    /// Returns a [`ProcessBackendError::Runner`] when an environment override
106    /// cannot be validated by the host runner.
107    pub fn unrestricted(
108        workspace_root: impl Into<PathBuf>,
109        options: ProcessBackendOptions,
110    ) -> Result<Self, ProcessBackendError> {
111        Self::unrestricted_with_shared_state(workspace_root, options, None, None)
112    }
113
114    fn unrestricted_with_shared_state(
115        workspace_root: impl Into<PathBuf>,
116        options: ProcessBackendOptions,
117        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
118        shared_permissions: Option<ProcessSessionPermissions>,
119    ) -> Result<Self, ProcessBackendError> {
120        let workspace_root = workspace_root.into();
121        let environment_overrides = options.environment_overrides;
122        let env_isolation = options.env_isolation;
123        let mut runner = TokioProcessRunner::new_at_workspace_root(workspace_root.clone())
124            .with_env_isolation(env_isolation.clone())?
125            .with_environment_overrides(environment_overrides.clone())?;
126        if let Some(background) = shared_background {
127            runner = runner.with_background(background);
128        }
129        let runner = Arc::new(runner);
130        let path_rules = options.path_rules;
131        let product_private_paths = merry_runtime::extract_product_private_paths(&path_rules);
132        let permissioned_factory = Arc::new(
133            UnrestrictedPermissionedProcessRunnerFactory::new(
134                Arc::clone(&runner) as Arc<dyn ProcessRunner>
135            )
136            .with_product_private_paths(workspace_root.clone(), product_private_paths.clone()),
137        );
138        let workspace_writable = options.workspace_writable;
139        let network_policy = options.network_policy;
140        let allowed_domains = options.allowed_domains;
141        let browser_allow_local = options.browser_allow_local;
142        let permissions = shared_permissions.unwrap_or_default();
143        let default_session = ProcessSession::from_parts(
144            AcceptedLocalWorkspaceProcessAdmission::accept_host(),
145            runner,
146            permissioned_factory,
147        )
148        .with_session_permissions(permissions.clone())
149        .with_access_policy_inputs(path_rules.clone(), workspace_writable)
150        .with_network_policy_inputs(network_policy, allowed_domains.clone(), browser_allow_local)
151        .with_env_isolation(env_isolation.clone());
152        Ok(Self {
153            new_session: Arc::new(move || default_session.clone()),
154            new_session_with: Arc::new(move |request| {
155                let effective_root = request
156                    .workspace_root
157                    .unwrap_or_else(|| workspace_root.clone());
158                let runner = Arc::new(
159                    TokioProcessRunner::new_at_workspace_root(effective_root.clone())
160                        .with_env_isolation(env_isolation.clone())?
161                        .with_environment_overrides(environment_overrides.clone())?,
162                );
163                let mut combined_rules = path_rules.clone();
164                combined_rules.extend(request.extra_path_rules);
165                let child_private_paths =
166                    merry_runtime::extract_product_private_paths(&combined_rules);
167                let permissioned_factory = Arc::new(
168                    UnrestrictedPermissionedProcessRunnerFactory::new(
169                        Arc::clone(&runner) as Arc<dyn ProcessRunner>
170                    )
171                    .with_product_private_paths(effective_root, child_private_paths),
172                );
173                let child_permissions = match request.inherited_permissions.as_ref() {
174                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
175                    None => ProcessSessionPermissions::new(),
176                };
177                Ok(ProcessSession::from_parts(
178                    AcceptedLocalWorkspaceProcessAdmission::accept_host(),
179                    runner,
180                    permissioned_factory,
181                )
182                .with_session_permissions(child_permissions)
183                .with_access_policy_inputs(
184                    combined_rules,
185                    workspace_writable && request.workspace_writable,
186                )
187                .with_network_policy_inputs(
188                    network_policy,
189                    allowed_domains.clone(),
190                    browser_allow_local,
191                )
192                .with_env_isolation(env_isolation.clone()))
193            }),
194        })
195    }
196
197    /// Creates the current isolated local-process implementation.
198    ///
199    /// On Linux, each action is confined with Landlock and, unless that action
200    /// was granted network, a seccomp filter. On macOS, each action is confined
201    /// with a Seatbelt profile. Other targets return
202    /// [`ProcessBackendError::UnsupportedIsolation`].
203    ///
204    /// # Errors
205    ///
206    /// Returns a [`ProcessBackendError`] when the workspace or sandbox
207    /// environment is invalid, a configured path cannot be enforced, or this
208    /// target has no isolated backend.
209    pub fn sandboxed(
210        workspace_root: impl Into<PathBuf>,
211        options: ProcessBackendOptions,
212    ) -> Result<Self, ProcessBackendError> {
213        Self::sandboxed_with_shared_state(workspace_root, options, None, None)
214    }
215}
216
217#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
218impl LocalProcessBackend {
219    fn sandboxed_with_shared_state(
220        workspace_root: impl Into<PathBuf>,
221        options: ProcessBackendOptions,
222        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
223        shared_permissions: Option<ProcessSessionPermissions>,
224    ) -> Result<Self, ProcessBackendError> {
225        let workspace_root = workspace_root.into();
226        let mut environment = WorkspaceProcessEnvironment::from_current_process()
227            .with_host_integrations(options.host_integrations)
228            .with_env_isolation(options.env_isolation)?
229            .with_overrides(options.environment_overrides)?
230            .validate_for_workspace(&workspace_root)?;
231        if let Some(sockets) = options.gpg_agent_sockets {
232            environment = environment.with_gpg_agent_sockets(sockets);
233        }
234        let mut rules_runner =
235            WorkspaceProcessRunner::new_at_workspace_root(workspace_root.clone())
236                .with_environment(environment.clone())
237                .with_path_rules(options.path_rules.iter().cloned());
238        if !options.workspace_writable {
239            rules_runner = rules_runner.read_only_workspace();
240        }
241        rules_runner.ensure_sandbox_rules()?;
242        Ok(Self::from_sandboxed_parts(SandboxedBackendParts {
243            workspace_root,
244            environment,
245            path_rules: options.path_rules,
246            network_policy: options.network_policy,
247            allowed_domains: options.allowed_domains,
248            browser_allow_local: options.browser_allow_local,
249            denied_host_integrations: options.denied_host_integrations,
250            workspace_writable: options.workspace_writable,
251            shared_background,
252            shared_permissions,
253        }))
254    }
255
256    fn from_sandboxed_parts(parts: SandboxedBackendParts) -> Self {
257        let SandboxedBackendParts {
258            workspace_root,
259            environment,
260            path_rules,
261            network_policy,
262            allowed_domains,
263            browser_allow_local,
264            denied_host_integrations,
265            workspace_writable,
266            shared_background,
267            shared_permissions,
268        } = parts;
269        let child_workspace_root = workspace_root.clone();
270        let child_environment = environment.clone();
271        let child_path_rules = path_rules.clone();
272        let child_allowed_domains = allowed_domains.clone();
273        let child_denied_integrations = denied_host_integrations.clone();
274        let scoped_workspace_root = workspace_root;
275        let scoped_environment = environment;
276        let scoped_path_rules = path_rules;
277        Self {
278            new_session: Arc::new(move || {
279                Self::sandboxed_session(SandboxedSessionParts {
280                    workspace_root: &child_workspace_root,
281                    environment: &child_environment,
282                    path_rules: &child_path_rules,
283                    network_policy,
284                    allowed_domains: &child_allowed_domains,
285                    browser_allow_local,
286                    denied_host_integrations: &child_denied_integrations,
287                    workspace_writable,
288                    session_permissions: shared_permissions.clone().unwrap_or_default(),
289                    background: shared_background.clone().unwrap_or_default(),
290                })
291            }),
292            new_session_with: Arc::new(move |request| {
293                let target_root = request
294                    .workspace_root
295                    .as_deref()
296                    .unwrap_or(&scoped_workspace_root);
297                // Intersection: a scoped session can narrow a writable backend
298                // to read-only, never widen a read-only backend to writable.
299                let effective_writable = workspace_writable && request.workspace_writable;
300                let session_permissions = match request.inherited_permissions.as_ref() {
301                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
302                    None => ProcessSessionPermissions::new(),
303                };
304                let mut combined_rules =
305                    Vec::with_capacity(scoped_path_rules.len() + request.extra_path_rules.len());
306                combined_rules.extend(scoped_path_rules.iter().cloned());
307                combined_rules.extend(request.extra_path_rules);
308                let validated_env = if request.workspace_root.is_some() {
309                    scoped_environment
310                        .clone()
311                        .validate_for_workspace(target_root)?
312                } else {
313                    scoped_environment.clone()
314                };
315                if request.workspace_root.is_some() || !combined_rules.is_empty() {
316                    let mut rules_runner =
317                        WorkspaceProcessRunner::new_at_workspace_root(target_root)
318                            .with_environment(validated_env.clone())
319                            .with_path_rules(combined_rules.iter().cloned());
320                    if !effective_writable {
321                        rules_runner = rules_runner.read_only_workspace();
322                    }
323                    rules_runner.ensure_sandbox_rules()?;
324                }
325                Ok(Self::sandboxed_session(SandboxedSessionParts {
326                    workspace_root: target_root,
327                    environment: &validated_env,
328                    path_rules: &combined_rules,
329                    network_policy,
330                    allowed_domains: &allowed_domains,
331                    browser_allow_local,
332                    denied_host_integrations: &denied_host_integrations,
333                    workspace_writable: effective_writable,
334                    session_permissions,
335                    background: crate::process_runner::BackgroundSupervisor::new(),
336                }))
337            }),
338        }
339    }
340
341    fn sandboxed_session(parts: SandboxedSessionParts<'_>) -> ProcessSession {
342        let SandboxedSessionParts {
343            workspace_root,
344            environment,
345            path_rules,
346            network_policy,
347            allowed_domains,
348            browser_allow_local,
349            denied_host_integrations,
350            workspace_writable,
351            session_permissions,
352            background,
353        } = parts;
354        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(workspace_root)
355            .with_environment(environment.clone())
356            .with_path_rules(path_rules.iter().cloned())
357            .with_background(background.clone());
358        let mut permissioned_factory =
359            WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace_root)
360                .with_environment(environment.clone())
361                .with_path_rules(path_rules.iter().cloned())
362                .with_network_policy(network_policy)
363                .with_denied_host_integrations(denied_host_integrations.iter().copied())
364                .with_background(background);
365        if network_policy.is_preauthorized() {
366            runner = runner.allow_network();
367        }
368        if !workspace_writable {
369            runner = runner.read_only_workspace();
370            permissioned_factory = permissioned_factory.read_only_workspace();
371        }
372        let runner = runner.with_session_permissions(session_permissions.clone());
373        let permissioned_factory =
374            permissioned_factory.with_session_permissions(session_permissions.clone());
375        ProcessSession::from_parts(
376            AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
377            Arc::new(runner),
378            Arc::new(permissioned_factory),
379        )
380        .with_session_permissions(session_permissions)
381        .with_access_policy_inputs(path_rules.to_vec(), workspace_writable)
382        .with_network_policy_inputs(
383            network_policy,
384            allowed_domains.to_vec(),
385            browser_allow_local,
386        )
387        .with_env_isolation(environment.env_isolation().clone())
388    }
389}
390
391#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
392struct SandboxedBackendParts {
393    workspace_root: PathBuf,
394    environment: WorkspaceProcessEnvironment,
395    path_rules: Vec<PathAccessRule>,
396    network_policy: CapabilityPolicy,
397    allowed_domains: Vec<String>,
398    browser_allow_local: bool,
399    denied_host_integrations: Vec<HostIntegration>,
400    workspace_writable: bool,
401    shared_background: Option<crate::process_runner::BackgroundSupervisor>,
402    shared_permissions: Option<ProcessSessionPermissions>,
403}
404
405#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
406struct SandboxedSessionParts<'a> {
407    workspace_root: &'a Path,
408    environment: &'a WorkspaceProcessEnvironment,
409    path_rules: &'a [PathAccessRule],
410    network_policy: CapabilityPolicy,
411    allowed_domains: &'a [String],
412    browser_allow_local: bool,
413    denied_host_integrations: &'a [HostIntegration],
414    workspace_writable: bool,
415    session_permissions: ProcessSessionPermissions,
416    background: crate::process_runner::BackgroundSupervisor,
417}
418
419#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
420impl LocalProcessBackend {
421    fn sandboxed_with_shared_state(
422        workspace_root: impl Into<PathBuf>,
423        options: ProcessBackendOptions,
424        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
425        shared_permissions: Option<ProcessSessionPermissions>,
426    ) -> Result<Self, ProcessBackendError> {
427        let _ = (
428            workspace_root.into(),
429            options,
430            shared_background,
431            shared_permissions,
432        );
433        Err(ProcessBackendError::UnsupportedIsolation {
434            target_os: std::env::consts::OS,
435        })
436    }
437}
438
439impl ProcessBackend for LocalProcessBackend {
440    fn new_session(&self) -> ProcessSession {
441        (self.new_session)()
442    }
443
444    fn new_session_with(
445        &self,
446        request: ProcessSessionRequest,
447    ) -> Result<ProcessSession, ProcessBackendError> {
448        (self.new_session_with)(request)
449    }
450}
451
452/// Process backend whose active mode and sandbox options can be swapped live
453/// while keeping the parent session's background process supervisor and
454/// live-updatable permission view intact.
455///
456/// Newly spawned child sessions via [`ProcessBackend::new_session_with`] read
457/// the latest swapped backend automatically, while [`Self::replace`] clears
458/// stale session-retained grants and returns a new parent [`ProcessSession`]
459/// bound to the same background supervisor and permission view so retained
460/// background processes remain inspectable/stoppable and future subagents
461/// inherit only post-reload grants.
462/// Policy governing how existing session-scoped permission grants are treated
463/// when [`LiveProcessBackend`] swaps its active configuration.
464#[derive(Debug, Clone, PartialEq, Eq)]
465pub enum SessionGrantClearPolicy {
466    /// Clear all session grants (used when switching `SandboxMode`).
467    ClearAll,
468    /// Preserve all existing session grants (used when adding/removing saved
469    /// workspace rules).
470    PreserveAll,
471    /// Selectively revoke only grants invalidated by newly denied capability
472    /// policies, keeping unrelated path/domain grants intact.
473    RevokeDenied {
474        /// Whether outbound network is now `CapabilityPolicy::Deny`.
475        network_denied: bool,
476        /// Host integrations that are now `CapabilityPolicy::Deny`.
477        denied_host_integrations: Vec<merry_runtime::HostIntegration>,
478    },
479}
480
481/// Validated, uncommitted live backend replacement produced by
482/// [`LiveProcessBackend::prepare_replace`].
483///
484/// Dropping this handle without calling [`Self::commit`] leaves the active
485/// backend, live policy baseline, and retained session permissions untouched.
486pub struct PreparedLiveReplace<'a> {
487    backend: &'a LiveProcessBackend,
488    next_backend: LocalProcessBackend,
489    next_session: ProcessSession,
490    next_baseline: merry_runtime::LivePolicyBaseline,
491    next_env_isolation: crate::ProcessEnvIsolation,
492    clear_policy: SessionGrantClearPolicy,
493}
494
495impl PreparedLiveReplace<'_> {
496    /// Borrows the prepared parent [`ProcessSession`] (with runners and
497    /// factories ready for `InteractiveProcessExecutionUpdate`) before commit.
498    #[must_use]
499    pub fn session(&self) -> &ProcessSession {
500        &self.next_session
501    }
502
503    /// Atomically commits the prepared backend, live policy baseline,
504    /// environment isolation, and session grant clear policy.
505    ///
506    /// # Errors
507    ///
508    /// Returns a [`ProcessBackendError`] if the session permission lock was poisoned.
509    pub fn commit(self) -> Result<ProcessSession, ProcessBackendError> {
510        match &self.clear_policy {
511            SessionGrantClearPolicy::ClearAll => {
512                self.backend.session_permissions.clear()?;
513            }
514            SessionGrantClearPolicy::PreserveAll => {}
515            SessionGrantClearPolicy::RevokeDenied {
516                network_denied,
517                denied_host_integrations,
518            } => {
519                self.backend
520                    .session_permissions
521                    .revoke_denied_capabilities(*network_denied, denied_host_integrations)?;
522            }
523        }
524        if let Some(live) = &self.backend.live_policy {
525            live.replace_baseline(self.next_baseline);
526        }
527        if let Some(live_env) = &self.backend.live_env_isolation {
528            *live_env
529                .write()
530                .unwrap_or_else(std::sync::PoisonError::into_inner) = self.next_env_isolation;
531        }
532        let mut guard = self
533            .backend
534            .state
535            .write()
536            .unwrap_or_else(std::sync::PoisonError::into_inner);
537        *guard = self.next_backend;
538        Ok(self.next_session)
539    }
540}
541
542pub struct LiveProcessBackend {
543    state: std::sync::RwLock<LocalProcessBackend>,
544    session_background: crate::process_runner::BackgroundSupervisor,
545    session_permissions: ProcessSessionPermissions,
546    live_policy: Option<merry_runtime::LivePolicyHandle>,
547    live_env_isolation: Option<Arc<std::sync::RwLock<crate::ProcessEnvIsolation>>>,
548}
549
550impl LiveProcessBackend {
551    /// Creates a live-swappable local process backend.
552    ///
553    /// # Errors
554    ///
555    /// Returns a [`ProcessBackendError`] when the initial backend configuration
556    /// is invalid or the requested isolated sandbox is unavailable.
557    pub fn new(
558        workspace_root: impl Into<PathBuf>,
559        mode: ProcessBackendMode,
560        options: ProcessBackendOptions,
561    ) -> Result<Self, ProcessBackendError> {
562        let workspace_root = workspace_root.into();
563        let session_background = crate::process_runner::BackgroundSupervisor::new();
564        let session_permissions = ProcessSessionPermissions::new();
565        let backend = LocalProcessBackend::new_with_shared_state(
566            workspace_root.clone(),
567            mode,
568            options,
569            Some(session_background.clone()),
570            Some(session_permissions.clone()),
571        )?;
572        let initial_session = backend.new_session();
573        let initial_baseline = live_policy_baseline(&workspace_root, mode, &initial_session);
574        let live_policy = merry_runtime::LivePolicyHandle::new(initial_baseline)
575            .with_session_permissions(session_permissions.view());
576        let live_env_isolation = Arc::new(std::sync::RwLock::new(
577            initial_session.env_isolation().clone(),
578        ));
579        Ok(Self {
580            state: std::sync::RwLock::new(backend),
581            session_background,
582            session_permissions,
583            live_policy: Some(live_policy),
584            live_env_isolation: Some(live_env_isolation),
585        })
586    }
587
588    /// Wraps a fixed process session (primarily for tests and custom adapters).
589    #[must_use]
590    pub fn from_session(session: ProcessSession) -> Self {
591        Self {
592            state: std::sync::RwLock::new(LocalProcessBackend::from_session(session)),
593            session_background: crate::process_runner::BackgroundSupervisor::new(),
594            session_permissions: ProcessSessionPermissions::new(),
595            live_policy: None,
596            live_env_isolation: None,
597        }
598    }
599
600    /// Validates and prepares a replacement backend configuration without
601    /// mutating live state or clearing session grants until
602    /// [`PreparedLiveReplace::commit`] is called.
603    ///
604    /// # Errors
605    ///
606    /// Returns a [`ProcessBackendError`] when the new configuration is invalid
607    /// or the requested isolated sandbox is unavailable.
608    pub fn prepare_replace(
609        &self,
610        workspace_root: impl Into<PathBuf>,
611        mode: ProcessBackendMode,
612        options: ProcessBackendOptions,
613        clear_policy: SessionGrantClearPolicy,
614    ) -> Result<PreparedLiveReplace<'_>, ProcessBackendError> {
615        let workspace_root = workspace_root.into();
616        let next_backend = LocalProcessBackend::new_with_shared_state(
617            workspace_root.clone(),
618            mode,
619            options,
620            Some(self.session_background.clone()),
621            Some(self.session_permissions.clone()),
622        )?;
623        let mut next_session = next_backend.new_session();
624        let next_baseline = live_policy_baseline(&workspace_root, mode, &next_session);
625        let next_env_isolation = next_session.env_isolation().clone();
626        if let Some(live) = &self.live_policy {
627            next_session = next_session.with_live_policy(live.clone());
628        }
629        if let Some(live_env) = &self.live_env_isolation {
630            next_session = next_session.with_live_env_isolation(Arc::clone(live_env));
631        }
632        Ok(PreparedLiveReplace {
633            backend: self,
634            next_backend,
635            next_session,
636            next_baseline,
637            next_env_isolation,
638            clear_policy,
639        })
640    }
641
642    /// Validates and installs a replacement backend configuration, returning a
643    /// new parent [`ProcessSession`] sharing the existing background supervisor,
644    /// unified live policy handle, and a freshly cleared session permission store.
645    ///
646    /// If validation fails, the active backend and retained session permissions
647    /// remain unchanged.
648    ///
649    /// # Errors
650    ///
651    /// Returns a [`ProcessBackendError`] when the new configuration is invalid
652    /// or the requested isolated sandbox is unavailable.
653    pub fn replace(
654        &self,
655        workspace_root: impl Into<PathBuf>,
656        mode: ProcessBackendMode,
657        options: ProcessBackendOptions,
658    ) -> Result<ProcessSession, ProcessBackendError> {
659        self.prepare_replace(
660            workspace_root,
661            mode,
662            options,
663            SessionGrantClearPolicy::ClearAll,
664        )?
665        .commit()
666    }
667}
668
669fn live_policy_baseline(
670    workspace_root: &std::path::Path,
671    mode: ProcessBackendMode,
672    session: &ProcessSession,
673) -> merry_runtime::LivePolicyBaseline {
674    let restricted = matches!(mode, ProcessBackendMode::Isolated);
675    let workspace_access = restricted
676        .then(|| session.workspace_access_policy(workspace_root, session.workspace_writable()));
677    merry_runtime::LivePolicyBaseline::new(
678        restricted,
679        workspace_access,
680        session.product_private_paths(),
681        session.network_access_policy(),
682    )
683}
684
685impl ProcessBackend for LiveProcessBackend {
686    fn new_session(&self) -> ProcessSession {
687        let mut session = self
688            .state
689            .read()
690            .unwrap_or_else(std::sync::PoisonError::into_inner)
691            .new_session();
692        if let Some(live) = &self.live_policy {
693            session = session.with_live_policy(live.clone());
694        }
695        if let Some(live_env) = &self.live_env_isolation {
696            session = session.with_live_env_isolation(Arc::clone(live_env));
697        }
698        session
699    }
700
701    fn new_session_with(
702        &self,
703        request: ProcessSessionRequest,
704    ) -> Result<ProcessSession, ProcessBackendError> {
705        let mut child_override =
706            merry_runtime::ChildWorkspacePolicyOverride::new(request.workspace_writable);
707        if let Some(root) = request.workspace_root.as_ref() {
708            child_override = child_override.with_workspace_root(root);
709        }
710        if !request.extra_path_rules.is_empty() {
711            child_override =
712                child_override.with_extra_path_rules(request.extra_path_rules.iter().cloned());
713        }
714        let mut session = self
715            .state
716            .read()
717            .unwrap_or_else(std::sync::PoisonError::into_inner)
718            .new_session_with(request)?;
719        if let Some(live) = &self.live_policy {
720            let child_live = live.for_child(session.permission_view(), Some(child_override));
721            session = session.with_live_policy(child_live);
722        }
723        if let Some(live_env) = &self.live_env_isolation {
724            session = session.with_live_env_isolation(Arc::clone(live_env));
725        }
726        Ok(session)
727    }
728}
729
730/// Permissioned runner factory for the explicit unrestricted host backend.
731///
732/// The host backend already runs without an OS sandbox, so a reviewed
733/// capability request reuses its runner. Runtime admission, action evidence,
734/// and `ProductPrivate` (`providers/` / `MERRY_API_KEY_FILE`) protection remain
735/// active around the returned runner.
736#[derive(Clone)]
737pub struct UnrestrictedPermissionedProcessRunnerFactory {
738    runner: Arc<dyn ProcessRunner>,
739    cwd_root: Option<PathBuf>,
740    product_private_paths: Vec<PathBuf>,
741}
742
743impl UnrestrictedPermissionedProcessRunnerFactory {
744    /// Creates a factory that reuses the host-process runner.
745    #[must_use]
746    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
747        Self {
748            runner,
749            cwd_root: None,
750            product_private_paths: Vec::new(),
751        }
752    }
753
754    /// Configures `ProductPrivate` paths (such as `providers/` and
755    /// `MERRY_API_KEY_FILE`) that remain high-risk once-only approval targets
756    /// even when OS sandboxing is disabled.
757    #[must_use]
758    pub fn with_product_private_paths(
759        mut self,
760        cwd_root: PathBuf,
761        paths: impl IntoIterator<Item = PathBuf>,
762    ) -> Self {
763        self.cwd_root = Some(cwd_root);
764        self.product_private_paths = paths
765            .into_iter()
766            .map(|path| crate::resolve_host_path(&path))
767            .collect();
768        self
769    }
770}
771
772impl PermissionedProcessRunnerFactory for UnrestrictedPermissionedProcessRunnerFactory {
773    fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
774        if self.product_private_paths.is_empty() {
775            return false;
776        }
777        request.requested().iter().any(|capability| {
778            let merry_runtime::RequestedCapability::Path(requested) = capability else {
779                return false;
780            };
781            let raw = std::path::Path::new(requested.path());
782            let materialized = if raw.is_absolute() {
783                raw.to_path_buf()
784            } else if let Some(root) = &self.cwd_root {
785                root.join(raw)
786            } else {
787                raw.to_path_buf()
788            };
789            merry_runtime::is_protected_in_unrestricted_mode(
790                &self.product_private_paths,
791                &materialized,
792            )
793        })
794    }
795
796    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
797        Arc::clone(&self.runner)
798    }
799}
800
801#[cfg(test)]
802#[path = "backend_tests.rs"]
803mod tests;