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
use super::{background::BackgroundSupervisor, environment::WorkspaceProcessEnvironment};
use crate::resolve_host_path;
use merry_core::CapabilityPolicy;
use merry_runtime::{
    HostIntegration, PathAccess, PathAccessDecision, PathAccessRule, PathAccessRuleSource,
    PathDenialReason, PermissionRequest, PermissionedProcessRunnerFactory,
    PreparedProcessPermission, ProcessActionIntent, ProcessPathGrant, ProcessPathGrantConstraint,
    ProcessRunner, ProcessRunnerError, ProcessSessionPermissionSnapshot,
    ProcessSessionPermissionView, ProcessSessionPermissions, RequestedCapability,
    SessionPermissionedProcessRunnerFactory, WorkspaceAccessPolicy,
};
use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

/// Host-process runner that confines each process action.
///
/// Linux applies Landlock and, unless the action was granted network, a seccomp
/// filter. macOS applies a Seatbelt profile. The Merry process itself stays
/// unrestricted.
#[derive(Debug, Clone)]
pub struct WorkspaceProcessRunner {
    pub(super) cwd_root: PathBuf,
    pub(super) environment: WorkspaceProcessEnvironment,
    pub(super) network_allowed: bool,
    pub(super) path_rules: Vec<PathAccessRule>,
    /// Paths explicitly requested by this action (never inherited from earlier
    /// session-retained grants) that Landlock must verify exist before exec.
    pub(super) action_required_rules: Vec<PathAccessRule>,
    pub(super) session_permissions: Option<ProcessSessionPermissionView>,
    pub(super) configuration_error: Option<String>,
    workspace_writable: bool,
    /// Keeps background children after `run` returns. Session drop kills them.
    pub(super) background: BackgroundSupervisor,
}

impl WorkspaceProcessRunner {
    /// Creates a per-action workspace runner rooted at a workspace path.
    #[must_use]
    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
        Self {
            cwd_root: root.into(),
            environment: WorkspaceProcessEnvironment::from_current_process(),
            network_allowed: false,
            path_rules: Vec::new(),
            action_required_rules: Vec::new(),
            session_permissions: None,
            configuration_error: None,
            workspace_writable: true,
            background: BackgroundSupervisor::new(),
        }
    }

    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
        self.background = background;
        self
    }

    /// Keeps the workspace readable and not writable.
    ///
    /// Baseline paths such as `/tmp` stay writable. This does not turn the
    /// sandbox off.
    #[must_use]
    pub fn read_only_workspace(mut self) -> Self {
        self.workspace_writable = false;
        self
    }

    /// Sets the environment layout visible to child processes.
    #[must_use]
    pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
        self.environment = environment;
        self
    }

    /// Allows network access for child process actions.
    #[must_use]
    pub fn allow_network(mut self) -> Self {
        self.network_allowed = true;
        self
    }

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

    /// Shares session-scoped approved capabilities with the permissioned runner factory.
    #[must_use]
    pub fn with_session_permissions(mut self, permissions: ProcessSessionPermissions) -> Self {
        self.session_permissions = Some(permissions.view());
        self
    }

    /// Rejects allow-list conflicts before a session can run a command.
    ///
    /// # Errors
    ///
    /// Returns the same conflict `plan_for` would return for these rules when a
    /// deny, review, or private path sits inside an allowed directory.
    pub(crate) fn ensure_sandbox_rules(&self) -> Result<(), ProcessRunnerError> {
        if let Some(message) = self.configuration_error.clone() {
            return Err(ProcessRunnerError::infrastructure(message));
        }
        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
        let path_rules = normalize_path_rules(self.path_rules.clone());
        crate::confinement::check_sandbox_rules(
            &self.cwd_root,
            &environment,
            &path_rules,
            &self.action_required_rules,
            self.workspace_writable,
        )
    }

    pub(super) fn plan_for(
        &self,
        intent: &ProcessActionIntent,
    ) -> Result<crate::confinement::SandboxLaunch, ProcessRunnerError> {
        if let Some(message) = self.configuration_error.clone() {
            return Err(ProcessRunnerError::infrastructure(message));
        }
        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
        let session_snapshot = self
            .session_permissions
            .as_ref()
            .map(ProcessSessionPermissionView::snapshot)
            .transpose()?;
        let mut environment = environment;
        let mut path_rules = self.path_rules.clone();
        let mut effective_network = self.network_allowed;
        if let Some(snapshot) = session_snapshot {
            path_rules.extend(snapshot.path_rules().iter().cloned());
            environment =
                environment.with_host_integrations(snapshot.host_integrations().iter().copied());
            if snapshot.network_allowed() {
                effective_network = true;
            }
        }
        path_rules = normalize_path_rules(path_rules);
        crate::confinement::prepare_launch(
            intent,
            &self.cwd_root,
            &environment,
            effective_network,
            &path_rules,
            &self.action_required_rules,
            self.workspace_writable,
        )
    }
}

/// Builds a workspace runner from an approved permission request.
///
/// Filesystem access stays governed by the configured path rules and the
/// session-scoped capabilities explicitly retained by the runtime. Ordinary
/// paths, host integrations, and outbound network are retained only when
/// approved with [`merry_core::ApprovalScope::Session`]; explicitly reviewed
/// paths and protected metadata remain strictly action-scoped.
#[derive(Debug, Clone)]
pub struct WorkspaceProcessRunnerFactory {
    pub(super) cwd_root: PathBuf,
    pub(super) environment: WorkspaceProcessEnvironment,
    pub(super) path_rules: Vec<PathAccessRule>,
    network_policy: CapabilityPolicy,
    denied_host_integrations: Vec<HostIntegration>,
    pub(super) session_permissions: Option<ProcessSessionPermissionView>,
    workspace_writable: bool,
    /// Shared by every runner this factory builds. `runner_for` drops its
    /// runner when the tool call returns, so background children cannot live
    /// only on that runner.
    background: BackgroundSupervisor,
}

impl WorkspaceProcessRunnerFactory {
    /// Creates a workspace-sandbox runner factory rooted at a workspace path.
    #[must_use]
    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
        Self {
            cwd_root: root.into(),
            environment: WorkspaceProcessEnvironment::from_current_process(),
            path_rules: Vec::new(),
            network_policy: CapabilityPolicy::Ask,
            denied_host_integrations: Vec::new(),
            session_permissions: None,
            workspace_writable: true,
            background: BackgroundSupervisor::new(),
        }
    }

    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
        self.background = background;
        self
    }

    /// Keeps the workspace readable and not writable for every child runner.
    #[must_use]
    pub fn read_only_workspace(mut self) -> Self {
        self.workspace_writable = false;
        self
    }

    /// Sets the environment layout used by every materialized child runner.
    #[must_use]
    pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
        self.environment = environment;
        self
    }

    /// Installs trusted path rules shared by each materialized runner.
    #[must_use]
    pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
        self.path_rules = rules.into_iter().collect();
        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 whether network capability requests can proceed to review.
    ///
    /// Defaults to true (`Ask`) without preauthorizing access. False (`Deny`)
    /// rejects requests during validation and materialization, including direct
    /// runner creation.
    #[must_use]
    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
        self.network_policy = if allowed {
            CapabilityPolicy::Ask
        } else {
            CapabilityPolicy::Deny
        };
        self
    }

    /// Sets host integrations hard-denied (`deny`) by configuration.
    #[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
    }

    /// Attaches a read-only capability view and returns the runtime-owned
    /// retention decorator. Configure backend-specific options before attaching it.
    #[must_use]
    pub fn with_session_permissions(
        mut self,
        permissions: ProcessSessionPermissions,
    ) -> SessionPermissionedProcessRunnerFactory<Self> {
        self.session_permissions = Some(permissions.view());
        permissions.with_factory(self)
    }

    fn access_policy(&self) -> WorkspaceAccessPolicy {
        WorkspaceAccessPolicy::new(&self.cwd_root, self.workspace_writable)
            .with_static_rules(self.path_rules.iter().cloned())
    }

    fn requested_path_rules_for_request(
        &self,
        request: &PermissionRequest,
        policy: &WorkspaceAccessPolicy,
        snapshot: &ProcessSessionPermissionSnapshot,
    ) -> Result<(Vec<PathAccessRule>, Vec<PathAccessRule>), ProcessRunnerError> {
        let mut new_rules = Vec::new();
        let mut action_required = Vec::new();
        for capability in request.requested() {
            let RequestedCapability::Path(requested) = capability else {
                continue;
            };
            let path = materialize_requested_path(&self.cwd_root, requested.path());
            let effective_access =
                effective_requested_path_access(policy, &path, requested.access(), snapshot)?;
            let rule = PathAccessRule::new(
                path.clone(),
                effective_access,
                PathAccessRuleSource::PermissionReview,
            );
            action_required.push(rule.clone());
            if !policy.explicit_rules_cover(&path, effective_access, Some(snapshot)) {
                new_rules.push(rule);
            }
        }
        Ok((new_rules, action_required))
    }

    fn requested_host_integrations_for_request(
        &self,
        request: &PermissionRequest,
    ) -> Vec<HostIntegration> {
        request
            .requested()
            .iter()
            .filter_map(|capability| match capability {
                RequestedCapability::HostIntegration(integration) => Some(*integration),
                _ => None,
            })
            .collect()
    }

    pub(super) fn build_runner(&self, request: &PermissionRequest) -> WorkspaceProcessRunner {
        match self.prepare_runner(request) {
            Ok((runner, _)) => runner,
            Err(error) => {
                let mut runner = WorkspaceProcessRunner::new_at_workspace_root(&self.cwd_root);
                runner.configuration_error = Some(error.to_string());
                runner.background = self.background.clone();
                runner
            }
        }
    }

    fn prepare_runner(
        &self,
        request: &PermissionRequest,
    ) -> Result<(WorkspaceProcessRunner, Vec<ProcessPathGrant>), ProcessRunnerError> {
        self.validate_network_request(request)?;
        let mut environment = self.environment.validate_for_workspace(&self.cwd_root)?;
        let integrations = self.requested_host_integrations_for_request(request);
        self.validate_denied_host_integrations(&integrations)?;
        environment.validate_requested_host_integrations(&integrations)?;
        let snapshot = self
            .session_permissions
            .as_ref()
            .map(ProcessSessionPermissionView::snapshot)
            .transpose()?
            .unwrap_or_default();
        let policy = self.access_policy();
        let mut path_rules = self.path_rules.clone();
        path_rules.extend(snapshot.path_rules().iter().cloned());
        path_rules = normalize_path_rules(path_rules);
        let (requested_rules, action_required_rules) =
            self.requested_path_rules_for_request(request, &policy, &snapshot)?;
        let grants = requested_rules
            .iter()
            .map(|rule| {
                let eval = policy.evaluate_path(rule.path(), rule.access(), None, &[]);
                let constraint = if eval.git_metadata || eval.protected_target {
                    ProcessPathGrantConstraint::ProtectedMetadata
                } else {
                    ProcessPathGrantConstraint::Ordinary
                };
                ProcessPathGrant::new(
                    PathAccessRule::new(
                        resolve_host_path(rule.path()),
                        rule.access(),
                        rule.source(),
                    ),
                    constraint,
                )
            })
            .collect();
        path_rules.extend(requested_rules);
        path_rules = normalize_path_rules(path_rules);
        environment = environment
            .with_host_integrations(integrations)
            .with_host_integrations(snapshot.host_integrations().iter().copied());
        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(self.cwd_root.clone())
            .with_environment(environment)
            .with_path_rules(path_rules);
        if !self.workspace_writable {
            runner = runner.read_only_workspace();
        }
        if request.requests_network()
            || self.network_policy.is_preauthorized()
            || snapshot.network_allowed()
        {
            runner = runner.allow_network();
        }
        runner.action_required_rules = action_required_rules;
        runner.session_permissions = self.session_permissions.clone();
        runner.background = self.background.clone();
        runner.ensure_sandbox_rules()?;
        Ok((runner, grants))
    }

    /// Enforces the capability ceiling before review, grants, or runner construction.
    fn validate_network_request(
        &self,
        request: &PermissionRequest,
    ) -> Result<(), ProcessRunnerError> {
        if request.requests_network() && self.network_policy.is_denied() {
            return Err(ProcessRunnerError::infrastructure(
                "network requests are disabled by the configured process capability ceiling",
            ));
        }
        Ok(())
    }

    fn validate_denied_host_integrations(
        &self,
        requested: &[HostIntegration],
    ) -> Result<(), ProcessRunnerError> {
        for integration in requested {
            if self.denied_host_integrations.contains(integration) {
                return Err(ProcessRunnerError::infrastructure(format!(
                    "host integration `{}` is disabled by configured permission policy",
                    integration.as_str()
                )));
            }
        }
        Ok(())
    }
}

impl PermissionedProcessRunnerFactory for WorkspaceProcessRunnerFactory {
    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
        self.prepare_runner(request).map(|_| ())
    }

    fn request_capabilities_are_satisfied(
        &self,
        request: &PermissionRequest,
    ) -> Result<bool, ProcessRunnerError> {
        self.validate_network_request(request)?;
        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
        let snapshot = self
            .session_permissions
            .as_ref()
            .map(ProcessSessionPermissionView::snapshot)
            .transpose()?
            .unwrap_or_default();

        let requested_integrations = self.requested_host_integrations_for_request(request);
        self.validate_denied_host_integrations(&requested_integrations)?;
        environment.validate_requested_host_integrations(&requested_integrations)?;
        let network_satisfied =
            self.network_policy.is_preauthorized() || snapshot.network_allowed();
        if request.requests_network() && !network_satisfied {
            return Ok(false);
        }

        let mut available_integrations = environment.host_integrations.clone();
        available_integrations.extend(snapshot.host_integrations().iter().copied());
        available_integrations.sort_unstable();
        available_integrations.dedup();
        if requested_integrations
            .iter()
            .any(|integration| !available_integrations.contains(integration))
        {
            return Ok(false);
        }

        let policy = self.access_policy();
        for capability in request.requested() {
            let satisfied = match capability {
                RequestedCapability::Network => network_satisfied,
                RequestedCapability::NetworkDomain(domain) => {
                    network_satisfied || snapshot.allows_domain(domain)
                }
                RequestedCapability::HostIntegration(_) => true,
                RequestedCapability::Path(requested) => {
                    let path = materialize_requested_path(&self.cwd_root, requested.path());
                    policy
                        .evaluate_directory_grant(&path, requested.access(), Some(&snapshot), &[])
                        .decision
                        == PathAccessDecision::Allow
                }
            };
            if !satisfied {
                return Ok(false);
            }
        }
        Ok(true)
    }

    fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
        let policy = self.access_policy();
        request.requested().iter().any(|capability| {
            let RequestedCapability::Path(requested) = capability else {
                return false;
            };
            let path = materialize_requested_path(&self.cwd_root, requested.path());
            policy.is_protected_target(&path, requested.access())
        })
    }

    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
        Arc::new(self.build_runner(request))
    }

    fn prepare_approved_request(
        &self,
        request: &PermissionRequest,
    ) -> Result<PreparedProcessPermission, ProcessRunnerError> {
        let (runner, grants) = self.prepare_runner(request)?;
        Ok(PreparedProcessPermission::new(Arc::new(runner), grants))
    }
}

fn materialize_requested_path(root: &Path, requested: &str) -> PathBuf {
    let path = Path::new(requested);
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    }
}

fn effective_requested_path_access(
    policy: &WorkspaceAccessPolicy,
    requested_path: &Path,
    requested_access: PathAccess,
    snapshot: &ProcessSessionPermissionSnapshot,
) -> Result<PathAccess, ProcessRunnerError> {
    let resolved = resolve_host_path(requested_path);
    let eval = policy.evaluate_directory_grant(&resolved, requested_access, Some(snapshot), &[]);
    match eval.denial_reason {
        Some(PathDenialReason::UserHardDeny) => {
            let blocking = policy
                .blocking_rule_path(&resolved, requested_access)
                .unwrap_or_else(|| resolved.clone());
            Err(ProcessRunnerError::infrastructure(format!(
                "requested path `{}` is denied by configured path policy `{}`",
                resolved.display(),
                blocking.display()
            )))
        }
        Some(PathDenialReason::CoversDeniedDescendant) => {
            let blocking = policy
                .blocking_rule_path(&resolved, requested_access)
                .unwrap_or_else(|| resolved.clone());
            Err(ProcessRunnerError::infrastructure(format!(
                "requested path `{}` covers denied path `{}`; narrow the request so it excludes protected paths",
                resolved.display(),
                blocking.display()
            )))
        }
        Some(PathDenialReason::CoversProtectedReadOnlyDescendant) => {
            let blocking = policy
                .blocking_rule_path(&resolved, requested_access)
                .unwrap_or_else(|| resolved.clone());
            Err(ProcessRunnerError::infrastructure(format!(
                "requested writable path `{}` covers Merry protected read-only path `{}`; request write access on `{}` directly or narrow the request",
                resolved.display(),
                blocking.display(),
                blocking.display()
            )))
        }
        Some(PathDenialReason::UserReadOnlyCeiling) => {
            // Explicit global read-only rules are a hard ceiling. Git metadata
            // baselines and Merry's default `ProductReadOnly` directories are
            // intentionally different: a reviewed action may temporarily overlay
            // them directly, but the grant is never session-persistent.
            Ok(PathAccess::ReadOnly)
        }
        Some(PathDenialReason::ReadOnlyWorkspace | PathDenialReason::InvalidAccess) | None => {
            Ok(requested_access)
        }
    }
}

fn normalize_path_rules(rules: Vec<PathAccessRule>) -> Vec<PathAccessRule> {
    let mut merged =
        std::collections::BTreeMap::<PathBuf, (PathAccess, PathAccessRuleSource)>::new();
    for rule in rules {
        let access = rule.access();
        let key = resolve_host_path(rule.path());
        let entry = merged.entry(key).or_insert((access, rule.source()));
        (entry.0, entry.1) = merged_path_rule(entry.0, entry.1, access, rule.source());
    }
    let mut rules = merged
        .into_iter()
        .map(|(path, (access, source))| PathAccessRule::new(path, access, source))
        .collect::<Vec<_>>();
    rules.sort_by(|left, right| {
        path_depth(left.path())
            .cmp(&path_depth(right.path()))
            .then_with(|| left.path().cmp(right.path()))
    });
    rules
}

fn merged_path_rule(
    left_access: PathAccess,
    left_source: PathAccessRuleSource,
    right_access: PathAccess,
    right_source: PathAccessRuleSource,
) -> (PathAccess, PathAccessRuleSource) {
    let left_is_hard_deny =
        left_access == PathAccess::Deny && left_source != PathAccessRuleSource::ProductPrivate;
    let right_is_hard_deny =
        right_access == PathAccess::Deny && right_source != PathAccessRuleSource::ProductPrivate;
    if left_is_hard_deny {
        return (left_access, left_source);
    }
    if right_is_hard_deny {
        return (right_access, right_source);
    }
    if left_access == PathAccess::Deny && right_source == PathAccessRuleSource::PermissionReview {
        return (right_access, right_source);
    }
    if right_access == PathAccess::Deny && left_source == PathAccessRuleSource::PermissionReview {
        return (left_access, left_source);
    }
    if left_access == PathAccess::Deny {
        return (left_access, left_source);
    }
    if right_access == PathAccess::Deny {
        return (right_access, right_source);
    }

    let left_is_hard_read_only = left_access == PathAccess::ReadOnly
        && left_source == PathAccessRuleSource::TrustedGlobalConfig;
    let right_is_hard_read_only = right_access == PathAccess::ReadOnly
        && right_source == PathAccessRuleSource::TrustedGlobalConfig;
    if left_is_hard_read_only {
        return (left_access, left_source);
    }
    if right_is_hard_read_only {
        return (right_access, right_source);
    }

    // Built-in ProductReadOnly protection beats saved workspace paths so a
    // hand-edited workspace-permissions.json can never escalate writes into
    // `$XDG_CONFIG_HOME/merry` or `$XDG_STATE_HOME/merry`.
    if left_access == PathAccess::ReadOnly
        && left_source == PathAccessRuleSource::ProductReadOnly
        && right_source == PathAccessRuleSource::WorkspacePermissions
    {
        return (left_access, left_source);
    }
    if right_access == PathAccess::ReadOnly
        && right_source == PathAccessRuleSource::ProductReadOnly
        && left_source == PathAccessRuleSource::WorkspacePermissions
    {
        return (right_access, right_source);
    }

    let left_is_reviewed_write = left_access == PathAccess::ReadWrite
        && left_source == PathAccessRuleSource::PermissionReview;
    let right_is_reviewed_write = right_access == PathAccess::ReadWrite
        && right_source == PathAccessRuleSource::PermissionReview;
    if left_is_reviewed_write {
        return (left_access, left_source);
    }
    if right_is_reviewed_write {
        return (right_access, right_source);
    }

    match (left_access, right_access) {
        (PathAccess::ReadWrite, _) => (left_access, left_source),
        (_, PathAccess::ReadWrite) => (right_access, right_source),
        _ => (PathAccess::ReadOnly, left_source),
    }
}

fn path_depth(path: &Path) -> usize {
    path.components().count()
}