merry-runtime 0.1.4

Structured session, task ledger, context compaction, memory, permission, and tool runtime 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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Unified filesystem access policy shared by in-process workspace tools,
//! host-process sandbox backends, and workspace persistence guards.
//!
//! This module is pure Rust with zero process spawning (`fork`/`exec`), so it
//! works identically across desktop CLI, headless SDKs, Windows, and Apple App
//! Sandbox targets (`rootshell` on iOS / Mac Catalyst / visionOS).

use crate::{
    ChildWorkspacePolicyOverride, PathAccess, PathAccessRule, PathAccessRuleSource,
    ProcessSessionPermissionSnapshot, ProcessSessionPermissionView,
};
use merry_core::HostPathPolicy;
use std::{
    fs,
    path::{Component, Path, PathBuf},
};

/// Three-state decision produced by [`WorkspaceAccessPolicy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathAccessDecision {
    /// Path is authorized by workspace, static rules, session grants, or once grants.
    Allow,
    /// Path is outside current grants and requires permission admission review.
    RequireReview,
    /// Path is blocked by a hard policy ceiling (`Deny`, trusted global
    /// `ReadOnly` write ceiling, read-only workspace, or descendant coverage
    /// of a protected path) and cannot be escalated by runtime approval.
    Deny,
}

/// Specific reason a path evaluation returned [`PathAccessDecision::Deny`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathDenialReason {
    /// Blocked by a user-configured or non-`ProductPrivate` hard `Deny` rule.
    UserHardDeny,
    /// Write blocked by a `TrustedGlobalConfig` `ReadOnly` hard write ceiling.
    UserReadOnlyCeiling,
    /// Write blocked because the active workspace is read-only.
    ReadOnlyWorkspace,
    /// Directory grant covers a strictly nested denied path.
    CoversDeniedDescendant,
    /// Writable directory grant covers a strictly nested Merry `ProductReadOnly` path.
    CoversProtectedReadOnlyDescendant,
    /// Requested `PathAccess::Deny` is never an executable grant.
    InvalidAccess,
}

/// Structured result of evaluating a path against Merry's single authoritative
/// filesystem access policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PathEvaluation {
    /// Final three-state admission decision.
    pub decision: PathAccessDecision,
    /// Whether the target hits a built-in Merry protected path (`ProductPrivate`
    /// or `ProductReadOnly` write) that must remain `Once`-only and default-`Deny`.
    pub protected_target: bool,
    /// Whether the lexical or canonical target touches `.git` metadata.
    pub git_metadata: bool,
    /// Specific reason when `decision == PathAccessDecision::Deny`.
    pub denial_reason: Option<PathDenialReason>,
}

impl PathEvaluation {
    #[must_use]
    pub(crate) const fn allow(git_metadata: bool) -> Self {
        Self {
            decision: PathAccessDecision::Allow,
            protected_target: false,
            git_metadata,
            denial_reason: None,
        }
    }

    #[must_use]
    pub(crate) const fn require_review(git_metadata: bool) -> Self {
        Self {
            decision: PathAccessDecision::RequireReview,
            protected_target: false,
            git_metadata,
            denial_reason: None,
        }
    }

    #[must_use]
    pub(crate) const fn deny(reason: PathDenialReason, git_metadata: bool) -> Self {
        Self {
            decision: PathAccessDecision::Deny,
            protected_target: false,
            git_metadata,
            denial_reason: Some(reason),
        }
    }

    #[must_use]
    pub(crate) const fn protected(decision: PathAccessDecision, git_metadata: bool) -> Self {
        Self {
            decision,
            protected_target: true,
            git_metadata,
            denial_reason: None,
        }
    }
}

/// Pre-resolved static path rule so hot-path evaluations never repeat
/// `fs::canonicalize()` syscalls across multiple precedence passes.
#[derive(Debug, Clone)]
pub(crate) struct ResolvedPathRule {
    pub(crate) resolved: PathBuf,
    pub(crate) depth: usize,
    pub(crate) access: PathAccess,
    pub(crate) source: PathAccessRuleSource,
}

impl ResolvedPathRule {
    pub(crate) fn from_rule(rule: &PathAccessRule) -> Self {
        let resolved = resolve_rule_path(rule.path());
        let depth = resolved.components().count();
        Self {
            resolved,
            depth,
            access: rule.access(),
            source: rule.source(),
        }
    }
}

/// Single-source-of-truth filesystem allowlist evaluated by in-process file
/// tools (`read_file`, `apply_patch`), host-process sandboxes (`merry-process`),
/// and persistence guards (`merry-app`).
#[derive(Debug, Clone)]
pub struct WorkspaceAccessPolicy {
    workspace_root: PathBuf,
    workspace_root_canonical: PathBuf,
    workspace_writable: bool,
    static_rules: Vec<ResolvedPathRule>,
    session_permissions: Option<ProcessSessionPermissionView>,
}

impl WorkspaceAccessPolicy {
    /// Creates an access policy rooted at `workspace_root`.
    #[must_use]
    pub fn new(workspace_root: impl Into<PathBuf>, workspace_writable: bool) -> Self {
        let workspace_root = normalize_path_lexically(&workspace_root.into());
        let workspace_root_canonical = resolve_path_with_existing_ancestor(&workspace_root);
        Self {
            workspace_root,
            workspace_root_canonical,
            workspace_writable,
            static_rules: Vec::new(),
            session_permissions: None,
        }
    }

    /// Installs static baseline, trusted-config, and product path rules,
    /// canonicalizing each rule path once up front.
    #[must_use]
    pub fn with_static_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
        self.static_rules = rules
            .into_iter()
            .map(|rule| ResolvedPathRule::from_rule(&rule))
            .collect();
        self
    }

    /// Attaches a live read-only view of session-approved capability grants.
    #[must_use]
    pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
        self.session_permissions = Some(view);
        self
    }

    /// Returns the workspace root path.
    #[must_use]
    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

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

    /// Returns canonicalized `ProductPrivate` paths configured in static rules.
    #[must_use]
    pub fn product_private_paths(&self) -> Vec<PathBuf> {
        self.static_rules
            .iter()
            .filter(|entry| {
                entry.access == PathAccess::Deny
                    && entry.source == PathAccessRuleSource::ProductPrivate
            })
            .map(|entry| entry.resolved.clone())
            .collect()
    }

    /// Evaluates read access for `path` under the current policy, attached
    /// session grants, and optional single-action `once_grants`.
    #[must_use]
    pub fn evaluate_read(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathAccessDecision {
        let snapshot = self
            .session_permissions
            .as_ref()
            .and_then(|view| view.snapshot().ok());
        self.evaluate_path(path, PathAccess::ReadOnly, snapshot.as_ref(), once_grants)
            .decision
    }

    /// Evaluates write access for `path` under the current policy, attached
    /// session grants, and optional single-action `once_grants`.
    #[must_use]
    pub fn evaluate_write(
        &self,
        path: &Path,
        once_grants: &[PathAccessRule],
    ) -> PathAccessDecision {
        let snapshot = self
            .session_permissions
            .as_ref()
            .and_then(|view| view.snapshot().ok());
        self.evaluate_path(path, PathAccess::ReadWrite, snapshot.as_ref(), once_grants)
            .decision
    }

    /// Pure single-path evaluation returning structured decision, protected
    /// target flag, `.git` flag, and denial reason.
    #[must_use]
    pub fn evaluate_path(
        &self,
        path: &Path,
        requested: PathAccess,
        session: Option<&ProcessSessionPermissionSnapshot>,
        once_grants: &[PathAccessRule],
    ) -> PathEvaluation {
        self.evaluate_inner(None, path, requested, session, once_grants, false)
    }

    /// Evaluates a single path with an optional child-session override without
    /// cloning `static_rules` or re-canonicalizing rule paths.
    #[must_use]
    pub(crate) fn evaluate_with_child_override(
        &self,
        child: Option<&ChildWorkspacePolicyOverride>,
        path: &Path,
        requested: PathAccess,
        session: Option<&ProcessSessionPermissionSnapshot>,
        once_grants: &[PathAccessRule],
    ) -> PathEvaluation {
        self.evaluate_inner(child, path, requested, session, once_grants, false)
    }

    /// Pure directory-grant evaluation (used by process sandboxes) that also
    /// rejects grants covering strictly nested denied or `ProductReadOnly` paths.
    #[must_use]
    pub fn evaluate_directory_grant(
        &self,
        path: &Path,
        requested: PathAccess,
        session: Option<&ProcessSessionPermissionSnapshot>,
        once_grants: &[PathAccessRule],
    ) -> PathEvaluation {
        self.evaluate_inner(None, path, requested, session, once_grants, true)
    }

    /// Returns whether `path` is already covered at `requested` access by
    /// configured static rules or retained session grants (independent of
    /// implicit workspace membership), and not blocked by any ceiling or
    /// descendant constraint.
    #[must_use]
    pub fn explicit_rules_cover(
        &self,
        path: &Path,
        requested: PathAccess,
        session: Option<&ProcessSessionPermissionSnapshot>,
    ) -> bool {
        let eval = self.evaluate_directory_grant(path, requested, session, &[]);
        if eval.decision != PathAccessDecision::Allow {
            return false;
        }
        let resolved = resolve_rule_path(path);
        let session_rules = session
            .map(ProcessSessionPermissionSnapshot::path_rules)
            .unwrap_or(&[]);
        resolved_and_dynamic_rules_cover_path(
            self.static_rules.iter(),
            session_rules.iter(),
            &resolved,
            requested,
        )
    }

    /// Returns whether `path` targets a built-in Merry protected path
    /// (`ProductPrivate` or `ProductReadOnly` write).
    #[must_use]
    pub fn is_protected_target(&self, path: &Path, requested: PathAccess) -> bool {
        let resolved = resolve_rule_path(path);
        requires_built_in_product_review(&self.static_rules, &[], &resolved, requested)
    }

    /// Returns the blocking rule path when a directory grant is rejected by a
    /// hard deny or descendant coverage rule, for actionable error messages.
    #[must_use]
    pub fn blocking_rule_path(&self, path: &Path, requested: PathAccess) -> Option<PathBuf> {
        let resolved = resolve_rule_path(path);
        if let Some(rule_path) = effective_user_hard_deny_path(&self.static_rules, &[], &resolved) {
            return Some(rule_path);
        }
        if let Some(child_path) = covered_denied_descendant_path(&self.static_rules, &[], &resolved)
        {
            return Some(child_path);
        }
        if requested == PathAccess::ReadWrite
            && let Some(child_path) =
                covered_protected_readonly_descendant_path(&self.static_rules, &[], &resolved)
        {
            return Some(child_path);
        }
        None
    }

    fn evaluate_inner(
        &self,
        child: Option<&ChildWorkspacePolicyOverride>,
        path: &Path,
        requested: PathAccess,
        session: Option<&ProcessSessionPermissionSnapshot>,
        once_grants: &[PathAccessRule],
        check_descendants: bool,
    ) -> PathEvaluation {
        let lexical = normalize_path_lexically(path);
        let resolved = resolve_path_with_existing_ancestor(&lexical);
        let git_metadata = is_git_metadata_path_parts(&lexical, &resolved);

        if requested == PathAccess::Deny {
            return PathEvaluation::deny(PathDenialReason::InvalidAccess, git_metadata);
        }

        let (effective_root, effective_writable, extra_rules) = match child {
            Some(override_cfg) => (
                override_cfg
                    .workspace_root_canonical()
                    .unwrap_or(&self.workspace_root_canonical),
                self.workspace_writable && override_cfg.workspace_writable(),
                override_cfg.extra_resolved_rules(),
            ),
            None => (
                self.workspace_root_canonical.as_path(),
                self.workspace_writable,
                &[][..],
            ),
        };
        let in_workspace = path_within(&resolved, effective_root);

        // 1. User-configured hard ceilings always win over built-in product
        //    review and runtime approvals.
        if let Some(reason) = user_hard_ceiling_reason(
            &self.static_rules,
            extra_rules,
            &resolved,
            requested,
            in_workspace,
            effective_writable,
            effective_root.components().count(),
        ) {
            return PathEvaluation::deny(reason, git_metadata);
        }

        // 2. Directory grants (process sandbox) must not cover strictly nested
        //    denied or protected read-only paths.
        if check_descendants {
            if covered_denied_descendant_path(&self.static_rules, extra_rules, &resolved).is_some()
            {
                return PathEvaluation::deny(
                    PathDenialReason::CoversDeniedDescendant,
                    git_metadata,
                );
            }
            if requested == PathAccess::ReadWrite
                && covered_protected_readonly_descendant_path(
                    &self.static_rules,
                    extra_rules,
                    &resolved,
                )
                .is_some()
            {
                return PathEvaluation::deny(
                    PathDenialReason::CoversProtectedReadOnlyDescendant,
                    git_metadata,
                );
            }
        }

        // 3. Built-in Merry product protections (`ProductPrivate` credentials
        //    and `ProductReadOnly` writes) require explicit single-action review.
        if requires_built_in_product_review(&self.static_rules, extra_rules, &resolved, requested) {
            let decision = if dynamic_rules_cover_path(once_grants.iter(), &resolved, requested) {
                PathAccessDecision::Allow
            } else {
                PathAccessDecision::RequireReview
            };
            return PathEvaluation::protected(decision, git_metadata);
        }

        // 4. Only the resolved canonical target determines workspace membership;
        //    `.git` writes are excluded from automatic workspace writability.
        if in_workspace && !(requested == PathAccess::ReadWrite && git_metadata) {
            return match requested {
                PathAccess::ReadOnly => PathEvaluation::allow(git_metadata),
                PathAccess::ReadWrite if effective_writable => PathEvaluation::allow(git_metadata),
                PathAccess::ReadWrite | PathAccess::Deny => {
                    PathEvaluation::deny(PathDenialReason::ReadOnlyWorkspace, git_metadata)
                }
            };
        }

        let session_rules = session
            .map(ProcessSessionPermissionSnapshot::path_rules)
            .unwrap_or(&[]);
        if resolved_and_dynamic_rules_cover_path(
            self.static_rules.iter().chain(extra_rules.iter()),
            once_grants.iter().chain(session_rules.iter()),
            &resolved,
            requested,
        ) {
            PathEvaluation::allow(git_metadata)
        } else {
            PathEvaluation::require_review(git_metadata)
        }
    }
}

fn chained_rules<'a>(
    base: &'a [ResolvedPathRule],
    extra: &'a [ResolvedPathRule],
) -> impl Iterator<Item = &'a ResolvedPathRule> + Clone {
    base.iter().chain(extra.iter())
}

fn effective_user_hard_deny_path(
    base: &[ResolvedPathRule],
    extra: &[ResolvedPathRule],
    resolved: &Path,
) -> Option<PathBuf> {
    chained_rules(base, extra)
        .filter(|entry| {
            entry.access == PathAccess::Deny && entry.source != PathAccessRuleSource::ProductPrivate
        })
        .filter(|entry| path_within(resolved, &entry.resolved))
        .max_by_key(|entry| entry.depth)
        .map(|entry| entry.resolved.clone())
}

fn user_hard_ceiling_reason(
    base: &[ResolvedPathRule],
    extra: &[ResolvedPathRule],
    resolved: &Path,
    requested: PathAccess,
    in_workspace: bool,
    workspace_writable: bool,
    workspace_depth: usize,
) -> Option<PathDenialReason> {
    if effective_user_hard_deny_path(base, extra, resolved).is_some() {
        return Some(PathDenialReason::UserHardDeny);
    }

    if requested == PathAccess::ReadWrite {
        let deepest_trusted_ro_depth = chained_rules(base, extra)
            .filter(|entry| {
                entry.access == PathAccess::ReadOnly
                    && entry.source == PathAccessRuleSource::TrustedGlobalConfig
                    && path_within(resolved, &entry.resolved)
            })
            .map(|entry| entry.depth)
            .max();
        if let Some(ro_depth) = deepest_trusted_ro_depth {
            let deeper_writable_workspace =
                in_workspace && workspace_writable && workspace_depth > ro_depth;
            let deeper_trusted_rw = chained_rules(base, extra).any(|entry| {
                entry.access == PathAccess::ReadWrite
                    && entry.source == PathAccessRuleSource::TrustedGlobalConfig
                    && entry.depth > ro_depth
                    && path_within(resolved, &entry.resolved)
            });
            if !deeper_writable_workspace && !deeper_trusted_rw {
                return Some(PathDenialReason::UserReadOnlyCeiling);
            }
        }
    }

    None
}

fn covered_denied_descendant_path(
    base: &[ResolvedPathRule],
    extra: &[ResolvedPathRule],
    resolved: &Path,
) -> Option<PathBuf> {
    chained_rules(base, extra)
        .filter(|entry| entry.access == PathAccess::Deny)
        .find_map(|entry| {
            (entry.resolved != resolved && entry.resolved.starts_with(resolved))
                .then(|| entry.resolved.clone())
        })
}

fn trusted_global_rw_overrides_product_ro<'a>(
    mut rules: impl Iterator<Item = &'a ResolvedPathRule>,
    target: &Path,
    ro_depth: usize,
) -> bool {
    rules.any(|entry| {
        entry.access == PathAccess::ReadWrite
            && entry.source == PathAccessRuleSource::TrustedGlobalConfig
            && entry.depth >= ro_depth
            && path_within(target, &entry.resolved)
    })
}

fn covered_protected_readonly_descendant_path(
    base: &[ResolvedPathRule],
    extra: &[ResolvedPathRule],
    resolved: &Path,
) -> Option<PathBuf> {
    let rules = chained_rules(base, extra);
    rules
        .clone()
        .filter(|entry| {
            entry.access == PathAccess::ReadOnly
                && entry.source == PathAccessRuleSource::ProductReadOnly
        })
        .find_map(|entry| {
            let covered = entry.resolved != resolved && entry.resolved.starts_with(resolved);
            if !covered {
                return None;
            }
            let explicitly_writable =
                trusted_global_rw_overrides_product_ro(rules.clone(), &entry.resolved, entry.depth);
            (!explicitly_writable).then(|| entry.resolved.clone())
        })
}

fn requires_built_in_product_review(
    base: &[ResolvedPathRule],
    extra: &[ResolvedPathRule],
    resolved: &Path,
    requested: PathAccess,
) -> bool {
    let rules = chained_rules(base, extra);
    let deepest_private_depth = rules
        .clone()
        .filter(|entry| {
            entry.access == PathAccess::Deny
                && entry.source == PathAccessRuleSource::ProductPrivate
                && path_within(resolved, &entry.resolved)
        })
        .map(|entry| entry.depth)
        .max();
    if let Some(private_depth) = deepest_private_depth {
        let deeper_product_ro = requested == PathAccess::ReadOnly
            && rules.clone().any(|entry| {
                entry.access == PathAccess::ReadOnly
                    && entry.source == PathAccessRuleSource::ProductReadOnly
                    && entry.depth > private_depth
                    && path_within(resolved, &entry.resolved)
            });
        if !deeper_product_ro {
            return true;
        }
    }

    if requested == PathAccess::ReadWrite {
        let deepest_product_ro_depth = rules
            .clone()
            .filter(|entry| {
                entry.access == PathAccess::ReadOnly
                    && entry.source == PathAccessRuleSource::ProductReadOnly
                    && path_within(resolved, &entry.resolved)
            })
            .map(|entry| entry.depth)
            .max();
        if let Some(ro_depth) = deepest_product_ro_depth {
            let writable_beats_ro =
                trusted_global_rw_overrides_product_ro(rules.clone(), resolved, ro_depth)
                    || rules.clone().any(|entry| {
                        entry.access == PathAccess::ReadWrite
                            && matches!(
                                entry.source,
                                PathAccessRuleSource::ProductConfig
                                    | PathAccessRuleSource::DurableMemory
                            )
                            && entry.depth > ro_depth
                            && path_within(resolved, &entry.resolved)
                    });
            if !writable_beats_ro {
                return true;
            }
        }
    }

    false
}

/// Extracts canonicalized `ProductPrivate` paths from a slice of path rules.
#[must_use]
pub fn extract_product_private_paths(rules: &[PathAccessRule]) -> Vec<PathBuf> {
    rules
        .iter()
        .filter(|rule| {
            rule.access() == PathAccess::Deny
                && rule.source() == PathAccessRuleSource::ProductPrivate
        })
        .map(|rule| resolve_rule_path(rule.path()))
        .collect()
}

/// Checks whether single-action `once_grants` cover `path` at `requested` access.
#[must_use]
pub fn once_grants_cover_path(
    once_grants: &[PathAccessRule],
    path: &Path,
    requested: PathAccess,
) -> bool {
    let resolved = resolve_rule_path(path);
    dynamic_rules_cover_path(once_grants.iter(), &resolved, requested)
}

/// Returns whether `path` hits or overlaps (as descendant OR ancestor) any
/// built-in Merry `ProductPrivate` path in unrestricted (`--sandbox off`) mode.
#[must_use]
pub fn is_protected_in_unrestricted_mode(product_private_paths: &[PathBuf], path: &Path) -> bool {
    let lexical = normalize_path_lexically(path);
    let resolved = resolve_path_with_existing_ancestor(&lexical);
    product_private_paths.iter().any(|private| {
        let resolved_private = resolve_rule_path(private);
        path_overlaps(&resolved, &resolved_private) || path_overlaps(&lexical, &resolved_private)
    })
}

/// Returns whether `path` is a protected Merry host path (or covers one as an
/// ancestor) and therefore must never be persisted to `workspace-permissions.json`.
#[must_use]
pub fn is_protected_host_path_for_persistence(
    path: &Path,
    access: PathAccess,
    policy: &HostPathPolicy,
) -> bool {
    let lexical = normalize_path_lexically(path);
    let resolved = resolve_path_with_existing_ancestor(&lexical);
    for denied in policy.denied() {
        let resolved_denied = resolve_rule_path(denied);
        if path_overlaps(&resolved, &resolved_denied) || path_overlaps(&lexical, &resolved_denied) {
            return true;
        }
    }
    if access == PathAccess::ReadWrite {
        for ro in policy.product_readonly() {
            let resolved_ro = resolve_rule_path(ro);
            if !(path_overlaps(&resolved, &resolved_ro) || path_overlaps(&lexical, &resolved_ro)) {
                continue;
            }
            let ro_depth = resolved_ro.components().count();
            let deeper_writable = policy
                .product_writable_config()
                .iter()
                .map(PathBuf::as_path)
                .chain(policy.durable_memory_root())
                .any(|writable| {
                    let resolved_writable = resolve_rule_path(writable);
                    path_within(&resolved, &resolved_writable)
                        && resolved_writable.components().count() > ro_depth
                });
            if !deeper_writable {
                return true;
            }
        }
    }
    false
}

/// Returns whether `path` (either lexically or after resolving symlinks on its
/// existing ancestor) targets `.git` metadata.
#[must_use]
pub fn is_git_metadata_path(path: &Path) -> bool {
    let lexical = normalize_path_lexically(path);
    let resolved = resolve_path_with_existing_ancestor(&lexical);
    is_git_metadata_path_parts(&lexical, &resolved)
}

fn is_git_metadata_path_parts(lexical: &Path, resolved: &Path) -> bool {
    has_git_component(lexical) || has_git_component(resolved)
}

fn has_git_component(path: &Path) -> bool {
    path.components()
        .any(|component| matches!(component, Component::Normal(name) if name == ".git"))
}

fn update_best_match(
    best_match: &mut Option<(usize, PathAccess, PathAccessRuleSource)>,
    depth: usize,
    access: PathAccess,
    source: PathAccessRuleSource,
) {
    let should_replace = match *best_match {
        None => true,
        Some((best_depth, best_access, best_source)) => {
            depth > best_depth
                || (depth == best_depth
                    && precedence(access, source) > precedence(best_access, best_source))
        }
    };
    if should_replace {
        *best_match = Some((depth, access, source));
    }
}

fn dynamic_rules_cover_path<'a>(
    rules: impl IntoIterator<Item = &'a PathAccessRule>,
    resolved: &Path,
    requested: PathAccess,
) -> bool {
    resolved_and_dynamic_rules_cover_path(std::iter::empty(), rules, resolved, requested)
}

fn resolved_and_dynamic_rules_cover_path<'a>(
    static_rules: impl IntoIterator<Item = &'a ResolvedPathRule>,
    dynamic_rules: impl IntoIterator<Item = &'a PathAccessRule>,
    resolved: &Path,
    requested: PathAccess,
) -> bool {
    let mut best_match: Option<(usize, PathAccess, PathAccessRuleSource)> = None;
    for entry in static_rules {
        if path_within(resolved, &entry.resolved) {
            update_best_match(&mut best_match, entry.depth, entry.access, entry.source);
        }
    }
    for rule in dynamic_rules {
        let rule_resolved = resolve_rule_path(rule.path());
        if path_within(resolved, &rule_resolved) {
            update_best_match(
                &mut best_match,
                rule_resolved.components().count(),
                rule.access(),
                rule.source(),
            );
        }
    }
    best_match.is_some_and(|(_, access, _)| access.covers(requested))
}

pub(crate) fn resolve_rule_path(path: &Path) -> PathBuf {
    resolve_path_with_existing_ancestor(&normalize_path_lexically(path))
}

fn precedence(access: PathAccess, source: PathAccessRuleSource) -> u8 {
    if access == PathAccess::Deny {
        return 4;
    }
    if access == PathAccess::ReadOnly && source == PathAccessRuleSource::TrustedGlobalConfig {
        return 3;
    }
    if access == PathAccess::ReadWrite {
        return 2;
    }
    1
}

fn path_within(target: &Path, root: &Path) -> bool {
    target == root || target.starts_with(root)
}

fn path_overlaps(left: &Path, right: &Path) -> bool {
    left == right || left.starts_with(right) || right.starts_with(left)
}

/// Canonicalizes `path`, or canonicalizes its deepest existing ancestor and
/// appends the remaining lexical components, simplifying Windows verbatim prefixes.
#[must_use]
pub fn resolve_path_with_existing_ancestor(path: &Path) -> PathBuf {
    let lexical = normalize_path_lexically(path);
    if let Ok(canonical) = fs::canonicalize(&lexical) {
        return merry_core::host_paths::simplify_verbatim_path(&canonical);
    }
    let mut suffix = Vec::new();
    let mut current = lexical.as_path();
    while let Some(parent) = current.parent() {
        if let Some(name) = current.file_name() {
            suffix.push(name.to_os_string());
        }
        if let Ok(canonical_parent) = fs::canonicalize(parent) {
            let mut resolved = merry_core::host_paths::simplify_verbatim_path(&canonical_parent);
            for part in suffix.into_iter().rev() {
                resolved.push(part);
            }
            return resolved;
        }
        current = parent;
    }
    lexical
}

/// Lexically normalizes `.` and `..` components without touching the filesystem.
#[must_use]
pub fn normalize_path_lexically(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    let is_absolute = path.is_absolute();
    for component in path.components() {
        match component {
            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
            Component::RootDir => normalized.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() && !is_absolute {
                    normalized.push("..");
                }
            }
            Component::Normal(part) => normalized.push(part),
        }
    }
    normalized
}

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