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
//! Host-process adapters for Merry's provider-neutral process contract.
//!
//! [`merry_runtime`] owns process intent, admission, permission requests, and
//! execution evidence. This crate owns the host-facing runner selection and
//! binds the runners used by one runtime owner to one [`ProcessSession`]. A
//! platform can replace the concrete backend without changing coding
//! composition or runtime call sites.

mod backend;
mod baseline;
mod browser_spawner;
mod callback_runner;
#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
mod confinement;
#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
#[path = "confinement/unsupported.rs"]
mod confinement;
mod gpg;
mod host_path;
mod host_resources;
mod process_runner;

pub use backend::{
    LiveProcessBackend, LocalProcessBackend, PreparedLiveReplace, SessionGrantClearPolicy,
    UnrestrictedPermissionedProcessRunnerFactory,
};
pub use baseline::{default_development_path_rules, default_development_path_rules_with_env};
pub use browser_spawner::BrowserProcessSpawner;
pub use callback_runner::{
    CallbackBackgroundSupervisor, CallbackProcessExecutor, CallbackProcessOutput,
    CallbackProcessRequest, CallbackProcessResponder, CallbackProcessRunner,
    CallbackProcessTerminalStatus,
};
#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
pub use confinement::BrowserSandboxProfile;
pub use confinement::{probe_workspace_sandbox, sandbox_helper_main, sandbox_helper_requested};
pub use gpg::GpgAgentSockets;
pub use host_path::resolve_host_path;
pub use host_resources::{HostPathKind, HostPathMetadata, ssh_known_hosts};

pub use process_runner::{
    DEFAULT_REMOVED_ENV_PREFIX, ProcessEnvIsolation, ProcessSessionPermissions, TokioProcessRunner,
    action_process_path,
};

#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
pub use process_runner::{
    WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory,
};

use merry_core::{CapabilityPolicy, HostPathPolicy};
use merry_runtime::{
    AcceptedLocalWorkspaceProcessAdmission, HostIntegration, PathAccess, PathAccessRule,
    PathAccessRuleSource, PermissionedProcessRunnerFactory, ProcessRunner, ProcessRunnerError,
    ProcessSessionPermissionView,
};
use std::{
    ffi::OsString,
    path::{Path, PathBuf},
    sync::Arc,
};
use thiserror::Error;

/// Semantic process backend behavior requested by an application surface.
///
/// The selected behavior is intentionally independent of the operating system.
/// A platform backend may implement [`Isolated`](Self::Isolated) with its
/// native mechanism or report that the behavior is unavailable; callers do not
/// need to name Landlock, seccomp, or another concrete mechanism.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessBackendMode {
    /// Run actions in the host process environment, subject to runtime policy.
    Host,
    /// Request the platform's isolated local-process behavior.
    Isolated,
}

/// Errors raised while selecting or constructing a host-process backend.
///
/// Execution failures remain [`merry_runtime::ProcessRunnerError`]. This error
/// belongs to the adapter layer because it also represents a platform backend
/// that is not available for the requested semantic mode.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum ProcessBackendError {
    /// The concrete runner rejected its configuration.
    #[error("process backend configuration failed: {source}")]
    Runner {
        /// The runner configuration failure.
        #[source]
        source: ProcessRunnerError,
    },
    /// The requested isolated behavior has no implementation on this target.
    #[error(
        "isolated local process backend is unavailable on target operating system `{target_os}`"
    )]
    UnsupportedIsolation {
        /// Rust's target-operating-system identifier.
        target_os: &'static str,
    },
}

impl From<ProcessRunnerError> for ProcessBackendError {
    fn from(source: ProcessRunnerError) -> Self {
        Self::Runner { source }
    }
}

/// One process execution boundary used by a runtime instance.
///
/// The admission and both runner capabilities are kept together so callers
/// cannot accidentally pair a runner with a permission factory from another
/// backend configuration. Child runtimes obtain their process session through
/// [`ProcessBackend::new_session`] or [`ProcessBackend::new_session_with`],
/// whose backend controls session isolation.
#[derive(Clone)]
pub struct ProcessSession {
    admission: AcceptedLocalWorkspaceProcessAdmission,
    runner: Arc<dyn ProcessRunner>,
    permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
    permission_view: Option<ProcessSessionPermissionView>,
    session_permissions: Option<ProcessSessionPermissions>,
    static_path_rules: Vec<PathAccessRule>,
    workspace_writable: bool,
    network_policy: CapabilityPolicy,
    allowed_domains: Vec<String>,
    browser_allow_local: bool,
    live_policy: Option<merry_runtime::LivePolicyHandle>,
    live_env_isolation: Option<Arc<std::sync::RwLock<ProcessEnvIsolation>>>,
    env_isolation: ProcessEnvIsolation,
}

impl ProcessSession {
    /// Creates a session from an explicit, trusted adapter boundary.
    ///
    /// Production callers should select [`LocalProcessBackend::new`] so the
    /// admission, runner, and reviewed-action factory are produced by one
    /// backend implementation. This constructor exists for adapters and
    /// deterministic fixtures that already own all three components.
    #[must_use]
    pub fn from_parts(
        admission: AcceptedLocalWorkspaceProcessAdmission,
        runner: Arc<dyn ProcessRunner>,
        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
    ) -> Self {
        Self {
            admission,
            runner,
            permissioned_factory,
            permission_view: None,
            session_permissions: None,
            static_path_rules: Vec::new(),
            workspace_writable: true,
            network_policy: CapabilityPolicy::Ask,
            allowed_domains: Vec::new(),
            browser_allow_local: true,
            live_policy: None,
            live_env_isolation: None,
            env_isolation: ProcessEnvIsolation::default(),
        }
    }

    /// Attaches a read-only view of this session's retained permissions so child
    /// runtimes may inherit already-approved ordinary capabilities without
    /// mutating the parent session.
    #[must_use]
    pub fn with_permission_view(mut self, view: ProcessSessionPermissionView) -> Self {
        self.permission_view = Some(view);
        self
    }

    /// Attaches the shared session-scoped capability store owned by this session.
    #[must_use]
    pub fn with_session_permissions(mut self, permissions: ProcessSessionPermissions) -> Self {
        self.permission_view = Some(permissions.view());
        self.session_permissions = Some(permissions);
        self
    }

    /// Attaches the static path rules and workspace writability backing this
    /// session so in-process workspace tools share the same access policy.
    #[must_use]
    pub fn with_access_policy_inputs(
        mut self,
        static_path_rules: Vec<PathAccessRule>,
        workspace_writable: bool,
    ) -> Self {
        self.static_path_rules = static_path_rules;
        self.workspace_writable = workspace_writable;
        self
    }

    /// Attaches static outbound network and browser-local policy inputs backing
    /// this session so in-process web/browser tools share the same rules.
    #[must_use]
    pub fn with_network_policy_inputs(
        mut self,
        network_policy: CapabilityPolicy,
        allowed_domains: Vec<String>,
        browser_allow_local: bool,
    ) -> Self {
        self.network_policy = network_policy;
        self.allowed_domains = allowed_domains;
        self.browser_allow_local = browser_allow_local;
        self
    }

    /// Attaches a unified single-lock [`merry_runtime::LivePolicyHandle`] shared
    /// with a [`LiveProcessBackend`] so mid-session sandbox, path, protected-path,
    /// and network changes update file tools, web/browser tools, and child
    /// sessions atomically.
    #[must_use]
    pub fn with_live_policy(mut self, policy: merry_runtime::LivePolicyHandle) -> Self {
        self.live_policy = Some(policy);
        self
    }

    /// Attaches a live environment-isolation handle shared with a
    /// [`LiveProcessBackend`] so browser spawns always observe the latest
    /// isolated environment configuration.
    #[must_use]
    pub fn with_live_env_isolation(
        mut self,
        env_isolation: Arc<std::sync::RwLock<ProcessEnvIsolation>>,
    ) -> Self {
        self.live_env_isolation = Some(env_isolation);
        self
    }

    /// Attaches the environment isolation policy stripped from browser and
    /// child processes spawned under this session.
    #[must_use]
    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
        self.env_isolation = env_isolation;
        self
    }

    /// Returns whether writes inside the workspace are allowed by this session.
    #[must_use]
    pub const fn workspace_writable(&self) -> bool {
        self.workspace_writable
    }

    /// Returns whether this session is backed by a live-swappable
    /// [`merry_runtime::LivePolicyHandle`] (from [`LiveProcessBackend`]).
    #[must_use]
    pub fn has_live_policy(&self) -> bool {
        self.live_policy.is_some()
    }

    /// Returns the static environment isolation configured on this session.
    #[must_use]
    pub fn env_isolation(&self) -> &ProcessEnvIsolation {
        &self.env_isolation
    }

    /// Returns the runtime admission selected for this process boundary.
    #[must_use]
    pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
        self.admission
    }

    /// Returns the runner for ordinary process actions.
    #[must_use]
    pub fn runner(&self) -> Arc<dyn ProcessRunner> {
        Arc::clone(&self.runner)
    }

    /// Returns the factory for reviewed process actions.
    #[must_use]
    pub fn permissioned_factory(&self) -> Arc<dyn PermissionedProcessRunnerFactory> {
        Arc::clone(&self.permissioned_factory)
    }

    /// Returns a read-only view of capabilities retained by this session, when
    /// backed by a session-scoped permission store.
    #[must_use]
    pub fn permission_view(&self) -> Option<ProcessSessionPermissionView> {
        self.permission_view.clone()
    }

    /// Returns the shared session-scoped capability store, when backed by one.
    #[must_use]
    pub fn session_permissions(&self) -> Option<ProcessSessionPermissions> {
        self.session_permissions.clone()
    }

    /// Builds a unified [`merry_runtime::WorkspaceAccessPolicy`] sharing this
    /// session's static rules and live session-scoped grants.
    #[must_use]
    pub fn workspace_access_policy(
        &self,
        workspace_root: &Path,
        workspace_writable: bool,
    ) -> merry_runtime::WorkspaceAccessPolicy {
        let mut policy = merry_runtime::WorkspaceAccessPolicy::new(
            workspace_root,
            self.workspace_writable && workspace_writable,
        )
        .with_static_rules(self.static_path_rules.iter().cloned());
        if let Some(view) = self.permission_view.clone() {
            policy = policy.with_session_permissions(view);
        }
        policy
    }

    /// Returns the unified single-lock [`merry_runtime::LivePolicyHandle`]
    /// backing this session, synthesizing a static handle if this session was
    /// not produced by [`LiveProcessBackend`].
    #[must_use]
    pub fn live_policy_handle(
        &self,
        workspace_root: &Path,
        workspace_writable: bool,
    ) -> merry_runtime::LivePolicyHandle {
        if let Some(live) = &self.live_policy {
            return live.clone();
        }
        let restricted = self.admission.sandbox_profile()
            != merry_runtime::LocalWorkspaceProcessSandboxProfile::Host;
        let workspace_access = restricted.then(|| {
            merry_runtime::WorkspaceAccessPolicy::new(
                workspace_root,
                self.workspace_writable && workspace_writable,
            )
            .with_static_rules(self.static_path_rules.iter().cloned())
        });
        let baseline = merry_runtime::LivePolicyBaseline::new(
            restricted,
            workspace_access,
            self.product_private_paths(),
            self.network_access_policy(),
        );
        let mut handle = merry_runtime::LivePolicyHandle::new(baseline);
        if let Some(view) = self.permission_view.clone() {
            handle = handle.with_session_permissions(view);
        }
        handle
    }

    /// Builds a unified [`merry_runtime::NetworkAccessPolicy`] sharing this
    /// session's configured `network` policy, `browser.allow_local`, workspace
    /// `allowed_domains`, and live session-scoped domain/network grants.
    #[must_use]
    pub fn network_access_policy(&self) -> merry_runtime::NetworkAccessPolicy {
        let mut policy =
            merry_runtime::NetworkAccessPolicy::new(self.network_policy, self.browser_allow_local)
                .with_allowed_domains(&self.allowed_domains);
        if let Some(view) = self.permission_view.clone() {
            policy = policy.with_session_permissions(view);
        }
        policy
    }

    /// Returns Merry built-in `ProductPrivate` paths (such as `providers/` and
    /// `MERRY_API_KEY_FILE`) configured on this session.
    #[must_use]
    pub fn product_private_paths(&self) -> Vec<PathBuf> {
        merry_runtime::extract_product_private_paths(&self.static_path_rules)
    }

    /// Creates a desktop headless browser spawner bound to this session's live
    /// policy handle and environment isolation policy.
    #[must_use]
    pub fn browser_spawner(&self, workspace_root: impl Into<PathBuf>) -> BrowserProcessSpawner {
        let workspace_root = workspace_root.into();
        let live_policy = self.live_policy_handle(&workspace_root, self.workspace_writable);
        let live_env = self
            .live_env_isolation
            .clone()
            .unwrap_or_else(|| Arc::new(std::sync::RwLock::new(self.env_isolation.clone())));
        BrowserProcessSpawner::new(live_policy, workspace_root, live_env)
    }
}

/// Request options for deriving a scoped [`ProcessSession`] from a [`ProcessBackend`].
#[derive(Debug, Clone)]
pub struct ProcessSessionRequest {
    pub(crate) workspace_root: Option<PathBuf>,
    pub(crate) workspace_writable: bool,
    pub(crate) inherited_permissions: Option<ProcessSessionPermissionView>,
    pub(crate) extra_path_rules: Vec<PathAccessRule>,
}

impl Default for ProcessSessionRequest {
    fn default() -> Self {
        Self {
            workspace_root: None,
            workspace_writable: true,
            inherited_permissions: None,
            extra_path_rules: Vec::new(),
        }
    }
}

impl ProcessSessionRequest {
    /// Creates a default session request inheriting the backend's workspace root
    /// and writability.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Overrides the workspace root directory for the new session (for example,
    /// an isolated git worktree).
    #[must_use]
    pub fn with_workspace_root(mut self, workspace_root: impl Into<PathBuf>) -> Self {
        self.workspace_root = Some(workspace_root.into());
        self
    }

    /// Keeps the workspace readable and not writable for isolated actions in
    /// this session.
    #[must_use]
    pub fn read_only_workspace(mut self) -> Self {
        self.workspace_writable = false;
        self
    }

    /// Sets whether isolated actions in this session may write inside the
    /// workspace root.
    ///
    /// A request cannot widen a backend that was already configured read-only.
    #[must_use]
    pub fn with_workspace_writable(mut self, writable: bool) -> Self {
        self.workspace_writable = writable;
        self
    }

    /// Seeds the new session with a read-only snapshot of an existing session's
    /// approved ordinary capabilities.
    #[must_use]
    pub fn with_inherited_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
        self.inherited_permissions = Some(view);
        self
    }

    /// Appends additional filesystem rules for the new session.
    #[must_use]
    pub fn with_extra_path_rules(
        mut self,
        rules: impl IntoIterator<Item = PathAccessRule>,
    ) -> Self {
        self.extra_path_rules = rules.into_iter().collect();
        self
    }

    /// Returns the optional workspace root override.
    #[must_use]
    pub fn workspace_root(&self) -> Option<&Path> {
        self.workspace_root.as_deref()
    }

    /// Returns whether the caller requested workspace writability.
    #[must_use]
    pub const fn workspace_writable(&self) -> bool {
        self.workspace_writable
    }

    /// Returns the optional inherited permission view.
    #[must_use]
    pub fn inherited_permissions(&self) -> Option<&ProcessSessionPermissionView> {
        self.inherited_permissions.as_ref()
    }

    /// Returns any extra filesystem access rules attached to this request.
    #[must_use]
    pub fn extra_path_rules(&self) -> &[PathAccessRule] {
        &self.extra_path_rules
    }
}

/// Stable host-process backend boundary consumed by coding composition.
///
/// The trait deliberately says nothing about how a platform enforces the
/// selected behavior. Linux confines each action with Landlock and seccomp.
/// Other targets report that isolation is unavailable instead of silently
/// running on the host.
pub trait ProcessBackend: Send + Sync {
    /// Creates the process session for one runtime owner.
    ///
    /// Each call returns a session with the backend's configured admission and
    /// runner capabilities. Backends may use a fresh session-scoped capability
    /// store for every call, which keeps parent and child runtime state isolated.
    fn new_session(&self) -> ProcessSession;

    /// Creates a process session configured with scoped request options.
    ///
    /// The default implementation delegates to [`Self::new_session`] for custom
    /// test or adapter backends that do not vary session parameters.
    ///
    /// # Errors
    ///
    /// Returns a [`ProcessBackendError`] when the requested workspace root,
    /// sandbox rules, or inherited permissions cannot be validated.
    fn new_session_with(
        &self,
        _request: ProcessSessionRequest,
    ) -> Result<ProcessSession, ProcessBackendError> {
        Ok(self.new_session())
    }
}

/// Inputs shared by local process backend implementations.
#[derive(Debug, Clone)]
pub struct ProcessBackendOptions {
    /// Trusted filesystem rules installed for isolated actions.
    pub(crate) path_rules: Vec<PathAccessRule>,
    /// Three-state policy for outbound network capability (`deny`, `ask`, `allow`).
    pub(crate) network_policy: CapabilityPolicy,
    /// Workspace-persisted exact external hostnames allowed for web/browser tools.
    pub(crate) allowed_domains: Vec<String>,
    /// Whether explicit local loopback/data browser targets are allowed without review.
    pub(crate) browser_allow_local: bool,
    /// When false, the workspace itself is readable and not writable.
    pub(crate) workspace_writable: bool,
    /// Host integrations pre-authorized (`allow`) by the embedding application.
    pub(crate) host_integrations: Vec<HostIntegration>,
    /// Host integrations hard-blocked (`deny`) by the embedding application.
    pub(crate) denied_host_integrations: Vec<HostIntegration>,
    pub(crate) gpg_agent_sockets: Option<GpgAgentSockets>,
    /// Environment assignments validated and applied by the host backend.
    pub(crate) environment_overrides: Vec<(OsString, OsString)>,
    /// Environment variable isolation policy stripped from every child process.
    pub(crate) env_isolation: ProcessEnvIsolation,
}

impl Default for ProcessBackendOptions {
    fn default() -> Self {
        Self {
            path_rules: Vec::new(),
            network_policy: CapabilityPolicy::Ask,
            allowed_domains: Vec::new(),
            browser_allow_local: true,
            workspace_writable: true,
            host_integrations: Vec::new(),
            denied_host_integrations: Vec::new(),
            gpg_agent_sockets: None,
            environment_overrides: Vec::new(),
            env_isolation: ProcessEnvIsolation::default(),
        }
    }
}

impl ProcessBackendOptions {
    /// Creates default options without preauthorized process capabilities.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets trusted filesystem rules installed for isolated actions.
    #[must_use]
    pub fn with_path_rules(mut self, path_rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
        self.path_rules = path_rules.into_iter().collect();
        self
    }

    /// Appends filesystem rules installed for isolated actions.
    #[must_use]
    pub fn extend_path_rules(
        mut self,
        path_rules: impl IntoIterator<Item = PathAccessRule>,
    ) -> Self {
        self.path_rules.extend(path_rules);
        self
    }

    /// Appends the default local development toolchain and cache baseline rules.
    #[must_use]
    pub fn with_default_development_baseline(self, home: &Path) -> Self {
        self.extend_path_rules(default_development_path_rules(home))
    }

    /// Appends Merry's product path rules from the shared [`HostPathPolicy`]
    /// contract (writable config/skills, writable durable memory, read-only
    /// state/history, and denied private credentials).
    #[must_use]
    pub fn with_host_path_policy(mut self, policy: &HostPathPolicy) -> Self {
        for path in policy.product_writable_config() {
            self.path_rules.push(PathAccessRule::new(
                path.clone(),
                PathAccess::ReadWrite,
                PathAccessRuleSource::ProductConfig,
            ));
        }
        if let Some(memory_root) = policy.durable_memory_root() {
            self.path_rules.push(PathAccessRule::new(
                memory_root.to_path_buf(),
                PathAccess::ReadWrite,
                PathAccessRuleSource::DurableMemory,
            ));
        }
        for path in policy.product_readonly() {
            self.path_rules.push(PathAccessRule::new(
                path.clone(),
                PathAccess::ReadOnly,
                PathAccessRuleSource::ProductReadOnly,
            ));
        }
        for path in policy.denied() {
            self.path_rules.push(PathAccessRule::new(
                path.clone(),
                PathAccess::Deny,
                PathAccessRuleSource::ProductPrivate,
            ));
        }
        self
    }

    /// Sets the three-state network policy (`deny`, `ask`, or `allow`).
    #[must_use]
    pub fn with_network_policy(mut self, policy: CapabilityPolicy) -> Self {
        self.network_policy = policy;
        self
    }

    /// Sets workspace-persisted exact allowed domains for web/browser tools.
    #[must_use]
    pub fn with_allowed_domains<I, S>(mut self, domains: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allowed_domains = domains.into_iter().map(Into::into).collect();
        self
    }

    /// Sets whether explicit local browser targets (`localhost`, `127.0.0.1`,
    /// `::1`, `data:text/html`) are permitted without permission review.
    #[must_use]
    pub fn with_browser_allow_local(mut self, allow_local: bool) -> Self {
        self.browser_allow_local = allow_local;
        self
    }

    /// Sets whether isolated process sessions may request network capability.
    ///
    /// `true` maps to [`CapabilityPolicy::Ask`]; `false` maps to
    /// [`CapabilityPolicy::Deny`]. Use [`Self::with_network_policy`] to
    /// pre-authorize network via [`CapabilityPolicy::Allow`].
    #[must_use]
    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
        self.network_policy = if allowed {
            CapabilityPolicy::Ask
        } else {
            CapabilityPolicy::Deny
        };
        self
    }

    /// Keeps the workspace readable and not writable for isolated actions.
    ///
    /// Baseline paths such as `/tmp` stay writable. Host execution ignores this.
    #[must_use]
    pub fn read_only_workspace(mut self) -> Self {
        self.workspace_writable = false;
        self
    }

    /// Sets host integrations pre-authorized (`allow`) by the embedding application.
    #[must_use]
    pub fn with_host_integrations(
        mut self,
        host_integrations: impl IntoIterator<Item = HostIntegration>,
    ) -> Self {
        self.host_integrations = host_integrations.into_iter().collect();
        self.denied_host_integrations
            .retain(|denied| !self.host_integrations.contains(denied));
        self
    }

    /// Sets host integrations hard-denied (`deny`) by the embedding application.
    #[must_use]
    pub fn with_denied_host_integrations(
        mut self,
        denied: impl IntoIterator<Item = HostIntegration>,
    ) -> Self {
        self.denied_host_integrations = denied.into_iter().collect();
        self.host_integrations
            .retain(|allowed| !self.denied_host_integrations.contains(allowed));
        self
    }

    /// Sets the three-state policy for one host integration (`deny`, `ask`, `allow`).
    #[must_use]
    pub fn with_host_integration_policy(
        mut self,
        integration: HostIntegration,
        policy: CapabilityPolicy,
    ) -> Self {
        self.host_integrations.retain(|item| *item != integration);
        self.denied_host_integrations
            .retain(|item| *item != integration);
        match policy {
            CapabilityPolicy::Allow => self.host_integrations.push(integration),
            CapabilityPolicy::Deny => self.denied_host_integrations.push(integration),
            CapabilityPolicy::Ask => {}
        }
        self
    }

    /// Installs explicitly discovered native and auxiliary GnuPG socket paths.
    #[must_use]
    pub fn with_gpg_agent_sockets(mut self, sockets: GpgAgentSockets) -> Self {
        self.gpg_agent_sockets = Some(sockets);
        self
    }

    /// Sets environment assignments that the backend validates before applying.
    #[must_use]
    pub fn with_environment_overrides(
        mut self,
        environment_overrides: impl IntoIterator<Item = (OsString, OsString)>,
    ) -> Self {
        self.environment_overrides = environment_overrides.into_iter().collect();
        self
    }

    /// Replaces the environment-variable isolation policy enforced across
    /// both isolated and host process runners.
    #[must_use]
    pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
        self.env_isolation = env_isolation;
        self
    }

    /// Returns the trusted filesystem rules installed for isolated actions.
    #[must_use]
    pub fn path_rules(&self) -> &[PathAccessRule] {
        &self.path_rules
    }

    /// Returns the configured three-state network policy.
    #[must_use]
    pub const fn network_policy(&self) -> CapabilityPolicy {
        self.network_policy
    }

    /// Returns workspace-persisted allowed domains for web/browser tools.
    #[must_use]
    pub fn allowed_domains(&self) -> &[String] {
        &self.allowed_domains
    }

    /// Returns whether local browser targets are allowed without review.
    #[must_use]
    pub const fn browser_allow_local(&self) -> bool {
        self.browser_allow_local
    }

    /// Returns whether isolated sessions allow network requests (`ask` or `allow`).
    #[must_use]
    pub const fn network_requests_allowed(&self) -> bool {
        self.network_policy.allows_requests()
    }

    /// Returns host integrations already approved by the embedding application.
    #[must_use]
    pub fn host_integrations(&self) -> &[HostIntegration] {
        &self.host_integrations
    }

    /// Returns host integrations hard-denied by the embedding application.
    #[must_use]
    pub fn denied_host_integrations(&self) -> &[HostIntegration] {
        &self.denied_host_integrations
    }

    /// Returns the validated environment assignments applied by the backend.
    #[must_use]
    pub fn environment_overrides(&self) -> &[(OsString, OsString)] {
        &self.environment_overrides
    }
}

#[cfg(test)]
mod tests;