Skip to main content

merry_process/
lib.rs

1//! Host-process adapters for Merry's provider-neutral process contract.
2//!
3//! [`merry_runtime`] owns process intent, admission, permission requests, and
4//! execution evidence. This crate owns the host-facing runner selection and
5//! binds the runners used by one runtime owner to one [`ProcessSession`]. A
6//! platform can replace the concrete backend without changing coding
7//! composition or runtime call sites.
8
9mod baseline;
10#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
11mod confinement;
12#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
13#[path = "confinement/unsupported.rs"]
14mod confinement;
15mod gpg;
16mod host_path;
17mod host_resources;
18mod process_runner;
19
20pub use baseline::{default_development_path_rules, default_development_path_rules_with_env};
21pub use confinement::{probe_workspace_sandbox, sandbox_helper_main, sandbox_helper_requested};
22pub use gpg::GpgAgentSockets;
23pub use host_path::resolve_host_path;
24pub use host_resources::{HostPathKind, HostPathMetadata, ssh_known_hosts};
25
26pub use process_runner::{
27    DEFAULT_REMOVED_ENV_PREFIX, ProcessEnvIsolation, ProcessSessionPermissions, TokioProcessRunner,
28    action_process_path,
29};
30
31#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
32pub use process_runner::{
33    WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory,
34};
35
36use merry_core::HostPathPolicy;
37use merry_runtime::{
38    AcceptedLocalWorkspaceProcessAdmission, HostIntegration, PathAccess, PathAccessRule,
39    PathAccessRuleSource, PermissionRequest, PermissionedProcessRunnerFactory, ProcessRunner,
40    ProcessRunnerError, ProcessSessionPermissionView,
41};
42use std::{
43    ffi::OsString,
44    path::{Path, PathBuf},
45    sync::Arc,
46};
47use thiserror::Error;
48
49/// Semantic process backend behavior requested by an application surface.
50///
51/// The selected behavior is intentionally independent of the operating system.
52/// A platform backend may implement [`Isolated`](Self::Isolated) with its
53/// native mechanism or report that the behavior is unavailable; callers do not
54/// need to name Landlock, seccomp, or another concrete mechanism.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum ProcessBackendMode {
57    /// Run actions in the host process environment, subject to runtime policy.
58    Host,
59    /// Request the platform's isolated local-process behavior.
60    Isolated,
61}
62
63/// Errors raised while selecting or constructing a host-process backend.
64///
65/// Execution failures remain [`merry_runtime::ProcessRunnerError`]. This error
66/// belongs to the adapter layer because it also represents a platform backend
67/// that is not available for the requested semantic mode.
68#[derive(Debug, Error, Clone, PartialEq, Eq)]
69pub enum ProcessBackendError {
70    /// The concrete runner rejected its configuration.
71    #[error("process backend configuration failed: {source}")]
72    Runner {
73        /// The runner configuration failure.
74        #[source]
75        source: ProcessRunnerError,
76    },
77    /// The requested isolated behavior has no implementation on this target.
78    #[error(
79        "isolated local process backend is unavailable on target operating system `{target_os}`"
80    )]
81    UnsupportedIsolation {
82        /// Rust's target-operating-system identifier.
83        target_os: &'static str,
84    },
85}
86
87impl From<ProcessRunnerError> for ProcessBackendError {
88    fn from(source: ProcessRunnerError) -> Self {
89        Self::Runner { source }
90    }
91}
92
93/// One process execution boundary used by a runtime instance.
94///
95/// The admission and both runner capabilities are kept together so callers
96/// cannot accidentally pair a runner with a permission factory from another
97/// backend configuration. Child runtimes obtain their process session through
98/// [`ProcessBackend::new_session`] or [`ProcessBackend::new_session_with`],
99/// whose backend controls session isolation.
100#[derive(Clone)]
101pub struct ProcessSession {
102    admission: AcceptedLocalWorkspaceProcessAdmission,
103    runner: Arc<dyn ProcessRunner>,
104    permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
105    permission_view: Option<ProcessSessionPermissionView>,
106}
107
108impl ProcessSession {
109    /// Creates a session from an explicit, trusted adapter boundary.
110    ///
111    /// Production callers should select [`LocalProcessBackend::new`] so the
112    /// admission, runner, and reviewed-action factory are produced by one
113    /// backend implementation. This constructor exists for adapters and
114    /// deterministic fixtures that already own all three components.
115    #[must_use]
116    pub fn from_parts(
117        admission: AcceptedLocalWorkspaceProcessAdmission,
118        runner: Arc<dyn ProcessRunner>,
119        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
120    ) -> Self {
121        Self {
122            admission,
123            runner,
124            permissioned_factory,
125            permission_view: None,
126        }
127    }
128
129    /// Attaches a read-only view of this session's retained permissions so child
130    /// runtimes may inherit already-approved ordinary capabilities without
131    /// mutating the parent session.
132    #[must_use]
133    pub fn with_permission_view(mut self, view: ProcessSessionPermissionView) -> Self {
134        self.permission_view = Some(view);
135        self
136    }
137
138    /// Returns the runtime admission selected for this process boundary.
139    #[must_use]
140    pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
141        self.admission
142    }
143
144    /// Returns the runner for ordinary process actions.
145    #[must_use]
146    pub fn runner(&self) -> Arc<dyn ProcessRunner> {
147        Arc::clone(&self.runner)
148    }
149
150    /// Returns the factory for reviewed process actions.
151    #[must_use]
152    pub fn permissioned_factory(&self) -> Arc<dyn PermissionedProcessRunnerFactory> {
153        Arc::clone(&self.permissioned_factory)
154    }
155
156    /// Returns a read-only view of capabilities retained by this session, when
157    /// backed by a session-scoped permission store.
158    #[must_use]
159    pub fn permission_view(&self) -> Option<ProcessSessionPermissionView> {
160        self.permission_view.clone()
161    }
162}
163
164/// Request options for deriving a scoped [`ProcessSession`] from a [`ProcessBackend`].
165#[derive(Debug, Clone)]
166pub struct ProcessSessionRequest {
167    workspace_root: Option<PathBuf>,
168    workspace_writable: bool,
169    inherited_permissions: Option<ProcessSessionPermissionView>,
170    extra_path_rules: Vec<PathAccessRule>,
171}
172
173impl Default for ProcessSessionRequest {
174    fn default() -> Self {
175        Self {
176            workspace_root: None,
177            workspace_writable: true,
178            inherited_permissions: None,
179            extra_path_rules: Vec::new(),
180        }
181    }
182}
183
184impl ProcessSessionRequest {
185    /// Creates a default session request inheriting the backend's workspace root
186    /// and writability.
187    #[must_use]
188    pub fn new() -> Self {
189        Self::default()
190    }
191
192    /// Overrides the workspace root directory for the new session (for example,
193    /// an isolated git worktree).
194    #[must_use]
195    pub fn with_workspace_root(mut self, workspace_root: impl Into<PathBuf>) -> Self {
196        self.workspace_root = Some(workspace_root.into());
197        self
198    }
199
200    /// Keeps the workspace readable and not writable for isolated actions in
201    /// this session.
202    #[must_use]
203    pub fn read_only_workspace(mut self) -> Self {
204        self.workspace_writable = false;
205        self
206    }
207
208    /// Sets whether isolated actions in this session may write inside the
209    /// workspace root.
210    ///
211    /// A request cannot widen a backend that was already configured read-only.
212    #[must_use]
213    pub fn with_workspace_writable(mut self, writable: bool) -> Self {
214        self.workspace_writable = writable;
215        self
216    }
217
218    /// Seeds the new session with a read-only snapshot of an existing session's
219    /// approved ordinary capabilities.
220    #[must_use]
221    pub fn with_inherited_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
222        self.inherited_permissions = Some(view);
223        self
224    }
225
226    /// Appends additional filesystem rules for the new session.
227    #[must_use]
228    pub fn with_extra_path_rules(
229        mut self,
230        rules: impl IntoIterator<Item = PathAccessRule>,
231    ) -> Self {
232        self.extra_path_rules = rules.into_iter().collect();
233        self
234    }
235
236    /// Returns the optional workspace root override.
237    #[must_use]
238    pub fn workspace_root(&self) -> Option<&Path> {
239        self.workspace_root.as_deref()
240    }
241
242    /// Returns whether the caller requested workspace writability.
243    #[must_use]
244    pub const fn workspace_writable(&self) -> bool {
245        self.workspace_writable
246    }
247
248    /// Returns the optional inherited permission view.
249    #[must_use]
250    pub fn inherited_permissions(&self) -> Option<&ProcessSessionPermissionView> {
251        self.inherited_permissions.as_ref()
252    }
253
254    /// Returns any extra filesystem access rules attached to this request.
255    #[must_use]
256    pub fn extra_path_rules(&self) -> &[PathAccessRule] {
257        &self.extra_path_rules
258    }
259}
260
261/// Stable host-process backend boundary consumed by coding composition.
262///
263/// The trait deliberately says nothing about how a platform enforces the
264/// selected behavior. Linux confines each action with Landlock and seccomp.
265/// Other targets report that isolation is unavailable instead of silently
266/// running on the host.
267pub trait ProcessBackend: Send + Sync {
268    /// Creates the process session for one runtime owner.
269    ///
270    /// Each call returns a session with the backend's configured admission and
271    /// runner capabilities. Backends may use a fresh session-scoped capability
272    /// store for every call, which keeps parent and child runtime state isolated.
273    fn new_session(&self) -> ProcessSession;
274
275    /// Creates a process session configured with scoped request options.
276    ///
277    /// The default implementation delegates to [`Self::new_session`] for custom
278    /// test or adapter backends that do not vary session parameters.
279    ///
280    /// # Errors
281    ///
282    /// Returns a [`ProcessBackendError`] when the requested workspace root,
283    /// sandbox rules, or inherited permissions cannot be validated.
284    fn new_session_with(
285        &self,
286        _request: ProcessSessionRequest,
287    ) -> Result<ProcessSession, ProcessBackendError> {
288        Ok(self.new_session())
289    }
290}
291
292/// Inputs shared by local process backend implementations.
293#[derive(Debug, Clone)]
294pub struct ProcessBackendOptions {
295    /// Trusted filesystem rules installed for isolated actions.
296    path_rules: Vec<PathAccessRule>,
297    /// Isolated-session capability ceiling, not a grant to an ordinary runner.
298    network_requests_allowed: bool,
299    /// When false, the workspace itself is readable and not writable.
300    workspace_writable: bool,
301    /// Host integrations the embedding application authorizes for isolated actions.
302    host_integrations: Vec<HostIntegration>,
303    gpg_agent_sockets: Option<GpgAgentSockets>,
304    /// Environment assignments validated and applied by the host backend.
305    environment_overrides: Vec<(OsString, OsString)>,
306    /// Environment variable isolation policy stripped from every child process.
307    env_isolation: ProcessEnvIsolation,
308}
309
310impl Default for ProcessBackendOptions {
311    fn default() -> Self {
312        Self {
313            path_rules: Vec::new(),
314            network_requests_allowed: true,
315            workspace_writable: true,
316            host_integrations: Vec::new(),
317            gpg_agent_sockets: None,
318            environment_overrides: Vec::new(),
319            env_isolation: ProcessEnvIsolation::default(),
320        }
321    }
322}
323
324impl ProcessBackendOptions {
325    /// Creates default options without preauthorized process capabilities.
326    #[must_use]
327    pub fn new() -> Self {
328        Self::default()
329    }
330
331    /// Sets trusted filesystem rules installed for isolated actions.
332    #[must_use]
333    pub fn with_path_rules(mut self, path_rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
334        self.path_rules = path_rules.into_iter().collect();
335        self
336    }
337
338    /// Appends filesystem rules installed for isolated actions.
339    #[must_use]
340    pub fn extend_path_rules(
341        mut self,
342        path_rules: impl IntoIterator<Item = PathAccessRule>,
343    ) -> Self {
344        self.path_rules.extend(path_rules);
345        self
346    }
347
348    /// Appends the default local development toolchain and cache baseline rules.
349    #[must_use]
350    pub fn with_default_development_baseline(self, home: &Path) -> Self {
351        self.extend_path_rules(default_development_path_rules(home))
352    }
353
354    /// Appends Merry's product path rules from the shared [`HostPathPolicy`]
355    /// contract (writable config/skills, writable durable memory, read-only
356    /// state/history, and denied private credentials).
357    #[must_use]
358    pub fn with_host_path_policy(mut self, policy: &HostPathPolicy) -> Self {
359        for path in policy.product_writable_config() {
360            self.path_rules.push(PathAccessRule::new(
361                path.clone(),
362                PathAccess::ReadWrite,
363                PathAccessRuleSource::ProductConfig,
364            ));
365        }
366        if let Some(memory_root) = policy.durable_memory_root() {
367            self.path_rules.push(PathAccessRule::new(
368                memory_root.to_path_buf(),
369                PathAccess::ReadWrite,
370                PathAccessRuleSource::DurableMemory,
371            ));
372        }
373        for path in policy.product_readonly() {
374            self.path_rules.push(PathAccessRule::new(
375                path.clone(),
376                PathAccess::ReadOnly,
377                PathAccessRuleSource::ProductReadOnly,
378            ));
379        }
380        for path in policy.denied() {
381            self.path_rules.push(PathAccessRule::new(
382                path.clone(),
383                PathAccess::Deny,
384                PathAccessRuleSource::ProductPrivate,
385            ));
386        }
387        self
388    }
389
390    /// Sets whether isolated process sessions may request network capability.
391    ///
392    /// Defaults to true, which still requires approval for each action. False
393    /// rejects network requests before review. Explicit host execution is not
394    /// isolated and is not restricted by this ceiling.
395    #[must_use]
396    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
397        self.network_requests_allowed = allowed;
398        self
399    }
400
401    /// Keeps the workspace readable and not writable for isolated actions.
402    ///
403    /// Baseline paths such as `/tmp` stay writable. Host execution ignores this.
404    #[must_use]
405    pub fn read_only_workspace(mut self) -> Self {
406        self.workspace_writable = false;
407        self
408    }
409
410    /// Sets host integrations the embedding application authorizes.
411    ///
412    /// The embedding application owns this decision; the backend treats the
413    /// listed integrations as part of the ordinary action baseline instead of
414    /// requiring a per-action request for them. Merry's CLI derives the list
415    /// from user-trusted global configuration, which preauthorizes the inner
416    /// action sandbox; project-local configuration never does. Endpoint
417    /// validation and path policy still apply per action, so a `deny_paths`
418    /// entry can keep a listed integration masked when it is not inside a
419    /// broader grant.
420    #[must_use]
421    pub fn with_host_integrations(
422        mut self,
423        host_integrations: impl IntoIterator<Item = HostIntegration>,
424    ) -> Self {
425        self.host_integrations = host_integrations.into_iter().collect();
426        self
427    }
428
429    /// Installs explicitly discovered native and auxiliary GnuPG socket paths.
430    #[must_use]
431    pub fn with_gpg_agent_sockets(mut self, sockets: GpgAgentSockets) -> Self {
432        self.gpg_agent_sockets = Some(sockets);
433        self
434    }
435
436    /// Sets environment assignments that the backend validates before applying.
437    #[must_use]
438    pub fn with_environment_overrides(
439        mut self,
440        environment_overrides: impl IntoIterator<Item = (OsString, OsString)>,
441    ) -> Self {
442        self.environment_overrides = environment_overrides.into_iter().collect();
443        self
444    }
445
446    /// Replaces the environment-variable isolation policy enforced across
447    /// both isolated and host process runners.
448    #[must_use]
449    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
450        self.env_isolation = env_isolation;
451        self
452    }
453
454    /// Returns the trusted filesystem rules installed for isolated actions.
455    #[must_use]
456    pub fn path_rules(&self) -> &[PathAccessRule] {
457        &self.path_rules
458    }
459
460    /// Returns whether isolated sessions may request, not preauthorize, network access.
461    #[must_use]
462    pub fn network_requests_allowed(&self) -> bool {
463        self.network_requests_allowed
464    }
465
466    /// Returns host integrations already approved by the embedding application.
467    #[must_use]
468    pub fn host_integrations(&self) -> &[HostIntegration] {
469        &self.host_integrations
470    }
471
472    /// Returns the validated environment assignments applied by the backend.
473    #[must_use]
474    pub fn environment_overrides(&self) -> &[(OsString, OsString)] {
475        &self.environment_overrides
476    }
477}
478
479/// Current local host-process backend.
480///
481/// The backend owns the current host implementation choice. Its public
482/// session contract is intentionally independent of that choice, so adding a
483/// platform-specific backend does not change coding profile or runtime APIs.
484#[derive(Clone)]
485pub struct LocalProcessBackend {
486    new_session: Arc<dyn Fn() -> ProcessSession + Send + Sync>,
487    new_session_with: Arc<
488        dyn Fn(ProcessSessionRequest) -> Result<ProcessSession, ProcessBackendError> + Send + Sync,
489    >,
490}
491
492impl LocalProcessBackend {
493    /// Creates a fixed backend from one already constructed session.
494    ///
495    /// This is intended for trusted adapters and deterministic test fixtures.
496    /// Platform-selected production backends should use [`Self::new`] so the
497    /// admission is created together with the concrete enforcement strategy.
498    #[must_use]
499    pub fn from_session(session: ProcessSession) -> Self {
500        let child_session = session.clone();
501        let scoped_session = session;
502        Self {
503            new_session: Arc::new(move || child_session.clone()),
504            new_session_with: Arc::new(move |_request| Ok(scoped_session.clone())),
505        }
506    }
507
508    #[cfg(test)]
509    fn from_parts(
510        admission: AcceptedLocalWorkspaceProcessAdmission,
511        runner: Arc<dyn ProcessRunner>,
512        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
513    ) -> Self {
514        Self::from_session(ProcessSession::from_parts(
515            admission,
516            runner,
517            permissioned_factory,
518        ))
519    }
520
521    /// Creates a platform-selected local process backend.
522    ///
523    /// # Errors
524    ///
525    /// Returns a [`ProcessBackendError`] when the selected backend cannot be
526    /// configured or the requested isolated behavior is unavailable.
527    pub fn new(
528        workspace_root: impl Into<PathBuf>,
529        mode: ProcessBackendMode,
530        options: ProcessBackendOptions,
531    ) -> Result<Self, ProcessBackendError> {
532        Self::new_with_shared_state(workspace_root, mode, options, None, None)
533    }
534
535    fn new_with_shared_state(
536        workspace_root: impl Into<PathBuf>,
537        mode: ProcessBackendMode,
538        options: ProcessBackendOptions,
539        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
540        shared_permissions: Option<ProcessSessionPermissions>,
541    ) -> Result<Self, ProcessBackendError> {
542        match mode {
543            ProcessBackendMode::Host => Self::unrestricted_with_shared_state(
544                workspace_root,
545                options,
546                shared_background,
547                shared_permissions,
548            ),
549            ProcessBackendMode::Isolated => Self::sandboxed_with_shared_state(
550                workspace_root,
551                options,
552                shared_background,
553                shared_permissions,
554            ),
555        }
556    }
557
558    /// Creates the current host-process implementation without an inner
559    /// operating-system sandbox.
560    ///
561    /// # Errors
562    ///
563    /// Returns a [`ProcessBackendError::Runner`] when an environment override
564    /// cannot be validated by the host runner.
565    pub fn unrestricted(
566        workspace_root: impl Into<PathBuf>,
567        options: ProcessBackendOptions,
568    ) -> Result<Self, ProcessBackendError> {
569        Self::unrestricted_with_shared_state(workspace_root, options, None, None)
570    }
571
572    fn unrestricted_with_shared_state(
573        workspace_root: impl Into<PathBuf>,
574        options: ProcessBackendOptions,
575        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
576        shared_permissions: Option<ProcessSessionPermissions>,
577    ) -> Result<Self, ProcessBackendError> {
578        let workspace_root = workspace_root.into();
579        let environment_overrides = options.environment_overrides;
580        let env_isolation = options.env_isolation;
581        let mut runner = TokioProcessRunner::new_at_workspace_root(workspace_root.clone())
582            .with_env_isolation(env_isolation.clone())?
583            .with_environment_overrides(environment_overrides.clone())?;
584        if let Some(background) = shared_background {
585            runner = runner.with_background(background);
586        }
587        let runner = Arc::new(runner);
588        let permissioned_factory = Arc::new(UnrestrictedPermissionedProcessRunnerFactory::new(
589            Arc::clone(&runner) as Arc<dyn ProcessRunner>,
590        ));
591        let mut default_session = ProcessSession::from_parts(
592            AcceptedLocalWorkspaceProcessAdmission::accept_host(),
593            runner,
594            permissioned_factory,
595        );
596        if let Some(permissions) = shared_permissions {
597            default_session = default_session.with_permission_view(permissions.view());
598        }
599        let fallback_session = default_session.clone();
600        Ok(Self {
601            new_session: Arc::new(move || default_session.clone()),
602            new_session_with: Arc::new(move |request| {
603                let Some(root_override) = request.workspace_root else {
604                    return Ok(fallback_session.clone());
605                };
606                let runner = Arc::new(
607                    TokioProcessRunner::new_at_workspace_root(root_override)
608                        .with_env_isolation(env_isolation.clone())?
609                        .with_environment_overrides(environment_overrides.clone())?,
610                );
611                let permissioned_factory =
612                    Arc::new(UnrestrictedPermissionedProcessRunnerFactory::new(
613                        Arc::clone(&runner) as Arc<dyn ProcessRunner>,
614                    ));
615                Ok(ProcessSession::from_parts(
616                    AcceptedLocalWorkspaceProcessAdmission::accept_host(),
617                    runner,
618                    permissioned_factory,
619                ))
620            }),
621        })
622    }
623
624    /// Creates the current isolated local-process implementation.
625    ///
626    /// On Linux, each action is confined with Landlock and, unless that action
627    /// was granted network, a seccomp filter. On macOS, each action is confined
628    /// with a Seatbelt profile. Other targets return
629    /// [`ProcessBackendError::UnsupportedIsolation`].
630    ///
631    /// # Errors
632    ///
633    /// Returns a [`ProcessBackendError`] when the workspace or sandbox
634    /// environment is invalid, a configured path cannot be enforced, or this
635    /// target has no isolated backend.
636    pub fn sandboxed(
637        workspace_root: impl Into<PathBuf>,
638        options: ProcessBackendOptions,
639    ) -> Result<Self, ProcessBackendError> {
640        Self::sandboxed_with_shared_state(workspace_root, options, None, None)
641    }
642}
643
644#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
645impl LocalProcessBackend {
646    fn sandboxed_with_shared_state(
647        workspace_root: impl Into<PathBuf>,
648        options: ProcessBackendOptions,
649        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
650        shared_permissions: Option<ProcessSessionPermissions>,
651    ) -> Result<Self, ProcessBackendError> {
652        let workspace_root = workspace_root.into();
653        let mut environment = WorkspaceProcessEnvironment::from_current_process()
654            .with_host_integrations(options.host_integrations)
655            .with_env_isolation(options.env_isolation)?
656            .with_overrides(options.environment_overrides)?
657            .validate_for_workspace(&workspace_root)?;
658        if let Some(sockets) = options.gpg_agent_sockets {
659            environment = environment.with_gpg_agent_sockets(sockets);
660        }
661        let mut rules_runner =
662            WorkspaceProcessRunner::new_at_workspace_root(workspace_root.clone())
663                .with_environment(environment.clone())
664                .with_path_rules(options.path_rules.iter().cloned());
665        if !options.workspace_writable {
666            rules_runner = rules_runner.read_only_workspace();
667        }
668        rules_runner.ensure_sandbox_rules()?;
669        Ok(Self::from_sandboxed_parts(
670            workspace_root,
671            environment,
672            options.path_rules,
673            options.network_requests_allowed,
674            options.workspace_writable,
675            shared_background,
676            shared_permissions,
677        ))
678    }
679
680    fn from_sandboxed_parts(
681        workspace_root: PathBuf,
682        environment: WorkspaceProcessEnvironment,
683        path_rules: Vec<PathAccessRule>,
684        network_requests_allowed: bool,
685        workspace_writable: bool,
686        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
687        shared_permissions: Option<ProcessSessionPermissions>,
688    ) -> Self {
689        let child_workspace_root = workspace_root.clone();
690        let child_environment = environment.clone();
691        let child_path_rules = path_rules.clone();
692        let scoped_workspace_root = workspace_root;
693        let scoped_environment = environment;
694        let scoped_path_rules = path_rules;
695        Self {
696            new_session: Arc::new(move || {
697                Self::sandboxed_session(
698                    &child_workspace_root,
699                    &child_environment,
700                    &child_path_rules,
701                    network_requests_allowed,
702                    workspace_writable,
703                    shared_permissions.clone().unwrap_or_default(),
704                    shared_background.clone().unwrap_or_default(),
705                )
706            }),
707            new_session_with: Arc::new(move |request| {
708                let target_root = request
709                    .workspace_root
710                    .as_deref()
711                    .unwrap_or(&scoped_workspace_root);
712                // Intersection: a scoped session can narrow a writable backend
713                // to read-only, never widen a read-only backend to writable.
714                let effective_writable = workspace_writable && request.workspace_writable;
715                let session_permissions = match request.inherited_permissions.as_ref() {
716                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
717                    None => ProcessSessionPermissions::new(),
718                };
719                let mut combined_rules =
720                    Vec::with_capacity(scoped_path_rules.len() + request.extra_path_rules.len());
721                combined_rules.extend(scoped_path_rules.iter().cloned());
722                combined_rules.extend(request.extra_path_rules);
723                let validated_env = if request.workspace_root.is_some() {
724                    scoped_environment
725                        .clone()
726                        .validate_for_workspace(target_root)?
727                } else {
728                    scoped_environment.clone()
729                };
730                if request.workspace_root.is_some() || !combined_rules.is_empty() {
731                    let mut rules_runner =
732                        WorkspaceProcessRunner::new_at_workspace_root(target_root)
733                            .with_environment(validated_env.clone())
734                            .with_path_rules(combined_rules.iter().cloned());
735                    if !effective_writable {
736                        rules_runner = rules_runner.read_only_workspace();
737                    }
738                    rules_runner.ensure_sandbox_rules()?;
739                }
740                Ok(Self::sandboxed_session(
741                    target_root,
742                    &validated_env,
743                    &combined_rules,
744                    network_requests_allowed,
745                    effective_writable,
746                    session_permissions,
747                    crate::process_runner::BackgroundSupervisor::new(),
748                ))
749            }),
750        }
751    }
752
753    fn sandboxed_session(
754        workspace_root: &Path,
755        environment: &WorkspaceProcessEnvironment,
756        path_rules: &[PathAccessRule],
757        network_requests_allowed: bool,
758        workspace_writable: bool,
759        session_permissions: ProcessSessionPermissions,
760        background: crate::process_runner::BackgroundSupervisor,
761    ) -> ProcessSession {
762        let permission_view = session_permissions.view();
763        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(workspace_root)
764            .with_environment(environment.clone())
765            .with_path_rules(path_rules.iter().cloned())
766            .with_background(background.clone());
767        let mut permissioned_factory =
768            WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace_root)
769                .with_environment(environment.clone())
770                .with_path_rules(path_rules.iter().cloned())
771                .with_network_requests_allowed(network_requests_allowed)
772                .with_background(background);
773        if !workspace_writable {
774            runner = runner.read_only_workspace();
775            permissioned_factory = permissioned_factory.read_only_workspace();
776        }
777        let runner = runner.with_session_permissions(session_permissions.clone());
778        let permissioned_factory =
779            permissioned_factory.with_session_permissions(session_permissions);
780        ProcessSession::from_parts(
781            AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
782            Arc::new(runner),
783            Arc::new(permissioned_factory),
784        )
785        .with_permission_view(permission_view)
786    }
787}
788
789#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
790impl LocalProcessBackend {
791    fn sandboxed_with_shared_state(
792        workspace_root: impl Into<PathBuf>,
793        options: ProcessBackendOptions,
794        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
795        shared_permissions: Option<ProcessSessionPermissions>,
796    ) -> Result<Self, ProcessBackendError> {
797        let _ = (
798            workspace_root.into(),
799            options,
800            shared_background,
801            shared_permissions,
802        );
803        Err(ProcessBackendError::UnsupportedIsolation {
804            target_os: std::env::consts::OS,
805        })
806    }
807}
808
809impl ProcessBackend for LocalProcessBackend {
810    fn new_session(&self) -> ProcessSession {
811        (self.new_session)()
812    }
813
814    fn new_session_with(
815        &self,
816        request: ProcessSessionRequest,
817    ) -> Result<ProcessSession, ProcessBackendError> {
818        (self.new_session_with)(request)
819    }
820}
821
822/// Process backend whose active mode and sandbox options can be swapped live
823/// while keeping the parent session's background process supervisor and
824/// live-updatable permission view intact.
825///
826/// Newly spawned child sessions via [`ProcessBackend::new_session_with`] read
827/// the latest swapped backend automatically, while [`Self::replace`] clears
828/// stale session-retained grants and returns a new parent [`ProcessSession`]
829/// bound to the same background supervisor and permission view so retained
830/// background processes remain inspectable/stoppable and future subagents
831/// inherit only post-reload grants.
832pub struct LiveProcessBackend {
833    state: std::sync::RwLock<LocalProcessBackend>,
834    session_background: crate::process_runner::BackgroundSupervisor,
835    session_permissions: ProcessSessionPermissions,
836}
837
838impl LiveProcessBackend {
839    /// Creates a live-swappable local process backend.
840    ///
841    /// # Errors
842    ///
843    /// Returns a [`ProcessBackendError`] when the initial backend configuration
844    /// is invalid or the requested isolated sandbox is unavailable.
845    pub fn new(
846        workspace_root: impl Into<PathBuf>,
847        mode: ProcessBackendMode,
848        options: ProcessBackendOptions,
849    ) -> Result<Self, ProcessBackendError> {
850        let session_background = crate::process_runner::BackgroundSupervisor::new();
851        let session_permissions = ProcessSessionPermissions::new();
852        let backend = LocalProcessBackend::new_with_shared_state(
853            workspace_root,
854            mode,
855            options,
856            Some(session_background.clone()),
857            Some(session_permissions.clone()),
858        )?;
859        Ok(Self {
860            state: std::sync::RwLock::new(backend),
861            session_background,
862            session_permissions,
863        })
864    }
865
866    /// Wraps a fixed process session (primarily for tests and custom adapters).
867    #[must_use]
868    pub fn from_session(session: ProcessSession) -> Self {
869        Self {
870            state: std::sync::RwLock::new(LocalProcessBackend::from_session(session)),
871            session_background: crate::process_runner::BackgroundSupervisor::new(),
872            session_permissions: ProcessSessionPermissions::new(),
873        }
874    }
875
876    /// Validates and installs a replacement backend configuration, returning a
877    /// new parent [`ProcessSession`] sharing the existing background supervisor
878    /// and a freshly cleared session permission store.
879    ///
880    /// If validation fails, the active backend and retained session permissions
881    /// remain unchanged.
882    ///
883    /// # Errors
884    ///
885    /// Returns a [`ProcessBackendError`] when the new configuration is invalid
886    /// or the requested isolated sandbox is unavailable.
887    pub fn replace(
888        &self,
889        workspace_root: impl Into<PathBuf>,
890        mode: ProcessBackendMode,
891        options: ProcessBackendOptions,
892    ) -> Result<ProcessSession, ProcessBackendError> {
893        let next = LocalProcessBackend::new_with_shared_state(
894            workspace_root,
895            mode,
896            options,
897            Some(self.session_background.clone()),
898            Some(self.session_permissions.clone()),
899        )?;
900        self.session_permissions.clear()?;
901        let next_session = next.new_session();
902        let mut guard = self
903            .state
904            .write()
905            .unwrap_or_else(std::sync::PoisonError::into_inner);
906        *guard = next;
907        Ok(next_session)
908    }
909}
910
911impl ProcessBackend for LiveProcessBackend {
912    fn new_session(&self) -> ProcessSession {
913        self.state
914            .read()
915            .unwrap_or_else(std::sync::PoisonError::into_inner)
916            .new_session()
917    }
918
919    fn new_session_with(
920        &self,
921        request: ProcessSessionRequest,
922    ) -> Result<ProcessSession, ProcessBackendError> {
923        self.state
924            .read()
925            .unwrap_or_else(std::sync::PoisonError::into_inner)
926            .new_session_with(request)
927    }
928}
929
930/// Permissioned runner factory for the explicit host-process backend.
931///
932/// The host backend already exposes the process to the operating system, so a
933/// reviewed capability request reuses its runner. Runtime admission and action
934/// evidence remain active around the returned runner.
935#[derive(Clone)]
936pub struct UnrestrictedPermissionedProcessRunnerFactory {
937    runner: Arc<dyn ProcessRunner>,
938}
939
940impl UnrestrictedPermissionedProcessRunnerFactory {
941    /// Creates a factory that reuses the host-process runner.
942    #[must_use]
943    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
944        Self { runner }
945    }
946}
947
948impl PermissionedProcessRunnerFactory for UnrestrictedPermissionedProcessRunnerFactory {
949    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
950        Arc::clone(&self.runner)
951    }
952}
953
954#[cfg(test)]
955mod tests;