phora 0.6.0

A git-based artifact package manager and multiplexer for content-addressed file distribution
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
//! Destination confinement for composed transitive targets (TDEP-CONFINE-001).

use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};

use unicode_normalization::UnicodeNormalization;

use crate::config::Paths;
use crate::error::{Error, Result};
use crate::paths::{cache_root_for, state_root_for};
use crate::source::safe_component;

/// Named diagnostics owned by confinement; tests assert these exact phrases.
const ANCHOR_SYMLINK: &str = "anchor ancestor is a symlink";
const PROTECTED_PATH: &str = "protected path";

/// Paths a transitive dep must never write, even when they do not yet exist.
pub(super) struct ProtectedPathSet {
    cwd: PathBuf,
    members: Vec<PathBuf>,
}

impl ProtectedPathSet {
    pub(super) fn resolve(paths: &Paths, cwd: &Path) -> Result<Self> {
        let mut members = vec![
            cwd.join("phora.toml"),
            cwd.join("phora.local.toml"),
            cwd.join("phora.lock"),
            cwd.join("phora.local.lock"),
            cwd.join(".git"),
        ];
        members.push(state_root_for(paths.state.as_deref(), cwd)?.join("projects"));
        members.push(cache_root_for(paths.cache.as_deref(), cwd)?);
        Ok(Self {
            cwd: cwd.to_path_buf(),
            members: members
                .iter()
                .map(PathBuf::as_path)
                .map(normalize_lexical)
                .collect(),
        })
    }

    fn protects(&self, path: &Path) -> bool {
        let absolute = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.cwd.join(path)
        };
        let candidate = canonical_lexical(&absolute);
        self.members
            .iter()
            .any(|member| starts_with_components(&candidate, &canonical_lexical(member)))
    }
}

pub(super) fn confine_removal_destination(
    current_anchor: Option<&Path>,
    persisted_anchor: Option<&Path>,
    dst: &Path,
    composed: bool,
    protected: &ProtectedPathSet,
) -> Result<PathBuf> {
    let anchor = match (current_anchor, persisted_anchor) {
        (Some(current), _)
            if strip_prefix_folded(&normalize_lexical(dst), &normalize_lexical(current))
                .is_some() =>
        {
            current
        }
        (_, Some(persisted)) => persisted,
        (Some(current), None) => current,
        (None, None) if composed => {
            return Err(Error::Config(
                "confinement: composed target reached prune without a confine anchor; refusing an unconfined delete"
                    .to_string(),
            ));
        }
        (None, None) => return Ok(dst.to_path_buf()),
    };
    reject_if_symlink(anchor)?;
    let path = confine_path(anchor, dst, protected)?;
    if let Some(parent) = path.parent() {
        reject_symlink_ancestor(&normalize_lexical(anchor), parent)?;
    }
    Ok(path)
}

pub(super) fn within_anchor(anchor: &Path, path: &Path) -> bool {
    starts_with_components(&normalize_lexical(path), &normalize_lexical(anchor))
}

/// Returns the path deploy must write verbatim, or rejects any escape of `anchor`.
pub(super) fn confine_destination(
    anchor: &Path,
    dst: &Path,
    protected: &ProtectedPathSet,
) -> Result<PathBuf> {
    let path = confine_path(anchor, dst, protected)?;
    reject_symlink_ancestor(&normalize_lexical(anchor), &path)?;
    Ok(path)
}

/// Like [`confine_destination`] for a destination replaced or removed as one directory
/// entry and never written through, so the entry itself may already be a symlink.
pub(super) fn confine_entry_destination(
    anchor: &Path,
    dst: &Path,
    protected: &ProtectedPathSet,
) -> Result<PathBuf> {
    let path = confine_path(anchor, dst, protected)?;
    if let Some(parent) = path.parent() {
        reject_symlink_ancestor(&normalize_lexical(anchor), parent)?;
    }
    Ok(path)
}

fn confine_path(anchor: &Path, dst: &Path, protected: &ProtectedPathSet) -> Result<PathBuf> {
    let anchor_norm = normalize_lexical(anchor);
    let dst_norm = normalize_lexical(dst);

    if protected.protects(&dst_norm) {
        return Err(Error::Config(format!(
            "confinement: {PROTECTED_PATH} {} may not be written by a transitive dependency",
            dst.display()
        )));
    }

    let relative = strip_prefix_folded(&dst_norm, &anchor_norm).ok_or_else(|| {
        Error::Config(format!(
            "confinement: destination {} escapes its anchor {}",
            dst.display(),
            anchor.display()
        ))
    })?;
    for component in relative.components() {
        match component {
            Component::Normal(name) => {
                let name = name.to_string_lossy();
                safe_component(&name).map_err(|_| {
                    Error::Config(format!(
                        "confinement: destination component `{name}` of {} is not a safe filename",
                        dst.display()
                    ))
                })?;
            }
            _ => {
                return Err(Error::Config(format!(
                    "confinement: destination {} escapes its anchor {}",
                    dst.display(),
                    anchor.display()
                )));
            }
        }
    }

    Ok(dst_norm)
}

fn reject_symlink_ancestor(anchor: &Path, dst: &Path) -> Result<()> {
    let Some(tail) = strip_prefix_folded(dst, anchor) else {
        return Ok(());
    };
    let mut current = anchor.to_path_buf();
    for component in tail.components() {
        current.push(component);
        reject_if_symlink(&current)?;
    }
    Ok(())
}

fn reject_if_symlink(path: &Path) -> Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_symlink() => Err(Error::Config(format!(
            "confinement: {ANCHOR_SYMLINK}: {} is a symlink and a transitive write \
             must not follow it",
            path.display()
        ))),
        Ok(_) | Err(_) => Ok(()),
    }
}

/// The swap moves any existing `dst` entry aside, so only its ancestors are guarded.
/// Residual risk: a cross-process TOCTOU race and hardlink-to-directory canonicalization stay unguarded.
pub(super) fn reject_symlink_ancestor_at_write(anchor: &Path, dst: &Path) -> Result<()> {
    let dst = normalize_lexical(dst);
    match dst.parent() {
        Some(parent) => reject_symlink_ancestor(&normalize_lexical(anchor), parent),
        None => Ok(()),
    }
}

/// Collapses `.`/`..` without touching the filesystem, so confinement holds for paths that do not yet exist.
fn normalize_lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => match out.components().next_back() {
                Some(Component::Normal(_)) => {
                    out.pop();
                }
                Some(Component::RootDir | Component::Prefix(_)) => {}
                _ => out.push(".."),
            },
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Same file via different representations (e.g. `/var` -> `/private/var`) must
/// compare equal; non-canonicalizable or relative paths fall back to lexical.
fn canonical_lexical(path: &Path) -> PathBuf {
    let lexical = normalize_lexical(path);
    if !lexical.is_absolute() {
        return lexical;
    }
    let mut existing = lexical.as_path();
    let mut tail: Vec<&std::ffi::OsStr> = Vec::new();
    loop {
        if let Ok(canon) = std::fs::canonicalize(existing) {
            let mut out = canon;
            out.extend(tail.iter().rev());
            return out;
        }
        match existing.parent() {
            Some(parent) if parent != existing => {
                if let Some(name) = existing.file_name() {
                    tail.push(name);
                }
                existing = parent;
            }
            _ => return lexical,
        }
    }
}

/// Resolves ancestors physically without following the final directory entry.
pub(super) fn normalize_physical_entry(path: &Path) -> Result<PathBuf> {
    match (path.parent(), path.file_name()) {
        (Some(parent), Some(name)) => Ok(normalize_physical(parent)?.join(name)),
        _ => normalize_physical(path),
    }
}

/// Resolves a path to its physical identity without requiring the final path to exist.
pub(super) fn normalize_physical(path: &Path) -> Result<PathBuf> {
    if !path.is_absolute() {
        return Err(Error::Config(format!(
            "overlap check: physical path {} is not absolute",
            path.display()
        )));
    }
    let mut existing = path.to_path_buf();
    let mut tail: Vec<OsString> = Vec::new();
    loop {
        match std::fs::canonicalize(&existing) {
            Ok(mut physical) => {
                physical.extend(tail.iter().rev());
                return Ok(physical);
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => {
                return Err(Error::Config(format!(
                    "overlap check: resolve physical prefix {}: {error}",
                    existing.display()
                )));
            }
        }
        if std::fs::symlink_metadata(&existing).is_ok() {
            return Err(Error::Config(format!(
                "overlap check: existing path {} has no resolvable physical identity",
                existing.display()
            )));
        }
        match existing.components().next_back() {
            Some(Component::Normal(name)) => {
                tail.push(name.to_os_string());
                existing.pop();
            }
            Some(Component::CurDir) => {
                existing.pop();
            }
            Some(Component::ParentDir) => {
                return Err(Error::Config(format!(
                    "overlap check: unresolved parent traversal in {} cannot be normalized safely",
                    path.display()
                )));
            }
            Some(Component::RootDir | Component::Prefix(_)) | None => {
                return Err(Error::Config(format!(
                    "overlap check: no existing physical prefix for {}",
                    path.display()
                )));
            }
        }
    }
}

fn starts_with_components(path: &Path, prefix: &Path) -> bool {
    strip_prefix_folded(path, prefix).is_some()
}

/// NFC-normalizes, then applies simple Unicode lowercase (`to_lowercase`), not
/// full case-folding: this matches how APFS/NTFS collide names, so `ß`/`ss` and
/// final sigma `ς`/`σ` stay distinct rather than over-rejecting.
fn fold_key(component: &std::ffi::OsStr) -> String {
    component
        .to_string_lossy()
        .nfc()
        .collect::<String>()
        .to_lowercase()
}

pub(crate) fn fold_path(path: &Path) -> PathBuf {
    path.components().map(|c| fold_key(c.as_os_str())).collect()
}

fn strip_prefix_folded(path: &Path, prefix: &Path) -> Option<PathBuf> {
    let mut tail = path.components();
    for pc in prefix.components() {
        match tail.next() {
            Some(tc) if fold_key(tc.as_os_str()) == fold_key(pc.as_os_str()) => {}
            _ => return None,
        }
    }
    Some(tail.as_path().to_path_buf())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn protected(cwd: &Path) -> ProtectedPathSet {
        ProtectedPathSet::resolve(&Paths::default(), cwd).expect("resolve protected set")
    }

    #[cfg(unix)]
    #[test]
    fn removal_allows_leaf_links_but_rejects_linked_parents_and_protected_files() {
        let root = tempfile::tempdir().expect("root");
        let outside = tempfile::tempdir().expect("outside");
        let leaf = root.path().join("leaf");
        std::os::unix::fs::symlink(root.path().join("missing"), &leaf).expect("dangling leaf");
        let protected = protected(root.path());
        assert_eq!(
            confine_removal_destination(None, Some(root.path()), &leaf, false, &protected)
                .expect("unlinking the final entry is confined"),
            leaf
        );
        confine_destination(root.path(), &leaf, &protected)
            .expect_err("writes must still reject a final symlink");
        let parent = root.path().join("alias");
        std::os::unix::fs::symlink(outside.path(), &parent).expect("parent alias");
        confine_removal_destination(
            None,
            Some(root.path()),
            &parent.join("file"),
            false,
            &protected,
        )
        .expect_err("removal must not traverse a parent symlink");
        confine_removal_destination(
            None,
            Some(root.path()),
            &root.path().join("phora.toml"),
            false,
            &protected,
        )
        .expect_err("protected files remain protected");
    }

    #[test]
    fn relative_anchors_preserve_leading_parent_components() {
        let anchor = Path::new("../../.henia/source");
        let dst = anchor.join("skills/code/SKILL.md");
        let set = protected(Path::new("/home/u/project/phora/stage"));
        assert_eq!(
            confine_destination(anchor, &dst, &set).expect("relative anchor"),
            dst
        );
        assert_eq!(
            normalize_lexical(Path::new("../../../a/../b")),
            Path::new("../../../b")
        );
        assert_eq!(normalize_lexical(Path::new("/../../b")), Path::new("/b"));
    }

    #[test]
    fn confines_a_plain_descendant() {
        let anchor = Path::new("/home/u/.config");
        let dst = anchor.join("nvim/init.lua");
        let set = protected(Path::new("/home/u/proj"));
        let confined = confine_destination(anchor, &dst, &set).expect("descendant confines");
        assert_eq!(confined, dst, "joined_dst must equal confined_dst");
    }

    #[test]
    fn rejects_parent_dir_escape() {
        let anchor = Path::new("/home/u/.config");
        let dst = Path::new("/home/u/.config/../.ssh/authorized_keys");
        let set = protected(Path::new("/home/u/proj"));
        confine_destination(anchor, dst, &set).expect_err("a `..` escape must be rejected");
    }

    #[test]
    fn rejects_prefix_sibling_not_descendant() {
        let anchor = Path::new("/home/u/.config");
        let dst = Path::new("/home/u/.config-unsafe/x");
        let set = protected(Path::new("/home/u/proj"));
        confine_destination(anchor, dst, &set)
            .expect_err("a prefix sibling must fail a component-wise anchor check");
    }

    fn err_message(e: &Error) -> String {
        match e {
            Error::Config(m) => m.clone(),
            other => panic!("expected Error::Config from confinement, got {other:?}"),
        }
    }

    #[test]
    fn returned_dst_is_normalized_canonical_no_raw_dot_segments() {
        let anchor = Path::new("/home/u/.config");
        let composed = Path::new("/home/u/.config/./nvim/./lua/init.lua");
        let canonical = Path::new("/home/u/.config/nvim/lua/init.lua");
        let set = protected(Path::new("/home/u/proj"));

        let confined =
            confine_destination(anchor, composed, &set).expect("a `.`-laden descendant confines");
        assert_eq!(
            confined, canonical,
            "confinement must return the normalized canonical dst (deploy's single source of \
             truth); a raw `.`/`..` segment reaching fs::rename is a TOCTOU hole"
        );
        assert!(
            !confined
                .components()
                .any(|c| matches!(c, Component::CurDir | Component::ParentDir)),
            "no `.`/`..` component may survive into the dst deploy writes verbatim; got {}",
            confined.display()
        );
    }

    #[test]
    fn staging_base_is_derived_from_confined_dst_not_raw_target() {
        let anchor = Path::new("/home/u/.config");
        let raw = Path::new("/home/u/.config/nvim/./init.lua");
        let set = protected(Path::new("/home/u/proj"));

        let confined = confine_destination(anchor, raw, &set).expect("descendant confines");
        let staging_base = super::super::target_parent(&confined).join(".phora-stage");

        assert_eq!(
            staging_base,
            Path::new("/home/u/.config/nvim/.phora-stage"),
            "staging_base must hang off the confined canonical parent so the rename lands under \
             the anchor; deriving it from the raw target_path would reintroduce the `.` segment"
        );
        assert!(
            starts_with_components(&staging_base, &normalize_lexical(anchor)),
            "the confined-derived staging_base must itself be component-wise under the anchor; \
             got {}",
            staging_base.display()
        );
    }

    #[test]
    fn prefix_sibling_rejection_names_the_escape_and_anchor() {
        let anchor = Path::new("/home/u/.config");
        let dst = Path::new("/home/u/.config-unsafe/payload");
        let set = protected(Path::new("/home/u/proj"));

        let err = confine_destination(anchor, dst, &set)
            .expect_err("`.config-unsafe` must not pass a `.config` anchor");
        let msg = err_message(&err);
        assert!(
            msg.contains("escapes its anchor"),
            "a prefix-sibling escape must emit the named `escapes its anchor` diagnostic (proving \
             a component-wise strip_prefix, not string starts_with); got: {msg}"
        );
        assert!(
            msg.contains(".config-unsafe"),
            "the diagnostic must name the offending destination `.config-unsafe`; got: {msg}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn canonicalized_out_of_anchor_ancestor_is_rejected() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().expect("tmp");
        let root = tmp.path();
        let anchor = root.join("anchor");
        std::fs::create_dir_all(&anchor).expect("anchor");
        let escape = root.join("escape");
        std::fs::create_dir_all(&escape).expect("escape");

        symlink(&escape, anchor.join("real")).expect("plant escaping ancestor");
        let dst = anchor.join("real/payload");
        let set = protected(root);

        let err = confine_destination(&anchor, &dst, &set).expect_err(
            "an ancestor whose canonical target escapes the anchor must be rejected; lexical \
             normalization alone cannot see through it",
        );
        let msg = err_message(&err);
        assert!(
            msg.contains(ANCHOR_SYMLINK) || msg.contains("escapes its anchor"),
            "an out-of-anchor real ancestor must be rejected with a confinement diagnostic; \
             got: {msg}"
        );
        assert!(
            !escape.join("payload").exists(),
            "no write may reach the canonical out-of-anchor target {}",
            escape.join("payload").display()
        );
    }

    #[test]
    fn protected_member_caught_under_case_fold_identity() {
        let cwd = Path::new("/home/u/proj");
        let anchor = cwd; // target anchored at the project root
        let set = protected(cwd);
        let cased = cwd.join(".GIT/config");

        let err = confine_destination(anchor, &cased, &set).expect_err(
            "`.GIT` is the same path as the protected `.git` under case-fold identity and must \
             be rejected as a protected path",
        );
        let msg = err_message(&err);
        assert!(
            msg.contains(PROTECTED_PATH),
            "a case-variant of a protected member must emit `{PROTECTED_PATH}`; got: {msg}"
        );
    }

    #[test]
    fn anchor_match_is_nfc_normalized() {
        let anchor = Path::new("/home/u/caf\u{00e9}");
        let dst = Path::new("/home/u/cafe\u{0301}/init.lua");
        let set = protected(Path::new("/home/u/proj"));

        let confined = confine_destination(anchor, dst, &set).expect(
            "a dst differing from the anchor only by Unicode normalization form must confine to \
             the same anchor (NFC identity), not be treated as a prefix-sibling escape",
        );
        assert_eq!(
            confined
                .file_name()
                .map(|n| n.to_string_lossy().into_owned()),
            Some("init.lua".to_owned()),
            "the NFC-equal dst must keep its leaf file; got {}",
            confined.display()
        );
        let parent = super::super::target_parent(&confined);
        assert!(
            starts_with_components(&parent, &normalize_lexical(anchor)),
            "the confined parent must sit under the anchor by the impl's NFC/casefold component \
             identity, not be split off to a prefix-sibling; got parent {}",
            parent.display()
        );
    }

    #[cfg(unix)]
    #[test]
    fn nfc_variant_anchor_does_not_skip_symlink_no_follow_guard() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().expect("tmp");
        let root = tmp.path();
        let anchor_nfc = root.join("caf\u{00e9}");
        std::fs::create_dir_all(&anchor_nfc).expect("anchor");
        let escape = root.join("escape");
        std::fs::create_dir_all(&escape).expect("escape");
        symlink(&escape, anchor_nfc.join("real")).expect("plant anchor-side symlink ancestor");

        let dst = root.join("cafe\u{0301}").join("real/payload");
        let set = protected(root);

        let err = confine_destination(&anchor_nfc, &dst, &set).expect_err(
            "an anchor-side symlink ancestor reached via an NFC/NFD-variant anchor must still be \
             rejected; the no-follow guard must fold like the escape check, not raw-strip",
        );
        let msg = err_message(&err);
        assert!(
            msg.contains(ANCHOR_SYMLINK),
            "an NFC-variant anchor must NOT bypass the symlink no-follow guard; expected \
             `{ANCHOR_SYMLINK}`, got: {msg}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn protected_member_caught_across_symlinked_representation() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().expect("tmp");
        let root = tmp.path();
        let realroot = root.join("realroot");
        std::fs::create_dir_all(realroot.join("proj/.git")).expect("real proj/.git");
        let linkroot = root.join("linkroot");
        symlink(&realroot, &linkroot).expect("plant linkroot -> realroot");

        // Protected set is built under the `linkroot` representation.
        let set = protected(&linkroot.join("proj"));
        let anchor = linkroot.join("proj");
        // Candidate dst denotes the SAME protected `.git` via the `realroot` representation.
        let dst = realroot.join("proj/.git/hooks/x");

        let err = confine_destination(&anchor, &dst, &set).expect_err(
            "the candidate reaches the protected `.git` through the alternate (realroot) \
             representation; a purely-lexical compare misses it, canonicalization must catch it",
        );
        let msg = err_message(&err);
        assert!(
            msg.contains(PROTECTED_PATH),
            "a protected member reached via an alternate filesystem representation must emit \
             `{PROTECTED_PATH}`; got: {msg}"
        );
    }

    #[test]
    fn dep_cannot_overwrite_the_consumer_phora_manifest_via_take_rename() {
        let cwd = Path::new("/home/u/proj");
        let anchor = cwd; // a dep target composed at the consumer root
        let set = protected(cwd);
        // The dest a `take` rename `{ "anything" = "phora.toml" }` resolves to
        // after layout composition: the consumer's own manifest.
        let dst = cwd.join("phora.toml");

        let err = confine_destination(anchor, &dst, &set).expect_err(
            "a transitive dep must never overwrite the consumer's phora.toml, even via a `take` \
             rename whose dest resolves onto the manifest",
        );
        let msg = err_message(&err);
        assert!(
            msg.contains(PROTECTED_PATH),
            "the rejection must carry the `{PROTECTED_PATH}` diagnostic; got: {msg}"
        );
        assert!(
            msg.contains("phora.toml"),
            "the rejection must name the protected `phora.toml`; got: {msg}"
        );
    }

    #[test]
    fn prune_confinement_rejects_forged_out_of_anchor_record_path() {
        let anchor = Path::new("/home/u/.config");
        let forged = Path::new("/home/u/.config/../.ssh/authorized_keys");
        let set = protected(Path::new("/home/u/proj"));

        let err = confine_destination(anchor, forged, &set).expect_err(
            "prune confines each deletion: a forged record path escaping the anchor must be \
             REJECTED, never handed to remove_orphan_path",
        );
        let msg = err_message(&err);
        assert!(
            msg.contains("escapes its anchor"),
            "the prune-side confinement rejection must carry the `escapes its anchor` diagnostic \
             so prune logs a refusal instead of deleting; got: {msg}"
        );
    }

    // ---- CLIFF-UNIFOLD-005: non-ASCII case-collision pins + casefold divergence ----

    #[test]
    fn confine_fold_folds_latin_accented_case_variant_to_one_key() {
        assert_eq!(
            fold_path(Path::new("/x/\u{00c9}/init.lua")),
            fold_path(Path::new("/x/\u{00e9}/init.lua")),
            "confine folding must treat `\u{00c9}` and `\u{00e9}` as one key (NFC + full-Unicode \
             to_lowercase); the fold is not ASCII-only, so a case-only variant cannot smuggle a \
             second path past a fold-based confinement check"
        );
    }

    #[test]
    fn confine_fold_folds_cyrillic_case_variant_to_one_key() {
        assert_eq!(
            fold_path(Path::new("/x/\u{0401}/f")),
            fold_path(Path::new("/x/\u{0451}/f")),
            "confine folding must fold Cyrillic `\u{0401}`/`\u{0451}` (\u{0401}/\u{0451}) to one \
             key; folding covers non-ASCII case pairs, not just ASCII"
        );
    }

    #[test]
    fn confine_treats_cyrillic_case_variant_anchor_as_the_same_path() {
        let anchor = Path::new("/home/u/\u{0401}"); // Ё
        let dst = Path::new("/home/u/\u{0451}/init.lua"); // ё
        let set = protected(Path::new("/home/u/proj"));

        let confined = confine_destination(anchor, dst, &set).expect(
            "a dst differing from the anchor only by Cyrillic case (\u{0401} vs \u{0451}) must \
             confine as the SAME path under fold identity, not be rejected as a prefix-sibling \
             escape",
        );
        assert_eq!(
            confined
                .file_name()
                .map(|n| n.to_string_lossy().into_owned()),
            Some("init.lua".to_owned()),
            "the case-variant anchor must keep confining the descendant leaf; got {}",
            confined.display()
        );
    }

    #[test]
    fn confine_fold_keeps_eszett_and_ss_distinct_documented_limitation() {
        assert_ne!(
            fold_path(Path::new("/x/stra\u{00df}e")), // straße
            fold_path(Path::new("/x/strasse")),
            "documented UNIFOLD limitation: the fold is simple lowercase, NOT full Unicode \
             case-folding, so `stra\u{00df}e` and `strasse` stay DISTINCT keys — this matches \
             APFS/NTFS simple-fold collision; a switch to full case-folding would over-collide \
             them and must fail this guard"
        );
    }

    #[test]
    fn confine_fold_keeps_final_sigma_distinct_but_folds_capital_sigma() {
        assert_ne!(
            fold_path(Path::new("/x/\u{03c2}")), // ς final sigma
            fold_path(Path::new("/x/\u{03c3}")), // σ small sigma
            "documented UNIFOLD limitation: final sigma `\u{03c2}` stays DISTINCT from `\u{03c3}` \
             under simple lowercase; only full case-folding merges them"
        );
        assert_eq!(
            fold_path(Path::new("/x/\u{03a3}")), // Σ capital sigma
            fold_path(Path::new("/x/\u{03c3}")), // σ small sigma
            "the fold IS full-Unicode for ordinary case pairs: capital `\u{03a3}` still lowercases \
             to `\u{03c3}`; only the final-sigma special case diverges from full folding"
        );
    }

    #[cfg(unix)]
    #[test]
    fn entry_destination_admits_a_symlink_leaf_but_not_a_symlink_ancestor() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().expect("tmp");
        let root = tmp.path();
        let anchor = root.join("anchor");
        let escape = root.join("escape");
        std::fs::create_dir_all(anchor.join("skills")).expect("anchor");
        std::fs::create_dir_all(&escape).expect("escape");
        symlink(escape.join("SKILL.md"), anchor.join("skills/SKILL.md")).expect("leaf link");
        symlink(&escape, anchor.join("linked")).expect("ancestor link");
        let set = protected(root);

        confine_entry_destination(&anchor, &anchor.join("skills/SKILL.md"), &set)
            .expect("a symlink leaf is replaced or removed as an entry, never followed");
        let err = confine_entry_destination(&anchor, &anchor.join("linked/SKILL.md"), &set)
            .expect_err("a symlink ancestor would be followed");
        assert!(err_message(&err).contains(ANCHOR_SYMLINK));
        confine_destination(&anchor, &anchor.join("skills/SKILL.md"), &set)
            .expect_err("a written-through destination still rejects a symlink leaf");
    }
}