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(any(target_os = "linux", target_os = "macos"))]
11mod confinement;
12#[cfg(not(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(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    #[cfg(any(target_os = "linux", target_os = "macos"))]
644    fn sandboxed_with_shared_state(
645        workspace_root: impl Into<PathBuf>,
646        options: ProcessBackendOptions,
647        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
648        shared_permissions: Option<ProcessSessionPermissions>,
649    ) -> Result<Self, ProcessBackendError> {
650        let workspace_root = workspace_root.into();
651        let mut environment = WorkspaceProcessEnvironment::from_current_process()
652            .with_host_integrations(options.host_integrations)
653            .with_env_isolation(options.env_isolation)?
654            .with_overrides(options.environment_overrides)?
655            .validate_for_workspace(&workspace_root)?;
656        if let Some(sockets) = options.gpg_agent_sockets {
657            environment = environment.with_gpg_agent_sockets(sockets);
658        }
659        let mut rules_runner =
660            WorkspaceProcessRunner::new_at_workspace_root(workspace_root.clone())
661                .with_environment(environment.clone())
662                .with_path_rules(options.path_rules.iter().cloned());
663        if !options.workspace_writable {
664            rules_runner = rules_runner.read_only_workspace();
665        }
666        rules_runner.ensure_sandbox_rules()?;
667        Ok(Self::from_sandboxed_parts(
668            workspace_root,
669            environment,
670            options.path_rules,
671            options.network_requests_allowed,
672            options.workspace_writable,
673            shared_background,
674            shared_permissions,
675        ))
676    }
677
678    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
679    fn sandboxed_with_shared_state(
680        workspace_root: impl Into<PathBuf>,
681        options: ProcessBackendOptions,
682        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
683        shared_permissions: Option<ProcessSessionPermissions>,
684    ) -> Result<Self, ProcessBackendError> {
685        let _ = (
686            workspace_root.into(),
687            options,
688            shared_background,
689            shared_permissions,
690        );
691        Err(ProcessBackendError::UnsupportedIsolation {
692            target_os: std::env::consts::OS,
693        })
694    }
695
696    #[cfg(any(target_os = "linux", target_os = "macos"))]
697    fn from_sandboxed_parts(
698        workspace_root: PathBuf,
699        environment: WorkspaceProcessEnvironment,
700        path_rules: Vec<PathAccessRule>,
701        network_requests_allowed: bool,
702        workspace_writable: bool,
703        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
704        shared_permissions: Option<ProcessSessionPermissions>,
705    ) -> Self {
706        let child_workspace_root = workspace_root.clone();
707        let child_environment = environment.clone();
708        let child_path_rules = path_rules.clone();
709        let scoped_workspace_root = workspace_root;
710        let scoped_environment = environment;
711        let scoped_path_rules = path_rules;
712        Self {
713            new_session: Arc::new(move || {
714                Self::sandboxed_session(
715                    &child_workspace_root,
716                    &child_environment,
717                    &child_path_rules,
718                    network_requests_allowed,
719                    workspace_writable,
720                    shared_permissions.clone().unwrap_or_default(),
721                    shared_background.clone().unwrap_or_default(),
722                )
723            }),
724            new_session_with: Arc::new(move |request| {
725                let target_root = request
726                    .workspace_root
727                    .as_deref()
728                    .unwrap_or(&scoped_workspace_root);
729                // Intersection: a scoped session can narrow a writable backend
730                // to read-only, never widen a read-only backend to writable.
731                let effective_writable = workspace_writable && request.workspace_writable;
732                let session_permissions = match request.inherited_permissions.as_ref() {
733                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
734                    None => ProcessSessionPermissions::new(),
735                };
736                let mut combined_rules =
737                    Vec::with_capacity(scoped_path_rules.len() + request.extra_path_rules.len());
738                combined_rules.extend(scoped_path_rules.iter().cloned());
739                combined_rules.extend(request.extra_path_rules);
740                let validated_env = if request.workspace_root.is_some() {
741                    scoped_environment
742                        .clone()
743                        .validate_for_workspace(target_root)?
744                } else {
745                    scoped_environment.clone()
746                };
747                if request.workspace_root.is_some() || !combined_rules.is_empty() {
748                    let mut rules_runner =
749                        WorkspaceProcessRunner::new_at_workspace_root(target_root)
750                            .with_environment(validated_env.clone())
751                            .with_path_rules(combined_rules.iter().cloned());
752                    if !effective_writable {
753                        rules_runner = rules_runner.read_only_workspace();
754                    }
755                    rules_runner.ensure_sandbox_rules()?;
756                }
757                Ok(Self::sandboxed_session(
758                    target_root,
759                    &validated_env,
760                    &combined_rules,
761                    network_requests_allowed,
762                    effective_writable,
763                    session_permissions,
764                    crate::process_runner::BackgroundSupervisor::new(),
765                ))
766            }),
767        }
768    }
769
770    #[cfg(any(target_os = "linux", target_os = "macos"))]
771    fn sandboxed_session(
772        workspace_root: &Path,
773        environment: &WorkspaceProcessEnvironment,
774        path_rules: &[PathAccessRule],
775        network_requests_allowed: bool,
776        workspace_writable: bool,
777        session_permissions: ProcessSessionPermissions,
778        background: crate::process_runner::BackgroundSupervisor,
779    ) -> ProcessSession {
780        let permission_view = session_permissions.view();
781        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(workspace_root)
782            .with_environment(environment.clone())
783            .with_path_rules(path_rules.iter().cloned())
784            .with_background(background.clone());
785        let mut permissioned_factory =
786            WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace_root)
787                .with_environment(environment.clone())
788                .with_path_rules(path_rules.iter().cloned())
789                .with_network_requests_allowed(network_requests_allowed)
790                .with_background(background);
791        if !workspace_writable {
792            runner = runner.read_only_workspace();
793            permissioned_factory = permissioned_factory.read_only_workspace();
794        }
795        let runner = runner.with_session_permissions(session_permissions.clone());
796        let permissioned_factory =
797            permissioned_factory.with_session_permissions(session_permissions);
798        ProcessSession::from_parts(
799            AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
800            Arc::new(runner),
801            Arc::new(permissioned_factory),
802        )
803        .with_permission_view(permission_view)
804    }
805}
806
807impl ProcessBackend for LocalProcessBackend {
808    fn new_session(&self) -> ProcessSession {
809        (self.new_session)()
810    }
811
812    fn new_session_with(
813        &self,
814        request: ProcessSessionRequest,
815    ) -> Result<ProcessSession, ProcessBackendError> {
816        (self.new_session_with)(request)
817    }
818}
819
820/// Process backend whose active mode and sandbox options can be swapped live
821/// while keeping the parent session's background process supervisor and
822/// live-updatable permission view intact.
823///
824/// Newly spawned child sessions via [`ProcessBackend::new_session_with`] read
825/// the latest swapped backend automatically, while [`Self::replace`] clears
826/// stale session-retained grants and returns a new parent [`ProcessSession`]
827/// bound to the same background supervisor and permission view so retained
828/// background processes remain inspectable/stoppable and future subagents
829/// inherit only post-reload grants.
830pub struct LiveProcessBackend {
831    state: std::sync::RwLock<LocalProcessBackend>,
832    session_background: crate::process_runner::BackgroundSupervisor,
833    session_permissions: ProcessSessionPermissions,
834}
835
836impl LiveProcessBackend {
837    /// Creates a live-swappable local process backend.
838    ///
839    /// # Errors
840    ///
841    /// Returns a [`ProcessBackendError`] when the initial backend configuration
842    /// is invalid or the requested isolated sandbox is unavailable.
843    pub fn new(
844        workspace_root: impl Into<PathBuf>,
845        mode: ProcessBackendMode,
846        options: ProcessBackendOptions,
847    ) -> Result<Self, ProcessBackendError> {
848        let session_background = crate::process_runner::BackgroundSupervisor::new();
849        let session_permissions = ProcessSessionPermissions::new();
850        let backend = LocalProcessBackend::new_with_shared_state(
851            workspace_root,
852            mode,
853            options,
854            Some(session_background.clone()),
855            Some(session_permissions.clone()),
856        )?;
857        Ok(Self {
858            state: std::sync::RwLock::new(backend),
859            session_background,
860            session_permissions,
861        })
862    }
863
864    /// Wraps a fixed process session (primarily for tests and custom adapters).
865    #[must_use]
866    pub fn from_session(session: ProcessSession) -> Self {
867        Self {
868            state: std::sync::RwLock::new(LocalProcessBackend::from_session(session)),
869            session_background: crate::process_runner::BackgroundSupervisor::new(),
870            session_permissions: ProcessSessionPermissions::new(),
871        }
872    }
873
874    /// Validates and installs a replacement backend configuration, returning a
875    /// new parent [`ProcessSession`] sharing the existing background supervisor
876    /// and a freshly cleared session permission store.
877    ///
878    /// If validation fails, the active backend and retained session permissions
879    /// remain unchanged.
880    ///
881    /// # Errors
882    ///
883    /// Returns a [`ProcessBackendError`] when the new configuration is invalid
884    /// or the requested isolated sandbox is unavailable.
885    pub fn replace(
886        &self,
887        workspace_root: impl Into<PathBuf>,
888        mode: ProcessBackendMode,
889        options: ProcessBackendOptions,
890    ) -> Result<ProcessSession, ProcessBackendError> {
891        let next = LocalProcessBackend::new_with_shared_state(
892            workspace_root,
893            mode,
894            options,
895            Some(self.session_background.clone()),
896            Some(self.session_permissions.clone()),
897        )?;
898        self.session_permissions.clear()?;
899        let next_session = next.new_session();
900        let mut guard = self
901            .state
902            .write()
903            .unwrap_or_else(std::sync::PoisonError::into_inner);
904        *guard = next;
905        Ok(next_session)
906    }
907}
908
909impl ProcessBackend for LiveProcessBackend {
910    fn new_session(&self) -> ProcessSession {
911        self.state
912            .read()
913            .unwrap_or_else(std::sync::PoisonError::into_inner)
914            .new_session()
915    }
916
917    fn new_session_with(
918        &self,
919        request: ProcessSessionRequest,
920    ) -> Result<ProcessSession, ProcessBackendError> {
921        self.state
922            .read()
923            .unwrap_or_else(std::sync::PoisonError::into_inner)
924            .new_session_with(request)
925    }
926}
927
928/// Permissioned runner factory for the explicit host-process backend.
929///
930/// The host backend already exposes the process to the operating system, so a
931/// reviewed capability request reuses its runner. Runtime admission and action
932/// evidence remain active around the returned runner.
933#[derive(Clone)]
934pub struct UnrestrictedPermissionedProcessRunnerFactory {
935    runner: Arc<dyn ProcessRunner>,
936}
937
938impl UnrestrictedPermissionedProcessRunnerFactory {
939    /// Creates a factory that reuses the host-process runner.
940    #[must_use]
941    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
942        Self { runner }
943    }
944}
945
946impl PermissionedProcessRunnerFactory for UnrestrictedPermissionedProcessRunnerFactory {
947    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
948        Arc::clone(&self.runner)
949    }
950}
951
952#[cfg(test)]
953mod tests;