merry-process 0.1.4

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Local and live-swappable host-process backend implementations.

use crate::{
    ProcessBackend, ProcessBackendError, ProcessBackendMode, ProcessBackendOptions, ProcessSession,
    ProcessSessionPermissions, ProcessSessionRequest, TokioProcessRunner,
};
#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
use crate::{WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory};
#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
use merry_core::CapabilityPolicy;
use merry_runtime::{
    AcceptedLocalWorkspaceProcessAdmission, PermissionRequest, PermissionedProcessRunnerFactory,
    ProcessRunner,
};
#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
use merry_runtime::{HostIntegration, PathAccessRule};
#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
use std::path::Path;
use std::{path::PathBuf, sync::Arc};

/// Current local host-process backend.
///
/// The backend owns the current host implementation choice. Its public
/// session contract is intentionally independent of that choice, so adding a
/// platform-specific backend does not change coding profile or runtime APIs.
#[derive(Clone)]
pub struct LocalProcessBackend {
    new_session: Arc<dyn Fn() -> ProcessSession + Send + Sync>,
    new_session_with: Arc<
        dyn Fn(ProcessSessionRequest) -> Result<ProcessSession, ProcessBackendError> + Send + Sync,
    >,
}

impl LocalProcessBackend {
    /// Creates a fixed backend from one already constructed session.
    ///
    /// This is intended for trusted adapters and deterministic test fixtures.
    /// Platform-selected production backends should use [`Self::new`] so the
    /// admission is created together with the concrete enforcement strategy.
    #[must_use]
    pub fn from_session(session: ProcessSession) -> Self {
        let child_session = session.clone();
        let scoped_session = session;
        Self {
            new_session: Arc::new(move || child_session.clone()),
            new_session_with: Arc::new(move |_request| Ok(scoped_session.clone())),
        }
    }

    #[cfg(test)]
    pub(crate) fn from_parts(
        admission: AcceptedLocalWorkspaceProcessAdmission,
        runner: Arc<dyn ProcessRunner>,
        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
    ) -> Self {
        Self::from_session(ProcessSession::from_parts(
            admission,
            runner,
            permissioned_factory,
        ))
    }

    /// Creates a platform-selected local process backend.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] when the selected backend cannot be
    /// configured or the requested isolated behavior is unavailable.
    pub fn new(
        workspace_root: impl Into<PathBuf>,
        mode: ProcessBackendMode,
        options: ProcessBackendOptions,
    ) -> Result<Self, ProcessBackendError> {
        Self::new_with_shared_state(workspace_root, mode, options, None, None)
    }

    fn new_with_shared_state(
        workspace_root: impl Into<PathBuf>,
        mode: ProcessBackendMode,
        options: ProcessBackendOptions,
        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
        shared_permissions: Option<ProcessSessionPermissions>,
    ) -> Result<Self, ProcessBackendError> {
        match mode {
            ProcessBackendMode::Host => Self::unrestricted_with_shared_state(
                workspace_root,
                options,
                shared_background,
                shared_permissions,
            ),
            ProcessBackendMode::Isolated => Self::sandboxed_with_shared_state(
                workspace_root,
                options,
                shared_background,
                shared_permissions,
            ),
        }
    }

    /// Creates the current host-process implementation without an inner
    /// operating-system sandbox.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError::Runner`] when an environment override
    /// cannot be validated by the host runner.
    pub fn unrestricted(
        workspace_root: impl Into<PathBuf>,
        options: ProcessBackendOptions,
    ) -> Result<Self, ProcessBackendError> {
        Self::unrestricted_with_shared_state(workspace_root, options, None, None)
    }

    fn unrestricted_with_shared_state(
        workspace_root: impl Into<PathBuf>,
        options: ProcessBackendOptions,
        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
        shared_permissions: Option<ProcessSessionPermissions>,
    ) -> Result<Self, ProcessBackendError> {
        let workspace_root = workspace_root.into();
        let environment_overrides = options.environment_overrides;
        let env_isolation = options.env_isolation;
        let mut runner = TokioProcessRunner::new_at_workspace_root(workspace_root.clone())
            .with_env_isolation(env_isolation.clone())?
            .with_environment_overrides(environment_overrides.clone())?;
        if let Some(background) = shared_background {
            runner = runner.with_background(background);
        }
        let runner = Arc::new(runner);
        let path_rules = options.path_rules;
        let product_private_paths = merry_runtime::extract_product_private_paths(&path_rules);
        let permissioned_factory = Arc::new(
            UnrestrictedPermissionedProcessRunnerFactory::new(
                Arc::clone(&runner) as Arc<dyn ProcessRunner>
            )
            .with_product_private_paths(workspace_root.clone(), product_private_paths.clone()),
        );
        let workspace_writable = options.workspace_writable;
        let network_policy = options.network_policy;
        let allowed_domains = options.allowed_domains;
        let browser_allow_local = options.browser_allow_local;
        let permissions = shared_permissions.unwrap_or_default();
        let default_session = ProcessSession::from_parts(
            AcceptedLocalWorkspaceProcessAdmission::accept_host(),
            runner,
            permissioned_factory,
        )
        .with_session_permissions(permissions.clone())
        .with_access_policy_inputs(path_rules.clone(), workspace_writable)
        .with_network_policy_inputs(network_policy, allowed_domains.clone(), browser_allow_local)
        .with_env_isolation(env_isolation.clone());
        Ok(Self {
            new_session: Arc::new(move || default_session.clone()),
            new_session_with: Arc::new(move |request| {
                let effective_root = request
                    .workspace_root
                    .unwrap_or_else(|| workspace_root.clone());
                let runner = Arc::new(
                    TokioProcessRunner::new_at_workspace_root(effective_root.clone())
                        .with_env_isolation(env_isolation.clone())?
                        .with_environment_overrides(environment_overrides.clone())?,
                );
                let mut combined_rules = path_rules.clone();
                combined_rules.extend(request.extra_path_rules);
                let child_private_paths =
                    merry_runtime::extract_product_private_paths(&combined_rules);
                let permissioned_factory = Arc::new(
                    UnrestrictedPermissionedProcessRunnerFactory::new(
                        Arc::clone(&runner) as Arc<dyn ProcessRunner>
                    )
                    .with_product_private_paths(effective_root, child_private_paths),
                );
                let child_permissions = match request.inherited_permissions.as_ref() {
                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
                    None => ProcessSessionPermissions::new(),
                };
                Ok(ProcessSession::from_parts(
                    AcceptedLocalWorkspaceProcessAdmission::accept_host(),
                    runner,
                    permissioned_factory,
                )
                .with_session_permissions(child_permissions)
                .with_access_policy_inputs(
                    combined_rules,
                    workspace_writable && request.workspace_writable,
                )
                .with_network_policy_inputs(
                    network_policy,
                    allowed_domains.clone(),
                    browser_allow_local,
                )
                .with_env_isolation(env_isolation.clone()))
            }),
        })
    }

    /// Creates the current isolated local-process implementation.
    ///
    /// On Linux, each action is confined with Landlock and, unless that action
    /// was granted network, a seccomp filter. On macOS, each action is confined
    /// with a Seatbelt profile. Other targets return
    /// [`ProcessBackendError::UnsupportedIsolation`].
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] when the workspace or sandbox
    /// environment is invalid, a configured path cannot be enforced, or this
    /// target has no isolated backend.
    pub fn sandboxed(
        workspace_root: impl Into<PathBuf>,
        options: ProcessBackendOptions,
    ) -> Result<Self, ProcessBackendError> {
        Self::sandboxed_with_shared_state(workspace_root, options, None, None)
    }
}

#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
impl LocalProcessBackend {
    fn sandboxed_with_shared_state(
        workspace_root: impl Into<PathBuf>,
        options: ProcessBackendOptions,
        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
        shared_permissions: Option<ProcessSessionPermissions>,
    ) -> Result<Self, ProcessBackendError> {
        let workspace_root = workspace_root.into();
        let mut environment = WorkspaceProcessEnvironment::from_current_process()
            .with_host_integrations(options.host_integrations)
            .with_env_isolation(options.env_isolation)?
            .with_overrides(options.environment_overrides)?
            .validate_for_workspace(&workspace_root)?;
        if let Some(sockets) = options.gpg_agent_sockets {
            environment = environment.with_gpg_agent_sockets(sockets);
        }
        let mut rules_runner =
            WorkspaceProcessRunner::new_at_workspace_root(workspace_root.clone())
                .with_environment(environment.clone())
                .with_path_rules(options.path_rules.iter().cloned());
        if !options.workspace_writable {
            rules_runner = rules_runner.read_only_workspace();
        }
        rules_runner.ensure_sandbox_rules()?;
        Ok(Self::from_sandboxed_parts(SandboxedBackendParts {
            workspace_root,
            environment,
            path_rules: options.path_rules,
            network_policy: options.network_policy,
            allowed_domains: options.allowed_domains,
            browser_allow_local: options.browser_allow_local,
            denied_host_integrations: options.denied_host_integrations,
            workspace_writable: options.workspace_writable,
            shared_background,
            shared_permissions,
        }))
    }

    fn from_sandboxed_parts(parts: SandboxedBackendParts) -> Self {
        let SandboxedBackendParts {
            workspace_root,
            environment,
            path_rules,
            network_policy,
            allowed_domains,
            browser_allow_local,
            denied_host_integrations,
            workspace_writable,
            shared_background,
            shared_permissions,
        } = parts;
        let child_workspace_root = workspace_root.clone();
        let child_environment = environment.clone();
        let child_path_rules = path_rules.clone();
        let child_allowed_domains = allowed_domains.clone();
        let child_denied_integrations = denied_host_integrations.clone();
        let scoped_workspace_root = workspace_root;
        let scoped_environment = environment;
        let scoped_path_rules = path_rules;
        Self {
            new_session: Arc::new(move || {
                Self::sandboxed_session(SandboxedSessionParts {
                    workspace_root: &child_workspace_root,
                    environment: &child_environment,
                    path_rules: &child_path_rules,
                    network_policy,
                    allowed_domains: &child_allowed_domains,
                    browser_allow_local,
                    denied_host_integrations: &child_denied_integrations,
                    workspace_writable,
                    session_permissions: shared_permissions.clone().unwrap_or_default(),
                    background: shared_background.clone().unwrap_or_default(),
                })
            }),
            new_session_with: Arc::new(move |request| {
                let target_root = request
                    .workspace_root
                    .as_deref()
                    .unwrap_or(&scoped_workspace_root);
                // Intersection: a scoped session can narrow a writable backend
                // to read-only, never widen a read-only backend to writable.
                let effective_writable = workspace_writable && request.workspace_writable;
                let session_permissions = match request.inherited_permissions.as_ref() {
                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
                    None => ProcessSessionPermissions::new(),
                };
                let mut combined_rules =
                    Vec::with_capacity(scoped_path_rules.len() + request.extra_path_rules.len());
                combined_rules.extend(scoped_path_rules.iter().cloned());
                combined_rules.extend(request.extra_path_rules);
                let validated_env = if request.workspace_root.is_some() {
                    scoped_environment
                        .clone()
                        .validate_for_workspace(target_root)?
                } else {
                    scoped_environment.clone()
                };
                if request.workspace_root.is_some() || !combined_rules.is_empty() {
                    let mut rules_runner =
                        WorkspaceProcessRunner::new_at_workspace_root(target_root)
                            .with_environment(validated_env.clone())
                            .with_path_rules(combined_rules.iter().cloned());
                    if !effective_writable {
                        rules_runner = rules_runner.read_only_workspace();
                    }
                    rules_runner.ensure_sandbox_rules()?;
                }
                Ok(Self::sandboxed_session(SandboxedSessionParts {
                    workspace_root: target_root,
                    environment: &validated_env,
                    path_rules: &combined_rules,
                    network_policy,
                    allowed_domains: &allowed_domains,
                    browser_allow_local,
                    denied_host_integrations: &denied_host_integrations,
                    workspace_writable: effective_writable,
                    session_permissions,
                    background: crate::process_runner::BackgroundSupervisor::new(),
                }))
            }),
        }
    }

    fn sandboxed_session(parts: SandboxedSessionParts<'_>) -> ProcessSession {
        let SandboxedSessionParts {
            workspace_root,
            environment,
            path_rules,
            network_policy,
            allowed_domains,
            browser_allow_local,
            denied_host_integrations,
            workspace_writable,
            session_permissions,
            background,
        } = parts;
        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(workspace_root)
            .with_environment(environment.clone())
            .with_path_rules(path_rules.iter().cloned())
            .with_background(background.clone());
        let mut permissioned_factory =
            WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace_root)
                .with_environment(environment.clone())
                .with_path_rules(path_rules.iter().cloned())
                .with_network_policy(network_policy)
                .with_denied_host_integrations(denied_host_integrations.iter().copied())
                .with_background(background);
        if network_policy.is_preauthorized() {
            runner = runner.allow_network();
        }
        if !workspace_writable {
            runner = runner.read_only_workspace();
            permissioned_factory = permissioned_factory.read_only_workspace();
        }
        let runner = runner.with_session_permissions(session_permissions.clone());
        let permissioned_factory =
            permissioned_factory.with_session_permissions(session_permissions.clone());
        ProcessSession::from_parts(
            AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
            Arc::new(runner),
            Arc::new(permissioned_factory),
        )
        .with_session_permissions(session_permissions)
        .with_access_policy_inputs(path_rules.to_vec(), workspace_writable)
        .with_network_policy_inputs(
            network_policy,
            allowed_domains.to_vec(),
            browser_allow_local,
        )
        .with_env_isolation(environment.env_isolation().clone())
    }
}

#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
struct SandboxedBackendParts {
    workspace_root: PathBuf,
    environment: WorkspaceProcessEnvironment,
    path_rules: Vec<PathAccessRule>,
    network_policy: CapabilityPolicy,
    allowed_domains: Vec<String>,
    browser_allow_local: bool,
    denied_host_integrations: Vec<HostIntegration>,
    workspace_writable: bool,
    shared_background: Option<crate::process_runner::BackgroundSupervisor>,
    shared_permissions: Option<ProcessSessionPermissions>,
}

#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
struct SandboxedSessionParts<'a> {
    workspace_root: &'a Path,
    environment: &'a WorkspaceProcessEnvironment,
    path_rules: &'a [PathAccessRule],
    network_policy: CapabilityPolicy,
    allowed_domains: &'a [String],
    browser_allow_local: bool,
    denied_host_integrations: &'a [HostIntegration],
    workspace_writable: bool,
    session_permissions: ProcessSessionPermissions,
    background: crate::process_runner::BackgroundSupervisor,
}

#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
impl LocalProcessBackend {
    fn sandboxed_with_shared_state(
        workspace_root: impl Into<PathBuf>,
        options: ProcessBackendOptions,
        shared_background: Option<crate::process_runner::BackgroundSupervisor>,
        shared_permissions: Option<ProcessSessionPermissions>,
    ) -> Result<Self, ProcessBackendError> {
        let _ = (
            workspace_root.into(),
            options,
            shared_background,
            shared_permissions,
        );
        Err(ProcessBackendError::UnsupportedIsolation {
            target_os: std::env::consts::OS,
        })
    }
}

impl ProcessBackend for LocalProcessBackend {
    fn new_session(&self) -> ProcessSession {
        (self.new_session)()
    }

    fn new_session_with(
        &self,
        request: ProcessSessionRequest,
    ) -> Result<ProcessSession, ProcessBackendError> {
        (self.new_session_with)(request)
    }
}

/// Process backend whose active mode and sandbox options can be swapped live
/// while keeping the parent session's background process supervisor and
/// live-updatable permission view intact.
///
/// Newly spawned child sessions via [`ProcessBackend::new_session_with`] read
/// the latest swapped backend automatically, while [`Self::replace`] clears
/// stale session-retained grants and returns a new parent [`ProcessSession`]
/// bound to the same background supervisor and permission view so retained
/// background processes remain inspectable/stoppable and future subagents
/// inherit only post-reload grants.
/// Policy governing how existing session-scoped permission grants are treated
/// when [`LiveProcessBackend`] swaps its active configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionGrantClearPolicy {
    /// Clear all session grants (used when switching `SandboxMode`).
    ClearAll,
    /// Preserve all existing session grants (used when adding/removing saved
    /// workspace rules).
    PreserveAll,
    /// Selectively revoke only grants invalidated by newly denied capability
    /// policies, keeping unrelated path/domain grants intact.
    RevokeDenied {
        /// Whether outbound network is now `CapabilityPolicy::Deny`.
        network_denied: bool,
        /// Host integrations that are now `CapabilityPolicy::Deny`.
        denied_host_integrations: Vec<merry_runtime::HostIntegration>,
    },
}

/// Validated, uncommitted live backend replacement produced by
/// [`LiveProcessBackend::prepare_replace`].
///
/// Dropping this handle without calling [`Self::commit`] leaves the active
/// backend, live policy baseline, and retained session permissions untouched.
pub struct PreparedLiveReplace<'a> {
    backend: &'a LiveProcessBackend,
    next_backend: LocalProcessBackend,
    next_session: ProcessSession,
    next_baseline: merry_runtime::LivePolicyBaseline,
    next_env_isolation: crate::ProcessEnvIsolation,
    clear_policy: SessionGrantClearPolicy,
}

impl PreparedLiveReplace<'_> {
    /// Borrows the prepared parent [`ProcessSession`] (with runners and
    /// factories ready for `InteractiveProcessExecutionUpdate`) before commit.
    #[must_use]
    pub fn session(&self) -> &ProcessSession {
        &self.next_session
    }

    /// Atomically commits the prepared backend, live policy baseline,
    /// environment isolation, and session grant clear policy.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] if the session permission lock was poisoned.
    pub fn commit(self) -> Result<ProcessSession, ProcessBackendError> {
        match &self.clear_policy {
            SessionGrantClearPolicy::ClearAll => {
                self.backend.session_permissions.clear()?;
            }
            SessionGrantClearPolicy::PreserveAll => {}
            SessionGrantClearPolicy::RevokeDenied {
                network_denied,
                denied_host_integrations,
            } => {
                self.backend
                    .session_permissions
                    .revoke_denied_capabilities(*network_denied, denied_host_integrations)?;
            }
        }
        if let Some(live) = &self.backend.live_policy {
            live.replace_baseline(self.next_baseline);
        }
        if let Some(live_env) = &self.backend.live_env_isolation {
            *live_env
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = self.next_env_isolation;
        }
        let mut guard = self
            .backend
            .state
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *guard = self.next_backend;
        Ok(self.next_session)
    }
}

pub struct LiveProcessBackend {
    state: std::sync::RwLock<LocalProcessBackend>,
    session_background: crate::process_runner::BackgroundSupervisor,
    session_permissions: ProcessSessionPermissions,
    live_policy: Option<merry_runtime::LivePolicyHandle>,
    live_env_isolation: Option<Arc<std::sync::RwLock<crate::ProcessEnvIsolation>>>,
}

impl LiveProcessBackend {
    /// Creates a live-swappable local process backend.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] when the initial backend configuration
    /// is invalid or the requested isolated sandbox is unavailable.
    pub fn new(
        workspace_root: impl Into<PathBuf>,
        mode: ProcessBackendMode,
        options: ProcessBackendOptions,
    ) -> Result<Self, ProcessBackendError> {
        let workspace_root = workspace_root.into();
        let session_background = crate::process_runner::BackgroundSupervisor::new();
        let session_permissions = ProcessSessionPermissions::new();
        let backend = LocalProcessBackend::new_with_shared_state(
            workspace_root.clone(),
            mode,
            options,
            Some(session_background.clone()),
            Some(session_permissions.clone()),
        )?;
        let initial_session = backend.new_session();
        let initial_baseline = live_policy_baseline(&workspace_root, mode, &initial_session);
        let live_policy = merry_runtime::LivePolicyHandle::new(initial_baseline)
            .with_session_permissions(session_permissions.view());
        let live_env_isolation = Arc::new(std::sync::RwLock::new(
            initial_session.env_isolation().clone(),
        ));
        Ok(Self {
            state: std::sync::RwLock::new(backend),
            session_background,
            session_permissions,
            live_policy: Some(live_policy),
            live_env_isolation: Some(live_env_isolation),
        })
    }

    /// Wraps a fixed process session (primarily for tests and custom adapters).
    #[must_use]
    pub fn from_session(session: ProcessSession) -> Self {
        Self {
            state: std::sync::RwLock::new(LocalProcessBackend::from_session(session)),
            session_background: crate::process_runner::BackgroundSupervisor::new(),
            session_permissions: ProcessSessionPermissions::new(),
            live_policy: None,
            live_env_isolation: None,
        }
    }

    /// Validates and prepares a replacement backend configuration without
    /// mutating live state or clearing session grants until
    /// [`PreparedLiveReplace::commit`] is called.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] when the new configuration is invalid
    /// or the requested isolated sandbox is unavailable.
    pub fn prepare_replace(
        &self,
        workspace_root: impl Into<PathBuf>,
        mode: ProcessBackendMode,
        options: ProcessBackendOptions,
        clear_policy: SessionGrantClearPolicy,
    ) -> Result<PreparedLiveReplace<'_>, ProcessBackendError> {
        let workspace_root = workspace_root.into();
        let next_backend = LocalProcessBackend::new_with_shared_state(
            workspace_root.clone(),
            mode,
            options,
            Some(self.session_background.clone()),
            Some(self.session_permissions.clone()),
        )?;
        let mut next_session = next_backend.new_session();
        let next_baseline = live_policy_baseline(&workspace_root, mode, &next_session);
        let next_env_isolation = next_session.env_isolation().clone();
        if let Some(live) = &self.live_policy {
            next_session = next_session.with_live_policy(live.clone());
        }
        if let Some(live_env) = &self.live_env_isolation {
            next_session = next_session.with_live_env_isolation(Arc::clone(live_env));
        }
        Ok(PreparedLiveReplace {
            backend: self,
            next_backend,
            next_session,
            next_baseline,
            next_env_isolation,
            clear_policy,
        })
    }

    /// Validates and installs a replacement backend configuration, returning a
    /// new parent [`ProcessSession`] sharing the existing background supervisor,
    /// unified live policy handle, and a freshly cleared session permission store.
    ///
    /// If validation fails, the active backend and retained session permissions
    /// remain unchanged.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] when the new configuration is invalid
    /// or the requested isolated sandbox is unavailable.
    pub fn replace(
        &self,
        workspace_root: impl Into<PathBuf>,
        mode: ProcessBackendMode,
        options: ProcessBackendOptions,
    ) -> Result<ProcessSession, ProcessBackendError> {
        self.prepare_replace(
            workspace_root,
            mode,
            options,
            SessionGrantClearPolicy::ClearAll,
        )?
        .commit()
    }
}

fn live_policy_baseline(
    workspace_root: &std::path::Path,
    mode: ProcessBackendMode,
    session: &ProcessSession,
) -> merry_runtime::LivePolicyBaseline {
    let restricted = matches!(mode, ProcessBackendMode::Isolated);
    let workspace_access = restricted
        .then(|| session.workspace_access_policy(workspace_root, session.workspace_writable()));
    merry_runtime::LivePolicyBaseline::new(
        restricted,
        workspace_access,
        session.product_private_paths(),
        session.network_access_policy(),
    )
}

impl ProcessBackend for LiveProcessBackend {
    fn new_session(&self) -> ProcessSession {
        let mut session = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .new_session();
        if let Some(live) = &self.live_policy {
            session = session.with_live_policy(live.clone());
        }
        if let Some(live_env) = &self.live_env_isolation {
            session = session.with_live_env_isolation(Arc::clone(live_env));
        }
        session
    }

    fn new_session_with(
        &self,
        request: ProcessSessionRequest,
    ) -> Result<ProcessSession, ProcessBackendError> {
        let mut child_override =
            merry_runtime::ChildWorkspacePolicyOverride::new(request.workspace_writable);
        if let Some(root) = request.workspace_root.as_ref() {
            child_override = child_override.with_workspace_root(root);
        }
        if !request.extra_path_rules.is_empty() {
            child_override =
                child_override.with_extra_path_rules(request.extra_path_rules.iter().cloned());
        }
        let mut session = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .new_session_with(request)?;
        if let Some(live) = &self.live_policy {
            let child_live = live.for_child(session.permission_view(), Some(child_override));
            session = session.with_live_policy(child_live);
        }
        if let Some(live_env) = &self.live_env_isolation {
            session = session.with_live_env_isolation(Arc::clone(live_env));
        }
        Ok(session)
    }
}

/// Permissioned runner factory for the explicit unrestricted host backend.
///
/// The host backend already runs without an OS sandbox, so a reviewed
/// capability request reuses its runner. Runtime admission, action evidence,
/// and `ProductPrivate` (`providers/` / `MERRY_API_KEY_FILE`) protection remain
/// active around the returned runner.
#[derive(Clone)]
pub struct UnrestrictedPermissionedProcessRunnerFactory {
    runner: Arc<dyn ProcessRunner>,
    cwd_root: Option<PathBuf>,
    product_private_paths: Vec<PathBuf>,
}

impl UnrestrictedPermissionedProcessRunnerFactory {
    /// Creates a factory that reuses the host-process runner.
    #[must_use]
    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
        Self {
            runner,
            cwd_root: None,
            product_private_paths: Vec::new(),
        }
    }

    /// Configures `ProductPrivate` paths (such as `providers/` and
    /// `MERRY_API_KEY_FILE`) that remain high-risk once-only approval targets
    /// even when OS sandboxing is disabled.
    #[must_use]
    pub fn with_product_private_paths(
        mut self,
        cwd_root: PathBuf,
        paths: impl IntoIterator<Item = PathBuf>,
    ) -> Self {
        self.cwd_root = Some(cwd_root);
        self.product_private_paths = paths
            .into_iter()
            .map(|path| crate::resolve_host_path(&path))
            .collect();
        self
    }
}

impl PermissionedProcessRunnerFactory for UnrestrictedPermissionedProcessRunnerFactory {
    fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
        if self.product_private_paths.is_empty() {
            return false;
        }
        request.requested().iter().any(|capability| {
            let merry_runtime::RequestedCapability::Path(requested) = capability else {
                return false;
            };
            let raw = std::path::Path::new(requested.path());
            let materialized = if raw.is_absolute() {
                raw.to_path_buf()
            } else if let Some(root) = &self.cwd_root {
                root.join(raw)
            } else {
                raw.to_path_buf()
            };
            merry_runtime::is_protected_in_unrestricted_mode(
                &self.product_private_paths,
                &materialized,
            )
        })
    }

    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
        Arc::clone(&self.runner)
    }
}

#[cfg(test)]
#[path = "backend_tests.rs"]
mod tests;