doctrine 0.34.0

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! Shared filesystem primitives — the path-containment chokepoint and the
//! accountable, atomic create operations used by both the scaffold engine
//! (`entity.rs`) and the runtime-state writer (`state.rs`, slice-004 D3).
//!
//! The split between those modules is of *contracts* (scaffold-once vs
//! mutate-in-place), not of IO: both reach disk through the same safe-join and
//! create-new primitives, so path-containment (H1) and create-new semantics
//! are implemented exactly once.

use std::fs::{self, File, OpenOptions};
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};

use anyhow::{Context, bail};

/// Join a descriptor `rel` path under `tree_root`, rejecting absolute paths
/// and any `..` that would escape the tree (H1). The single chokepoint
/// through which a descriptor path reaches the filesystem.
pub(crate) fn safe_join(tree_root: &Path, rel: &Path) -> anyhow::Result<PathBuf> {
    if rel.is_absolute() {
        bail!(
            "Artifact path {} must be relative to the entity tree",
            rel.display()
        );
    }
    if rel.components().any(|c| c == Component::ParentDir) {
        bail!(
            "Artifact path {} must not escape the entity tree",
            rel.display()
        );
    }
    Ok(tree_root.join(rel))
}

/// Create a file, failing atomically if it already exists. `create_new(true)`
/// collapses the existence check and creation into one syscall — no TOCTOU
/// window (slice-004 D4 / finding 1). The caller decides what `AlreadyExists`
/// means: a refusal (the engine) or skip-if-present (the state writer).
pub(crate) fn create_new_file(path: &Path) -> std::io::Result<File> {
    OpenOptions::new().write(true).create_new(true).open(path)
}

/// Write `bytes` to `path` atomically: write a sibling temp file in the *same
/// directory*, then `rename` it over the target. The rename is atomic on a
/// single filesystem, so a concurrent reader sees either the old file or the
/// fully-written new one — never a torn write (slice-007 M6). The temp sits
/// beside the target (not `$TMPDIR`) so the rename never crosses a mount.
/// The pid disambiguates distinct processes; a process-global counter disambiguates
/// concurrent same-process writers (the map-server's axum/tokio tasks), so neither
/// renames a temp the other already consumed (SL-113 D4). Last rename wins.
pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> anyhow::Result<()> {
    static TEMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let dir = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .ok_or_else(|| anyhow::anyhow!("path has no parent dir: {}", path.display()))?;
    let name = path
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("path has no file name: {}", path.display()))?;
    let seq = TEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let tmp = dir.join(format!(
        ".{}.{}.{}.tmp",
        name.to_string_lossy(),
        std::process::id(),
        seq
    ));
    #[expect(
        clippy::disallowed_methods,
        reason = "the seam itself — write_atomic's internal temp write"
    )]
    fs::write(&tmp, bytes).with_context(|| format!("Failed to write temp {}", tmp.display()))?;
    fs::rename(&tmp, path)
        .with_context(|| format!("Failed to rename {} -> {}", tmp.display(), path.display()))
}

/// Whether a *real* directory sits at `path` — `symlink_metadata` does not
/// follow links, so a symlink (even one pointing at a directory) reports
/// `false`. Used to tell a pre-existing/concurrently-created dir apart from a
/// file or symlink squatting a path component during component-wise creation.
pub(crate) fn is_real_dir(path: &Path) -> bool {
    matches!(fs::symlink_metadata(path), Ok(m) if m.is_dir())
}

/// Ensure a symlink at `link` points at `target`: create it if absent, replace
/// it if it is a symlink to somewhere else, leave it if already correct, and
/// **error** if a real file or directory squats the path (finding 10). The
/// convenience link is kept honest but is never authority — callers resolve by
/// id regardless of what this link says.
pub(crate) fn set_symlink(link: &Path, target: &Path) -> anyhow::Result<()> {
    match fs::symlink_metadata(link) {
        Ok(m) if m.file_type().is_symlink() => {
            let current = fs::read_link(link)
                .with_context(|| format!("Failed to read symlink {}", link.display()))?;
            if current != target {
                fs::remove_file(link)
                    .with_context(|| format!("Failed to replace symlink {}", link.display()))?;
                symlink(target, link)?;
            }
            Ok(())
        }
        Ok(_) => bail!(
            "Refusing to replace non-symlink {} with a symlink",
            link.display()
        ),
        Err(e) if e.kind() == ErrorKind::NotFound => symlink(target, link),
        Err(e) => Err(e).with_context(|| format!("Failed to stat {}", link.display())),
    }
}

fn symlink(target: &Path, link: &Path) -> anyhow::Result<()> {
    std::os::unix::fs::symlink(target, link)
        .with_context(|| format!("Failed to create symlink {}", link.display()))
}

/// Recursively copy a directory tree from `src` to `dst`. `dst` will be
/// created if it does not exist. Symlinks are followed — the target file is
/// copied, not the symlink itself.
pub(crate) fn copy_dir_all(src: &Path, dst: &Path) -> anyhow::Result<()> {
    fs::create_dir_all(dst).with_context(|| format!("copy_dir_all: create {}", dst.display()))?;
    for entry in
        fs::read_dir(src).with_context(|| format!("copy_dir_all: read {}", src.display()))?
    {
        let entry = entry?;
        let child = entry.path();
        let dest = dst.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir_all(&child, &dest)?;
        } else {
            fs::copy(&child, &dest)?;
        }
    }
    Ok(())
}

/// The disposition of one [`copy_selected`] candidate.
#[derive(Debug)]
pub(crate) enum CopyOutcome {
    /// Copied into the fork.
    Copied,
    /// Deliberately not copied (symlink escapes the tree / targets the withheld
    /// tier / is not a regular file); the reason is for a skip+warn line.
    Skipped(String),
}

/// Copy one repo-relative file from a **canonical** `source_root` into a
/// **canonical** `fork_root`, refusing anything whose real location escapes the
/// source tree (SL-029 §3 copy safety, B5 — `safe_join` is insufficient because
/// a symlink *component* can escape even with no `..`).
///
/// Both roots MUST already be canonical (the caller canonicalizes once). The
/// source path is resolved with [`fs::canonicalize`], so a symlink component or a
/// symlink pointing out-of-tree is caught; for a symlink whose target stays
/// in-tree, `target_withheld` decides whether that target lands in the
/// coordination tier (passed in to keep `fsutil` free of any git/worktree
/// dependency — no module cycle). The destination parent is canonicalized after
/// creation so a symlink component cannot redirect the write out of the fork;
/// the final path is then built by join (the dest leaf does not exist yet, R-c).
pub(crate) fn copy_selected(
    source_root: &Path,
    fork_root: &Path,
    rel: &Path,
    target_withheld: &dyn Fn(&Path) -> bool,
) -> anyhow::Result<CopyOutcome> {
    let src = source_root.join(rel);
    let meta = fs::symlink_metadata(&src).with_context(|| format!("stat {}", src.display()))?;

    let real = fs::canonicalize(&src).with_context(|| format!("canonicalize {}", src.display()))?;
    if !real.starts_with(source_root) {
        return Ok(CopyOutcome::Skipped(format!(
            "{} resolves outside the source tree",
            rel.display()
        )));
    }
    if meta.file_type().is_symlink() {
        let real_rel = real
            .strip_prefix(source_root)
            .map_err(|e| anyhow::anyhow!("strip source prefix: {e}"))?;
        if target_withheld(real_rel) {
            return Ok(CopyOutcome::Skipped(format!(
                "{} targets the withheld tier",
                rel.display()
            )));
        }
    }
    if !real.is_file() {
        return Ok(CopyOutcome::Skipped(format!(
            "{} is not a regular file",
            rel.display()
        )));
    }

    let dest = fork_root.join(rel);
    let parent = dest
        .parent()
        .ok_or_else(|| anyhow::anyhow!("dest {} has no parent", dest.display()))?;
    fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
    let parent_canon =
        fs::canonicalize(parent).with_context(|| format!("canonicalize {}", parent.display()))?;
    if !parent_canon.starts_with(fork_root) {
        return Ok(CopyOutcome::Skipped(format!(
            "{} destination escapes the fork",
            rel.display()
        )));
    }
    let name = dest
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("dest {} has no file name", dest.display()))?;
    let final_dest = parent_canon.join(name);
    fs::copy(&real, &final_dest)
        .with_context(|| format!("copy {} -> {}", real.display(), final_dest.display()))?;
    Ok(CopyOutcome::Copied)
}

// ---------------------------------------------------------------------------
// Component-wise parent creation (extracted from entity.rs, SL-231 PHASE-02)
// ---------------------------------------------------------------------------

/// Create each missing component of `rel`'s parent under `tree_root`, pushing
/// only the ones *this call* creates onto `created_dirs`. `create_dir_all`
/// cannot report which components it made, so the walk is component-wise
/// `create_dir` (finding 2). An `AlreadyExists` that is a real dir is a
/// pre-existing/concurrent parent (skip, do not track); anything else (a file
/// or symlink squatting the path) is an error.
pub(crate) fn ensure_parent_dirs(
    tree_root: &Path,
    rel: &Path,
    created_dirs: &mut Vec<PathBuf>,
) -> anyhow::Result<()> {
    let Some(parent) = rel.parent() else {
        return Ok(());
    };
    if parent.as_os_str().is_empty() {
        return Ok(());
    }
    let mut cur = tree_root.to_path_buf();
    for comp in parent.components() {
        cur.push(comp);
        if create_dir_component(&cur)? {
            created_dirs.push(cur.clone());
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// No-clobber publication primitive (SL-231 PHASE-02, design §3.2)
// ---------------------------------------------------------------------------

/// Reserved publication-temp filename prefix. Names starting with this prefix
/// are in-progress publication artifacts that corpus loaders must skip (EX-3).
pub(crate) const PUBLICATION_TEMP_PREFIX: &str = ".tmp.";

/// The outcome of a [`publish_complete`] call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PublishOutcome {
    /// The complete content was published at the destination.
    Created,
    /// The destination already exists — content was NOT overwritten.
    AlreadyExists,
}

/// Write complete bytes to a reserved sibling temp, publish only through a
/// no-clobber `hard_link`, then remove the temp. The destination is NEVER
/// opened for write.
///
/// The guarantee: partial authoritative records are prevented on macOS and
/// Linux; no-clobber concurrency is provided; encountered parent squatters
/// (symlink or non-directory) are refused. A crash before the link may leave
/// an ignored temp; a crash after the link may leave the inode under both
/// names. This does NOT protect against a malicious local actor continuously
/// swapping directory components.
pub(crate) fn publish_complete(
    destination: &Path,
    complete_bytes: &[u8],
) -> anyhow::Result<PublishOutcome> {
    static PUB_TEMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let dir = destination
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .ok_or_else(|| {
            anyhow::anyhow!("destination has no parent dir: {}", destination.display())
        })?;
    let dest_name = destination.file_name().ok_or_else(|| {
        anyhow::anyhow!("destination has no file name: {}", destination.display())
    })?;

    // Step 1: ensure parent components exist, refusing squatters.
    ensure_dir_components(dir)?;

    let seq = PUB_TEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let tmp_name = format!(
        "{}{}.{}.{}.pub",
        PUBLICATION_TEMP_PREFIX,
        dest_name.to_string_lossy(),
        std::process::id(),
        seq
    );
    let tmp = dir.join(&tmp_name);

    // Step 2: write and close the complete bytes at the reserved sibling temp.
    {
        let mut f = create_new_file(&tmp)
            .with_context(|| format!("Failed to create publication temp {}", tmp.display()))?;
        if let Err(e) = std::io::Write::write_all(&mut f, complete_bytes) {
            drop(f);
            drop(fs::remove_file(&tmp));
            return Err(e)
                .with_context(|| format!("Failed to write publication temp {}", tmp.display()));
        }
        // `f` is dropped here — closed before publication.
    }

    // Step 3: publish the complete inode through a no-clobber hard link.
    let outcome = match std::fs::hard_link(&tmp, destination) {
        Ok(()) => PublishOutcome::Created,
        Err(e) if e.kind() == ErrorKind::AlreadyExists => PublishOutcome::AlreadyExists,
        Err(e) => {
            // Clean the temp before surfacing the error.
            drop(fs::remove_file(&tmp));
            return Err(e).with_context(|| {
                format!(
                    "Failed to hard_link {} -> {}",
                    tmp.display(),
                    destination.display()
                )
            });
        }
    };

    // Step 4: remove the temporary name after publication or collision.
    // The destination inode retains the link (Created) or already existed
    // (AlreadyExists); in either case the temp name is no longer needed.
    drop(fs::remove_file(&tmp));

    Ok(outcome)
}

/// Try to create a single directory component. Returns `Ok(true)` if this
/// call created it, `Ok(false)` if it already existed as a real directory.
/// Errors on a symlink or non-directory squatter — the shared per-component
/// step for both [`ensure_parent_dirs`] (which records created dirs for
/// rollback) and `ensure_dir_components` (which does not).
fn create_dir_component(path: &Path) -> anyhow::Result<bool> {
    match fs::create_dir(path) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == ErrorKind::AlreadyExists => {
            if !is_real_dir(path) {
                bail!(
                    "Failed to create {}: a non-directory squats that path",
                    path.display()
                );
            }
            Ok(false)
        }
        Err(e) => Err(e).with_context(|| format!("Failed to create {}", path.display())),
    }
}

/// Ensure every component of `path` exists as a real directory, creating
/// missing ones component-wise. Refuses a symlink or non-directory squatter
/// to match the contract of [`ensure_parent_dirs`].
fn ensure_dir_components(path: &Path) -> anyhow::Result<()> {
    let mut cur = PathBuf::new();
    for comp in path.components() {
        cur.push(comp);
        create_dir_component(&cur)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- safe_join (H1 path containment) ---

    #[test]
    fn safe_join_accepts_a_tree_relative_path() {
        let joined = safe_join(Path::new("/tree"), Path::new("003/x.toml")).unwrap();
        assert_eq!(joined, Path::new("/tree/003/x.toml"));
    }

    #[test]
    fn safe_join_rejects_absolute_paths() {
        let err = safe_join(Path::new("/tree"), Path::new("/etc/passwd")).unwrap_err();
        assert!(err.to_string().contains("must be relative"));
    }

    #[test]
    fn safe_join_rejects_parent_escape() {
        let err = safe_join(Path::new("/tree"), Path::new("../../etc/passwd")).unwrap_err();
        assert!(err.to_string().contains("must not escape"));
    }

    // --- create_new_file (atomic clobber refusal) ---

    #[test]
    fn create_new_file_refuses_an_existing_target() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x");
        assert!(create_new_file(&path).is_ok());
        let err = create_new_file(&path).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
    }

    // --- write_atomic (temp+rename swap) ---

    #[test]
    fn write_atomic_creates_then_overwrites_leaving_no_temp() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.toml");

        write_atomic(&path, b"v1").unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), "v1");

        write_atomic(&path, b"v2").unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), "v2");

        // the swap leaves only the target — no stray `.tmp` sibling.
        let names: Vec<String> = fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["x.toml"]);
    }

    #[test]
    fn write_atomic_concurrent_writers_same_path_leave_no_torn_temp() {
        use std::thread;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("x.toml");

        // Two threads hammer the SAME path. Pre-fix both compute the identical
        // temp name `.x.toml.{pid}.tmp`, so one thread's rename races the other's
        // temp: the loser renames a temp the winner already consumed → ENOENT.
        // Loop to make the collision near-certain, not schedule-dependent (R1).
        const ITERS: usize = 200;
        thread::scope(|s| {
            let a = s.spawn(|| {
                for _ in 0..ITERS {
                    write_atomic(&path, b"aaaa").unwrap();
                }
            });
            let b = s.spawn(|| {
                for _ in 0..ITERS {
                    write_atomic(&path, b"bbbb").unwrap();
                }
            });
            a.join().unwrap();
            b.join().unwrap();
        });

        // the swap leaves only the target — no stray `.tmp` siblings.
        let names: Vec<String> = fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["x.toml"], "no stray temps, only the target");
        // content is one of the two complete inputs — never a torn write.
        let got = fs::read_to_string(&path).unwrap();
        assert!(
            got == "aaaa" || got == "bbbb",
            "content is a complete write, got {got:?}"
        );
    }

    // --- is_real_dir (squat detection) ---

    #[test]
    fn is_real_dir_distinguishes_dirs_files_and_symlinks() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("d");
        fs::create_dir(&real).unwrap();
        let file = dir.path().join("f");
        fs::write(&file, "x").unwrap();
        let link = dir.path().join("l");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        assert!(is_real_dir(&real));
        assert!(!is_real_dir(&file));
        // a symlink to a dir is NOT a real dir — it must not be silently traversed
        assert!(!is_real_dir(&link));
        assert!(!is_real_dir(&dir.path().join("absent")));
    }

    // --- set_symlink (verified convenience-link refresh) ---

    #[test]
    fn set_symlink_creates_replaces_and_keeps() {
        let dir = tempfile::tempdir().unwrap();
        let link = dir.path().join("phases");

        // absent → created
        set_symlink(&link, Path::new("../target-a")).unwrap();
        assert_eq!(fs::read_link(&link).unwrap(), Path::new("../target-a"));

        // wrong target → replaced
        set_symlink(&link, Path::new("../target-b")).unwrap();
        assert_eq!(fs::read_link(&link).unwrap(), Path::new("../target-b"));

        // already correct → idempotent no-op
        set_symlink(&link, Path::new("../target-b")).unwrap();
        assert_eq!(fs::read_link(&link).unwrap(), Path::new("../target-b"));
    }

    #[test]
    fn set_symlink_errors_on_a_real_file_squatting_the_path() {
        let dir = tempfile::tempdir().unwrap();
        let squat = dir.path().join("phases");
        fs::write(&squat, "not a symlink").unwrap();

        let err = set_symlink(&squat, Path::new("../target")).unwrap_err();
        assert!(err.to_string().contains("Refusing to replace non-symlink"));
        // untouched
        assert_eq!(fs::read_to_string(&squat).unwrap(), "not a symlink");
    }

    // --- copy_selected (SL-029 B5 copy safety) ---

    fn canon_roots() -> (tempfile::TempDir, tempfile::TempDir, PathBuf, PathBuf) {
        let src = tempfile::tempdir().unwrap();
        let fork = tempfile::tempdir().unwrap();
        let src_canon = fs::canonicalize(src.path()).unwrap();
        let fork_canon = fs::canonicalize(fork.path()).unwrap();
        (src, fork, src_canon, fork_canon)
    }

    #[test]
    fn copy_selected_copies_a_plain_nested_file() {
        let (src, _fork, src_canon, fork_canon) = canon_roots();
        let f = src.path().join("nested/data.txt");
        fs::create_dir_all(f.parent().unwrap()).unwrap();
        fs::write(&f, "hello").unwrap();

        let never = |_p: &Path| false;
        let out = copy_selected(
            &src_canon,
            &fork_canon,
            Path::new("nested/data.txt"),
            &never,
        )
        .unwrap();
        assert!(matches!(out, CopyOutcome::Copied));
        assert_eq!(
            fs::read_to_string(fork_canon.join("nested/data.txt")).unwrap(),
            "hello"
        );
    }

    #[test]
    fn copy_selected_refuses_an_out_of_tree_symlink() {
        let (src, _fork, src_canon, fork_canon) = canon_roots();
        let outside = tempfile::tempdir().unwrap();
        let secret = outside.path().join("secret");
        fs::write(&secret, "s").unwrap();
        std::os::unix::fs::symlink(&secret, src.path().join("link")).unwrap();

        let never = |_p: &Path| false;
        let out = copy_selected(&src_canon, &fork_canon, Path::new("link"), &never).unwrap();
        assert!(matches!(out, CopyOutcome::Skipped(_)));
        assert!(!fork_canon.join("link").exists());
    }

    #[test]
    fn copy_selected_refuses_a_symlink_into_the_withheld_tier() {
        let (src, _fork, src_canon, fork_canon) = canon_roots();
        let statefile = src.path().join(".doctrine/state/boot.md");
        fs::create_dir_all(statefile.parent().unwrap()).unwrap();
        fs::write(&statefile, "boot").unwrap();
        std::os::unix::fs::symlink(&statefile, src.path().join("link")).unwrap();

        let withheld = |p: &Path| p.starts_with(".doctrine/state");
        let out = copy_selected(&src_canon, &fork_canon, Path::new("link"), &withheld).unwrap();
        assert!(matches!(out, CopyOutcome::Skipped(_)));
        assert!(!fork_canon.join("link").exists());
    }

    #[test]
    fn copy_dir_all_copies_a_directory_tree() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        let dst = tmp.path().join("dst");

        fs::create_dir_all(src.join("sub")).unwrap();
        fs::write(src.join("a.txt"), "hello").unwrap();
        fs::write(src.join("sub").join("b.txt"), "world").unwrap();

        copy_dir_all(&src, &dst).unwrap();
        assert!(dst.join("a.txt").is_file(), "top-level file copied");
        assert!(
            dst.join("sub").join("b.txt").is_file(),
            "nested file copied"
        );
        assert_eq!(fs::read_to_string(dst.join("a.txt")).unwrap(), "hello");
        assert_eq!(
            fs::read_to_string(dst.join("sub").join("b.txt")).unwrap(),
            "world"
        );
    }

    // --- ensure_parent_dirs (component-wise safe parent walk) ---

    #[test]
    fn ensure_parent_dirs_creates_missing_components_and_tracks_them() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("tree");
        fs::create_dir(&root).unwrap(); // tree_root must exist (caller's contract)
        let mut created: Vec<PathBuf> = Vec::new();

        // rel includes the artifact leaf; only parent components are created.
        ensure_parent_dirs(&root, Path::new("a/b/c/file.toml"), &mut created).unwrap();

        assert!(root.join("a").is_dir());
        assert!(root.join("a/b").is_dir());
        assert!(root.join("a/b/c").is_dir());
        assert!(
            !root.join("a/b/c/file.toml").exists(),
            "artifact itself not created"
        );
        assert_eq!(created.len(), 3);
        assert!(created.contains(&root.join("a")));
        assert!(created.contains(&root.join("a/b")));
        assert!(created.contains(&root.join("a/b/c")));
    }

    #[test]
    fn ensure_parent_dirs_noop_when_all_dirs_exist() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("tree");
        fs::create_dir(&root).unwrap();
        fs::create_dir_all(root.join("a/b/c")).unwrap();
        let mut created: Vec<PathBuf> = Vec::new();

        ensure_parent_dirs(&root, Path::new("a/b/c/file.toml"), &mut created).unwrap();

        assert!(created.is_empty(), "no dirs created when all exist");
    }

    #[test]
    fn parent_creation_refuses_symlink_squatter() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("tree");
        fs::create_dir(&root).unwrap();
        // `a` is a symlink (pointing somewhere), not a real directory.
        std::os::unix::fs::symlink("/somewhere", root.join("a")).unwrap();
        let mut created: Vec<PathBuf> = Vec::new();

        let err = ensure_parent_dirs(&root, Path::new("a/b/file.toml"), &mut created).unwrap_err();
        assert!(err.to_string().contains("non-directory squats"));
    }

    #[test]
    fn parent_creation_refuses_file_squatter() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("tree");
        fs::create_dir(&root).unwrap();
        // `a` is a regular file, not a directory.
        fs::write(root.join("a"), "block").unwrap();
        let mut created: Vec<PathBuf> = Vec::new();

        let err = ensure_parent_dirs(&root, Path::new("a/b/file.toml"), &mut created).unwrap_err();
        assert!(err.to_string().contains("non-directory squats"));
    }

    // --- publish_complete (no-clobber hard-link publication) ---

    #[test]
    fn publish_complete_new() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("sub").join("record.toml");
        let body = b"uid = \"x\"\n";

        let outcome = publish_complete(&dest, body).unwrap();
        assert_eq!(outcome, PublishOutcome::Created);
        assert_eq!(
            fs::read_to_string(&dest).unwrap(),
            std::str::from_utf8(body).unwrap()
        );
        // No temp left behind.
        let siblings: Vec<String> = fs::read_dir(dest.parent().unwrap())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(siblings, vec!["record.toml"]);
    }

    #[test]
    fn publication_never_opens_destination_for_write() {
        // The implementation proves this structurally: publish_complete never
        // calls File::create or File::options().write(true).open() on the
        // destination. It writes to a temp sibling and publishes through
        // std::fs::hard_link — an atomic directory-entry operation that never
        // opens the existing inode. This test exercises collision to
        // demonstrate the content-preserving guarantee.
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("sub");
        fs::create_dir(&sub).unwrap();
        let dest = sub.join("record.toml");
        let body = b"uid = \"original\"\n";

        // First write creates the file.
        let outcome = publish_complete(&dest, body).unwrap();
        assert_eq!(outcome, PublishOutcome::Created);

        // Record inode after creation.
        let meta1 = fs::symlink_metadata(&dest).unwrap();
        let ino1 = {
            use std::os::unix::fs::MetadataExt;
            meta1.ino()
        };

        // Collision — must not open the destination for write.
        let outcome2 = publish_complete(&dest, b"uid = \"different\"\n").unwrap();
        assert_eq!(outcome2, PublishOutcome::AlreadyExists);

        // Content unchanged.
        assert_eq!(
            fs::read_to_string(&dest).unwrap(),
            std::str::from_utf8(body).unwrap()
        );
        // Inode unchanged — hard_link on collision doesn't touch it.
        let meta2 = fs::symlink_metadata(&dest).unwrap();
        {
            use std::os::unix::fs::MetadataExt;
            assert_eq!(meta2.ino(), ino1, "inode must not change");
        }
    }

    #[test]
    fn publication_cleans_temp_after_collision() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("sub");
        fs::create_dir(&sub).unwrap();
        let dest = sub.join("record.toml");
        let body = b"uid = \"x\"\n";

        // Create the destination first.
        let outcome = publish_complete(&dest, body).unwrap();
        assert_eq!(outcome, PublishOutcome::Created);

        // Collision.
        let outcome2 = publish_complete(&dest, b"uid = \"y\"\n").unwrap();
        assert_eq!(outcome2, PublishOutcome::AlreadyExists);
        // Content unchanged.
        assert_eq!(
            fs::read_to_string(&dest).unwrap(),
            std::str::from_utf8(body).unwrap()
        );

        // No stray temp.
        let siblings: Vec<String> = fs::read_dir(&sub)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(siblings, vec!["record.toml"]);
    }

    #[test]
    fn publish_complete_refuses_parent_squatter() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // Place a file where a directory component is expected.
        fs::write(root.join("sub"), "block").unwrap();
        let dest = root.join("sub").join("record.toml");

        let err = publish_complete(&dest, b"uid = \"x\"\n").unwrap_err();
        assert!(err.to_string().contains("non-directory squats"));
    }
}