jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! Stage complete bytes before replacing outputs. A set has one commit per
//! file; errors name any files already committed. No rollback or delete-old
//! fallback is attempted. Native host filesystems only.

use std::io;
use std::path::{Path, PathBuf};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Phase {
    Write,
    Flush,
    Sync,
    Validate,
    Commit,
    SyncParent,
}

trait Backend {
    type Staged;
    fn stage(&mut self, path: &Path) -> io::Result<Self::Staged>;
    /// Whether `a` and `b` were staged in one directory, as the filesystem
    /// resolved each parent (symlinks, `..`, the output root), not as spelled.
    fn same_parent(&mut self, a: &Self::Staged, b: &Self::Staged) -> io::Result<bool>;
    /// Record `staged`'s name among the names claimed in `holder`'s directory
    /// (one parent); `true` when the volume already holds an equivalent name.
    fn claim_name(&mut self, holder: &Self::Staged, staged: &Self::Staged) -> io::Result<bool>;
    fn step(&mut self, staged: &mut Self::Staged, phase: Phase, bytes: &[u8]) -> io::Result<()>;
    fn cleanup(&mut self, staged: &mut Self::Staged) -> io::Result<()>;
}

/// A successful publication, including any staging cleanup warnings.
#[derive(Debug, Default)]
pub struct PublishReport {
    /// Cleanup failures do not undo installed output.
    pub warnings: Vec<String>,
}

/// A publication failure, including output that has already become visible.
#[derive(Debug)]
pub struct PublishError {
    /// Files committed before the error. An empty list means nothing published.
    pub committed: Vec<PathBuf>,
    /// True when a committed file's parent could not acknowledge durability.
    pub durability_uncertain: bool,
    /// The operation's I/O error.
    pub source: io::Error,
    /// Staging cleanup failures, separate from the original publication error.
    pub warnings: Vec<String>,
}

impl std::fmt::Display for PublishError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}; committed outputs: {:?}{}",
            self.source,
            self.committed,
            if self.durability_uncertain {
                "; durability uncertain"
            } else {
                ""
            }
        )
    }
}
impl std::error::Error for PublishError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

fn finish(
    result: Result<(), PublishError>,
    warnings: Vec<String>,
) -> Result<PublishReport, PublishError> {
    match result {
        Ok(()) => Ok(PublishReport { warnings }),
        Err(mut error) => {
            error.warnings = warnings;
            Err(error)
        }
    }
}

fn transaction<B: Backend>(
    backend: &mut B,
    files: &[(PathBuf, &[u8])],
) -> Result<PublishReport, PublishError> {
    let mut staged: Vec<(PathBuf, B::Staged)> = Vec::with_capacity(files.len());
    let mut committed = Vec::new();
    let failure = |source: io::Error, path: &Path, committed: &[PathBuf], durability_uncertain| {
        PublishError {
            source: io::Error::new(
                source.kind(),
                format!("writing {}: {source}", path.display()),
            ),
            committed: committed.to_vec(),
            durability_uncertain,
            warnings: vec![],
        }
    };
    let result = (|| {
        // One staged file per distinct parent directory holds the names
        // claimed there: a destination is the parent the filesystem resolved
        // plus a name the volume treats as equal (case, normalization).
        let mut holders: Vec<usize> = Vec::new();
        for (path, bytes) in files {
            let held = backend
                .stage(path)
                .map_err(|e| failure(e, path, &committed, false))?;
            // Retain every staged file, including the one whose next step fails,
            // until the explicit cleanup below has reported its outcome.
            staged.push((path.clone(), held));
            let index = staged.len() - 1;
            let mut holder = None;
            for &candidate in &holders {
                if backend
                    .same_parent(&staged[candidate].1, &staged[index].1)
                    .map_err(|e| failure(e, path, &committed, false))?
                {
                    holder = Some(candidate);
                    break;
                }
            }
            let holder = holder.unwrap_or_else(|| {
                holders.push(index);
                index
            });
            if backend
                .claim_name(&staged[holder].1, &staged[index].1)
                .map_err(|e| failure(e, path, &committed, false))?
            {
                return Err(failure(
                    io::Error::new(io::ErrorKind::InvalidInput, "duplicate output path"),
                    path,
                    &committed,
                    false,
                ));
            }
            let (_, held) = staged.last_mut().expect("just staged");
            for phase in [Phase::Write, Phase::Flush, Phase::Sync, Phase::Validate] {
                backend
                    .step(held, phase, bytes)
                    .map_err(|e| failure(e, path, &committed, false))?;
            }
        }
        for (path, held) in &mut staged {
            backend
                .step(held, Phase::Commit, &[])
                .map_err(|e| failure(e, path, &committed, false))?;
            committed.push(path.clone());
            backend
                .step(held, Phase::SyncParent, &[])
                .map_err(|e| failure(e, path, &committed, true))?;
        }
        Ok(())
    })();
    let warnings = staged
        .iter_mut()
        .filter_map(|(path, held)| {
            backend
                .cleanup(held)
                .err()
                .map(|error| format!("cleaning staging for {}: {error}", path.display()))
        })
        .collect();
    finish(result, warnings)
}

/// A caller-granted directory held open across all operations. Relative path
/// resolution cannot follow a symlink outside this capability, even if a
/// pathname checked earlier is concurrently replaced.
pub struct OutputRoot {
    dir: cap_std::fs::Dir,
}

impl OutputRoot {
    /// Grant access to an existing trusted directory once, before serving callers.
    pub fn open(root: &Path) -> io::Result<Self> {
        Ok(Self {
            dir: cap_std::fs::Dir::open_ambient_dir(root, cap_std::ambient_authority())?,
        })
    }

    /// Read a confined file without reopening the root by pathname.
    pub fn read(&self, relative: &Path) -> io::Result<Vec<u8>> {
        // Input names are literal local names. The directory capability itself
        // confines resolution; export portability rules apply only to writes.
        self.dir.read(relative)
    }

    /// Stage and verify every file before committing any. Replacement is atomic
    /// per file, not across the set. Existing outputs survive all staging errors.
    ///
    /// # Errors
    /// Rejects nonportable paths, escaping symlinks, output symlinks and conflicts.
    /// A commit or durability error reports the files already committed.
    /// Cleanup failures are returned as warnings on either outcome.
    pub fn publish(
        &self,
        files: &[(PathBuf, &[u8])],
        overwrite: bool,
    ) -> Result<PublishReport, PublishError> {
        // Validate all names before even creating output directories.
        for (path, _) in files {
            validate_relative(path).map_err(|source| PublishError {
                committed: vec![],
                durability_uncertain: false,
                warnings: vec![],
                source,
            })?;
        }
        transaction(
            &mut FsBackend {
                root: Some(&self.dir),
                overwrite,
                #[cfg(test)]
                fail: None,
                #[cfg(test)]
                fail_cleanup: false,
            },
            files,
        )
    }
}

/// Publish explicitly authorized local paths. Each file's parent is opened
/// once and held through staging, replacement and directory sync. Unlike
/// [`OutputRoot`], this API grants ambient local access (the CLI policy).
/// Replacing a symlink replaces the link itself, never its referent.
///
/// # Errors
/// See [`PublishError`]; no fallback removes an old destination.
/// Cleanup failures are returned as warnings, including after successful installation.
pub fn publish_paths(
    files: &[(PathBuf, &[u8])],
    overwrite: bool,
) -> Result<PublishReport, PublishError> {
    transaction(
        &mut FsBackend {
            root: None,
            overwrite,
            #[cfg(test)]
            fail: None,
            #[cfg(test)]
            fail_cleanup: false,
        },
        files,
    )
}

fn validate_relative(path: &Path) -> io::Result<()> {
    let bad = || {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("unsafe export path: {}", path.display()),
        )
    };
    let text = path.to_str().ok_or_else(bad)?;
    if text.is_empty() {
        return Err(bad());
    }
    for part in text.split('/') {
        if part.is_empty()
            || part == "."
            || part == ".."
            || part.len() > 255
            || part.ends_with(['.', ' '])
            || part.chars().any(|c| {
                c.is_control()
                    || matches!(
                        c,
                        '\\' | ':' | '%' | '<' | '>' | '"' | '|' | '?' | '*'
                            | '\u{061c}' | '\u{200e}' | '\u{200f}'
                            | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
                            | '\u{feff}'
                    )
            })
        {
            return Err(bad());
        }
        let stem = part.split('.').next().unwrap_or("").to_ascii_uppercase();
        if matches!(
            stem.as_str(),
            "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
        ) || ["COM", "LPT"].iter().any(|prefix| {
            stem.strip_prefix(prefix).is_some_and(|n| {
                matches!(
                    n,
                    "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
                )
            })
        }) {
            return Err(bad());
        }
    }
    Ok(())
}

struct FsBackend<'a> {
    root: Option<&'a cap_std::fs::Dir>,
    overwrite: bool,
    #[cfg(test)]
    fail: Option<Phase>,
    #[cfg(test)]
    fail_cleanup: bool,
}
/// Verified bytes held in private staging beside an authorized local output.
/// Dropping an uncommitted file removes its staging directory best effort.
pub struct StagedFile {
    path: PathBuf,
    parent: cap_std::fs::Dir,
    scratch: Option<cap_std::fs::Dir>,
    scratch_name: Option<String>,
    file: Option<cap_std::fs::File>,
    target: std::ffi::OsString,
    overwrite: bool,
    #[cfg(test)]
    fail_cleanup: bool,
}
impl StagedFile {
    /// Write, flush, sync and verify bytes without changing the destination.
    pub fn prepare(path: &Path, bytes: &[u8], overwrite: bool) -> io::Result<Self> {
        let mut backend = FsBackend {
            root: None,
            overwrite,
            #[cfg(test)]
            fail: None,
            #[cfg(test)]
            fail_cleanup: false,
        };
        let mut staged = backend.stage(path)?;
        for phase in [Phase::Write, Phase::Flush, Phase::Sync, Phase::Validate] {
            backend.step(&mut staged, phase, bytes)?;
        }
        Ok(staged)
    }

    /// Install the verified bytes, then acknowledge parent-directory durability.
    /// A durability error names the output that has already committed.
    pub fn commit(mut self) -> Result<PublishReport, PublishError> {
        let mut backend = FsBackend {
            root: None,
            overwrite: self.overwrite,
            #[cfg(test)]
            fail: None,
            #[cfg(test)]
            fail_cleanup: false,
        };
        let result = (|| {
            backend
                .step(&mut self, Phase::Commit, &[])
                .map_err(|source| PublishError {
                    committed: vec![],
                    durability_uncertain: false,
                    source,
                    warnings: vec![],
                })?;
            backend
                .step(&mut self, Phase::SyncParent, &[])
                .map_err(|source| PublishError {
                    committed: vec![self.path.clone()],
                    durability_uncertain: true,
                    source,
                    warnings: vec![],
                })
        })();
        let warnings = self
            .cleanup()
            .err()
            .map(|error| format!("cleaning staging for {}: {error}", self.path.display()))
            .into_iter()
            .collect();
        finish(result, warnings)
    }

    /// Remove staging after closing all of its handles. Safe to call again.
    /// A swapped symlink is refused; its referent must never be traversed.
    fn cleanup(&mut self) -> io::Result<()> {
        drop(self.file.take());
        // cap-std directory handles deny FILE_SHARE_DELETE on Windows. Even
        // a clone passed to remove_open_dir_all leaves the original blocking it.
        drop(self.scratch.take());
        let Some(name) = self.scratch_name.as_ref() else {
            return Ok(());
        };
        #[cfg(test)]
        if self.fail_cleanup {
            return Err(io::Error::other("injected cleanup"));
        }
        match self.parent.symlink_metadata(name) {
            Ok(metadata) if metadata.is_symlink() => {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "refusing staging cleanup through a symlink",
                ));
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                self.scratch_name = None;
                return Ok(());
            }
            Err(error) => return Err(error),
            Ok(_) => (),
        }
        self.parent.remove_dir_all(name)?;
        self.scratch_name = None;
        Ok(())
    }
}

/// Windows directory handles are read-only, but `FlushFileBuffers` needs
/// `GENERIC_WRITE`. NTFS journals metadata; directory sync is a no-op there.
/// Reopening the parent for writing by path would break root confinement (D35).
fn sync_directory_for_platform(
    windows: bool,
    sync: impl FnOnce() -> io::Result<()>,
) -> io::Result<()> {
    if windows { Ok(()) } else { sync() }
}

/// cap-std opens directories `O_PATH` on Linux, and `fsync` on an `O_PATH`
/// descriptor is EBADF (#1351). Opening `.` through the handle gives a
/// readable descriptor without walking a path, so confinement holds (D35).
fn sync_directory_handle(dir: &cap_std::fs::Dir) -> io::Result<()> {
    sync_directory_for_platform(cfg!(windows), || {
        dir.open_with(".", cap_std::fs::OpenOptions::new().read(true))?
            .into_std()
            .sync_all()
    })
}

/// Acknowledge directory durability using a held directory handle (no-op on Windows).
pub fn sync_directory(path: &Path) -> io::Result<()> {
    let dir = cap_std::fs::Dir::open_ambient_dir(path, cap_std::ambient_authority())?;
    sync_directory_handle(&dir)
}

impl Drop for StagedFile {
    fn drop(&mut self) {
        let _ = self.cleanup();
    }
}

/// Attributes that belong to the destination and must move onto the staged
/// inode. A kernel security label stays behind: the kernel applies it, and
/// refusing the replacement because that label cannot be reset would fail
/// an ordinary publish.
#[cfg(unix)]
fn copy_replaced_xattrs(from: &cap_std::fs::File, to: &cap_std::fs::File) -> io::Result<()> {
    use std::os::unix::io::{AsRawFd, RawFd};
    use xattr::FileExt;

    struct Handle<'a>(&'a cap_std::fs::File);

    impl AsRawFd for Handle<'_> {
        fn as_raw_fd(&self) -> RawFd {
            self.0.as_raw_fd()
        }
    }

    impl xattr::FileExt for Handle<'_> {}

    let from = Handle(from);
    let to = Handle(to);
    let names = match from.list_xattr() {
        Ok(names) => names,
        Err(error) if error.kind() == io::ErrorKind::Unsupported => return Ok(()),
        Err(error) => return Err(error),
    };
    for name in names {
        if !replaced_xattr(&name) {
            continue;
        }
        if let Some(value) = from.get_xattr(&name)? {
            to.set_xattr(&name, &value)?;
        }
    }
    Ok(())
}

#[cfg(all(unix, target_os = "linux"))]
fn replaced_xattr(name: &std::ffi::OsStr) -> bool {
    let bytes = name.as_encoded_bytes();
    bytes.starts_with(b"user.") || bytes.starts_with(b"system.posix_acl_")
}

#[cfg(all(unix, not(target_os = "linux")))]
fn replaced_xattr(name: &std::ffi::OsStr) -> bool {
    let bytes = name.as_encoded_bytes();
    !bytes.starts_with(b"system.") && !macos_kernel_label(bytes)
}

/// A label the macOS kernel owns: userspace gets EPERM writing
/// `com.apple.rootless` or a `com.apple.system.` name, and the kernel sets
/// `com.apple.provenance` and `com.apple.macl` on the new inode itself.
#[cfg(all(unix, not(target_os = "linux")))]
fn macos_kernel_label(name: &[u8]) -> bool {
    name.starts_with(b"com.apple.system.")
        || matches!(
            name,
            b"com.apple.rootless" | b"com.apple.provenance" | b"com.apple.macl"
        )
}

impl Backend for FsBackend<'_> {
    type Staged = StagedFile;
    fn stage(&mut self, path: &Path) -> io::Result<StagedFile> {
        use cap_std::fs::{Dir, DirBuilder, OpenOptions};
        let parent = path
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or(Path::new("."));
        let target = path
            .file_name()
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "output has no filename"))?
            .to_os_string();
        let parent = if let Some(root) = self.root {
            let mut dir = root.try_clone()?;
            for component in parent.components() {
                if let std::path::Component::Normal(name) = component {
                    match dir.create_dir(name) {
                        Ok(()) => sync_directory_handle(&dir)?,
                        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (),
                        Err(e) => return Err(e),
                    }
                    dir = dir.open_dir(name)?;
                }
            }
            dir
        } else {
            Dir::open_ambient_dir(parent, cap_std::ambient_authority())?
        };
        let mut permissions = None;
        match parent.symlink_metadata(&target) {
            Ok(metadata) => {
                if !self.overwrite {
                    return Err(io::Error::new(
                        io::ErrorKind::AlreadyExists,
                        format!(
                            "{} exists; pass overwrite=true or --force to replace it",
                            path.display()
                        ),
                    ));
                }
                if metadata.is_dir() || (self.root.is_some() && metadata.is_symlink()) {
                    return Err(io::Error::new(
                        io::ErrorKind::PermissionDenied,
                        format!("output is a directory or symlink: {}", path.display()),
                    ));
                }
                if metadata.is_file() {
                    permissions = Some(metadata.permissions());
                }
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => (),
            Err(e) => return Err(e),
        }
        // Open the destination before `parent` and `target` move into the
        // staged file. The attributes are read from this handle.
        #[cfg(unix)]
        let source = if permissions.is_some() {
            Some(parent.open(&target)?)
        } else {
            None
        };
        let builder = DirBuilder::new();
        #[cfg(unix)]
        let builder = {
            use cap_std::fs::DirBuilderExt;
            let mut builder = builder;
            builder.mode(0o700);
            builder
        };
        let name = format!(".jubarte-{}.partial", staging_suffix());
        // Exclusive mkdir: a collision is an error, never an existing staging area.
        parent.create_dir_with(&name, &builder)?;
        let scratch = parent.open_dir(&name).inspect_err(|_| {
            let _ = parent.remove_dir(&name);
        })?;
        let mut staged = StagedFile {
            path: path.to_path_buf(),
            parent,
            scratch: Some(scratch),
            scratch_name: Some(name),
            file: None,
            target,
            overwrite: self.overwrite,
            #[cfg(test)]
            fail_cleanup: self.fail_cleanup,
        };
        staged.file = Some(
            staged
                .scratch
                .as_ref()
                .expect("open staging directory")
                .open_with(
                    "bytes",
                    OpenOptions::new().read(true).write(true).create_new(true),
                )?,
        );
        if let Some(permissions) = permissions {
            let file = staged.file.as_ref().expect("open staging file");
            file.set_permissions(permissions)?;
            // Mode bits are on the staged inode. Attributes are not, and the
            // later rename drops whatever still sits on the old inode.
            #[cfg(unix)]
            if let Some(source) = source.as_ref() {
                copy_replaced_xattrs(source, file)?;
            }
        }
        Ok(staged)
    }
    fn cleanup(&mut self, staged: &mut StagedFile) -> io::Result<()> {
        staged.cleanup()
    }
    fn same_parent(&mut self, a: &StagedFile, b: &StagedFile) -> io::Result<bool> {
        // `a`'s staging directory has a unique name; `b`'s parent handle sees
        // it exactly when both handles are one directory.
        let Some(name) = a.scratch_name.as_deref() else {
            return Ok(false);
        };
        match b.parent.symlink_metadata(name) {
            Ok(_) => Ok(true),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
            Err(error) => Err(error),
        }
    }
    fn claim_name(&mut self, holder: &StagedFile, staged: &StagedFile) -> io::Result<bool> {
        // The names live in a private directory inside `holder`'s staging, on
        // the destination's volume, so the volume itself decides equality.
        // The handle is closed before return: staging cleanup removes it.
        const NAMES: &str = "names";
        let scratch = holder.scratch.as_ref().expect("open staging directory");
        match scratch.create_dir(NAMES) {
            Ok(()) => (),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => (),
            Err(error) => return Err(error),
        }
        let names = scratch.open_dir(NAMES)?;
        match names.symlink_metadata(&staged.target) {
            Ok(_) => return Ok(true),
            Err(error) if error.kind() == io::ErrorKind::NotFound => (),
            Err(error) => return Err(error),
        }
        names.open_with(
            &staged.target,
            cap_std::fs::OpenOptions::new().write(true).create_new(true),
        )?;
        Ok(false)
    }
    fn step(&mut self, staged: &mut StagedFile, phase: Phase, bytes: &[u8]) -> io::Result<()> {
        use std::io::{Read, Seek, SeekFrom, Write};
        #[cfg(test)]
        if self.fail == Some(phase) {
            if phase == Phase::Commit {
                staged
                    .scratch
                    .as_ref()
                    .expect("open staging directory")
                    .remove_file("bytes")?;
            } else {
                return Err(io::Error::other(format!("injected {phase:?}")));
            }
        }
        let file = staged.file.as_mut().expect("open staging file");
        match phase {
            Phase::Write => file.write_all(bytes),
            Phase::Flush => file.flush(),
            Phase::Sync => file.sync_all(),
            Phase::Validate => {
                file.seek(SeekFrom::Start(0))?;
                if file.metadata()?.len() != bytes.len() as u64 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "staged output length mismatch",
                    ));
                }
                let mut buffer = [0; 8192];
                for chunk in bytes.chunks(buffer.len()) {
                    file.read_exact(&mut buffer[..chunk.len()])?;
                    if buffer[..chunk.len()] != *chunk {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            "staged output bytes mismatch",
                        ));
                    }
                }
                Ok(())
            }
            Phase::Commit if staged.overwrite => staged
                .scratch
                .as_ref()
                .expect("open staging directory")
                .rename("bytes", &staged.parent, &staged.target),
            // hard_link is an atomic no-clobber installation, including when a
            // hostile writer creates the target after the initial check.
            Phase::Commit => staged
                .scratch
                .as_ref()
                .expect("open staging directory")
                .hard_link("bytes", &staged.parent, &staged.target),
            Phase::SyncParent => sync_directory_handle(&staged.parent),
        }
    }
}

/// A staging-directory suffix: 32 lowercase hex characters hashed from the
/// process id, a process-wide counter and the clock, through two freshly
/// seeded hashers, so two staging areas never share a name without a uuid
/// dependency (the exclusive `create_dir_with` below still makes a
/// collision an error, never an existing staging area).
fn staging_suffix() -> String {
    use std::hash::BuildHasher;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos() as u64);
    let pid = u64::from(std::process::id());
    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
    let one = std::hash::RandomState::new().hash_one((pid, count, nanos));
    let two = std::hash::RandomState::new().hash_one((nanos, count, pid));
    format!("{one:016x}{two:016x}")
}

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

    #[test]
    fn staging_suffixes_are_unique_and_hex() {
        let suffixes: Vec<String> = (0..10_000).map(|_| staging_suffix()).collect();
        let distinct: std::collections::HashSet<&String> = suffixes.iter().collect();
        assert_eq!(distinct.len(), suffixes.len(), "every suffix is distinct");
        for suffix in &suffixes {
            assert_eq!(suffix.len(), 32, "{suffix}: 32 characters");
            assert!(
                suffix
                    .bytes()
                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
                "{suffix}: lowercase hex only"
            );
        }
    }

    // Filesystem integration probes: exercise actual handle lifetime and hard links.
    #[test]
    fn cleanup_failure_is_reported_after_install_and_alongside_publish_failure() {
        for phase in [
            None,
            Some(Phase::Write),
            Some(Phase::Commit),
            Some(Phase::SyncParent),
        ] {
            let temp = tempfile::tempdir().unwrap();
            let root = OutputRoot::open(temp.path()).unwrap();
            let mut backend = FsBackend {
                root: Some(&root.dir),
                overwrite: false,
                fail: phase,
                fail_cleanup: true,
            };
            let result = transaction(&mut backend, &[("output".into(), b"Alice")]);
            let installed = phase.is_none() || phase == Some(Phase::SyncParent);
            assert_eq!(temp.path().join("output").exists(), installed);
            if installed {
                assert_eq!(root.read(Path::new("output")).unwrap(), b"Alice");
            }
            let warnings = match result {
                Ok(report) => {
                    assert!(phase.is_none());
                    report.warnings
                }
                Err(error) => {
                    assert!(phase.is_some());
                    assert_eq!(
                        error.committed,
                        if installed {
                            vec![PathBuf::from("output")]
                        } else {
                            vec![]
                        }
                    );
                    assert_eq!(error.durability_uncertain, phase == Some(Phase::SyncParent));
                    if phase == Some(Phase::Commit) {
                        assert_eq!(error.source.kind(), io::ErrorKind::NotFound);
                    } else {
                        assert!(
                            error
                                .source
                                .to_string()
                                .contains(&format!("injected {:?}", phase.unwrap()))
                        );
                    }
                    error.warnings
                }
            };
            assert_eq!(warnings.len(), 1);
            assert!(
                warnings[0].contains("injected cleanup"),
                "cleanup failure was swallowed: {warnings:?}"
            );
        }
    }

    #[test]
    fn prepared_commit_reports_cleanup_failure_after_install() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("output");
        let mut staged = StagedFile::prepare(&path, b"Bob", false).unwrap();
        staged.fail_cleanup = true;
        let result = staged.commit();
        assert_eq!(std::fs::read(path).unwrap(), b"Bob");
        let report = result.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(report.warnings[0].contains("injected cleanup"));
    }

    #[test]
    fn every_publish_path_removes_partial_directories() {
        let temp = tempfile::tempdir().unwrap();
        let output = temp.path().join("output");
        // Fresh replacement, forced replacement, then no-overwrite hard-link commit.
        for overwrite in [true, true, false] {
            if !overwrite {
                std::fs::remove_file(&output).unwrap();
            }
            let report = publish_paths(&[(output.clone(), b"Carol Diaz")], overwrite).unwrap();
            assert!(report.warnings.is_empty(), "{report:?}");
            assert_no_partials(temp.path());
            assert_eq!(std::fs::read(&output).unwrap(), b"Carol Diaz");
        }
        for phase in [
            Phase::Write,
            Phase::Flush,
            Phase::Sync,
            Phase::Validate,
            Phase::Commit,
            Phase::SyncParent,
        ] {
            let mut backend = FsBackend {
                root: None,
                overwrite: true,
                fail: Some(phase),
                fail_cleanup: false,
            };
            let error = transaction(
                &mut backend,
                &[
                    (output.clone(), b"Alice"),
                    (temp.path().join("second"), b"Bob"),
                ],
            )
            .unwrap_err();
            assert!(error.warnings.is_empty(), "{error:?}");
            assert_no_partials(temp.path());
        }
    }

    fn assert_no_partials(parent: &Path) {
        let partials: Vec<_> = std::fs::read_dir(parent)
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .filter(|name| {
                let name = name.to_string_lossy();
                name.starts_with(".jubarte-") && name.ends_with(".partial")
            })
            .collect();
        assert!(partials.is_empty(), "staging leftovers: {partials:?}");
    }

    #[cfg(unix)]
    #[test]
    fn cleanup_refuses_a_swapped_scratch_symlink() {
        let temp = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        std::fs::write(outside.path().join("keep"), b"Carol Diaz").unwrap();
        let path = temp.path().join("output");
        let staged = StagedFile::prepare(&path, b"Alice", false).unwrap();
        let name = std::fs::read_dir(temp.path())
            .unwrap()
            .next()
            .unwrap()
            .unwrap()
            .file_name();
        std::fs::rename(temp.path().join(&name), temp.path().join("held")).unwrap();
        std::os::unix::fs::symlink(outside.path(), temp.path().join(&name)).unwrap();
        let result = staged.commit();
        assert_eq!(
            std::fs::read(outside.path().join("keep")).unwrap(),
            b"Carol Diaz"
        );
        assert!(
            temp.path()
                .join(&name)
                .symlink_metadata()
                .unwrap()
                .is_symlink()
        );
        let report = format!("{result:?}");
        assert!(
            report.contains("symlink"),
            "swapped symlink was not reported: {report}"
        );
    }

    /// A forced replacement keeps a user attribute that lived on the old inode.
    #[cfg(unix)]
    #[test]
    fn a_forced_replacement_keeps_the_destination_user_xattr() {
        let temp = tempfile::tempdir().unwrap();
        let output = temp.path().join("output");
        std::fs::write(&output, b"old").unwrap();
        // The crate the copy itself uses, so Linux and macOS both run it.
        match xattr::set(&output, "user.jubarte", b"kept") {
            Ok(()) => {}
            // A file system with no user attributes has nothing to keep.
            Err(error) if error.kind() == std::io::ErrorKind::Unsupported => return,
            Err(error) => panic!("could not set the user attribute: {error}"),
        }
        let report = publish_paths(&[(output.clone(), b"new")], true).unwrap();
        assert!(report.warnings.is_empty(), "{report:?}");
        assert_eq!(std::fs::read(&output).unwrap(), b"new");
        assert_eq!(
            xattr::get(&output, "user.jubarte").unwrap().as_deref(),
            Some(b"kept".as_slice()),
            "overwrite dropped the destination extended attribute"
        );
    }

    /// macOS labels the kernel owns stay behind: userspace cannot write
    /// `com.apple.rootless` or `com.apple.system.*` (EPERM), and the kernel
    /// sets `com.apple.provenance` and `com.apple.macl` itself. Copying them
    /// would fail an ordinary forced publish. Other names still move.
    #[cfg(target_os = "macos")]
    #[test]
    fn macos_kernel_labels_are_left_for_the_kernel() {
        use std::ffi::OsStr;
        for name in [
            "com.apple.rootless",
            "com.apple.system.Security",
            "com.apple.provenance",
            "com.apple.macl",
        ] {
            assert!(!replaced_xattr(OsStr::new(name)), "{name} must stay behind");
        }
        for name in ["user.jubarte", "com.apple.quarantine", "com.example.tag"] {
            assert!(replaced_xattr(OsStr::new(name)), "{name} must move");
        }
    }

    #[test]
    fn windows_directory_sync_is_a_noop() {
        let mut called = false;
        let result = sync_directory_for_platform(true, || {
            called = true;
            Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "read-only directory",
            ))
        });
        assert!(
            result.is_ok(),
            "Windows directory sync must succeed: {result:?}"
        );
        assert!(!called, "Windows must not attempt the directory sync");
    }

    #[test]
    fn unix_directory_sync_calls_the_operation_and_preserves_its_result() {
        for kind in [None, Some(io::ErrorKind::PermissionDenied)] {
            let mut called = false;
            let result = sync_directory_for_platform(false, || {
                called = true;
                match kind {
                    None => Ok(()),
                    Some(kind) => Err(io::Error::new(kind, "read-only directory")),
                }
            });
            assert!(called, "Unix must attempt the directory sync");
            assert_eq!(result.as_ref().err().map(io::Error::kind), kind);
            if let Err(error) = result {
                assert_eq!(error.to_string(), "read-only directory");
            }
        }
    }

    /// cap-std opens directories `O_PATH` on Linux, and `fsync` on an
    /// `O_PATH` descriptor is EBADF (#1351): every publication failed after
    /// its commit there, with "durability uncertain".
    #[test]
    fn a_cap_std_directory_handle_can_be_synced() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir(temp.path().join("sub")).unwrap();
        let dir =
            cap_std::fs::Dir::open_ambient_dir(temp.path(), cap_std::ambient_authority()).unwrap();
        sync_directory_handle(&dir).expect("an ambient directory handle syncs");
        sync_directory_handle(&dir.open_dir("sub").unwrap())
            .expect("a directory opened through a handle syncs");
        sync_directory(temp.path()).expect("sync_directory syncs");
    }

    /// Deterministic filesystem fake: all state and injected failures stay in memory.
    struct Memory {
        visible: BTreeMap<PathBuf, Vec<u8>>,
        fail: Option<(usize, Phase)>,
        count: usize,
        order: Vec<(usize, Phase)>,
        fail_stage: Option<usize>,
        claimed: std::collections::BTreeSet<PathBuf>,
    }
    impl Memory {
        fn new(fail: Option<(usize, Phase)>) -> Self {
            Self {
                visible: [
                    (PathBuf::from("a"), b"old a".to_vec()),
                    (PathBuf::from("b"), b"old b".to_vec()),
                ]
                .into(),
                fail,
                count: 0,
                order: vec![],
                fail_stage: None,
                claimed: std::collections::BTreeSet::new(),
            }
        }
    }
    impl Backend for Memory {
        type Staged = (usize, PathBuf, Vec<u8>);
        fn stage(&mut self, path: &Path) -> io::Result<Self::Staged> {
            let id = self.count;
            self.count += 1;
            if self.fail_stage == Some(id) {
                return Err(io::Error::other("injected staging creation failure"));
            }
            Ok((id, path.into(), vec![]))
        }
        fn cleanup(&mut self, _staged: &mut Self::Staged) -> io::Result<()> {
            Ok(())
        }
        fn same_parent(&mut self, a: &Self::Staged, b: &Self::Staged) -> io::Result<bool> {
            Ok(a.1.parent() == b.1.parent())
        }
        fn claim_name(
            &mut self,
            _holder: &Self::Staged,
            staged: &Self::Staged,
        ) -> io::Result<bool> {
            Ok(!self.claimed.insert(staged.1.clone()))
        }
        fn step(
            &mut self,
            staged: &mut Self::Staged,
            phase: Phase,
            bytes: &[u8],
        ) -> io::Result<()> {
            let (id, path, held) = staged;
            self.order.push((*id, phase));
            if self.fail == Some((*id, phase)) {
                return Err(io::Error::other(format!("injected {phase:?}")));
            }
            match phase {
                Phase::Write => *held = bytes.to_vec(),
                Phase::Commit => {
                    self.visible.insert(path.clone(), held.clone());
                }
                _ => (),
            }
            Ok(())
        }
    }
    fn files() -> [(PathBuf, &'static [u8]); 2] {
        [("a".into(), b"new a"), ("b".into(), b"new b")]
    }

    fn fs_failure(phase: Phase) {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("output"), b"old output").unwrap();
        let root = OutputRoot::open(temp.path()).unwrap();
        let mut backend = FsBackend {
            root: Some(&root.dir),
            overwrite: true,
            fail: Some(phase),
            fail_cleanup: false,
        };
        let error = transaction(&mut backend, &[("output".into(), b"new output")])
            .expect_err("configured filesystem fault must fail publication");
        let installed = phase == Phase::SyncParent;
        assert_eq!(
            root.read(Path::new("output")).unwrap(),
            if installed {
                b"new output"
            } else {
                b"old output"
            }
        );
        assert_eq!(
            error.committed,
            if installed {
                vec![PathBuf::from("output")]
            } else {
                vec![]
            }
        );
        assert_eq!(error.durability_uncertain, installed);
        if installed {
            assert!(
                error.to_string().contains("durability uncertain"),
                "{error}"
            );
            assert!(
                error.source.to_string().contains("injected SyncParent"),
                "{error}"
            );
        } else {
            assert_eq!(error.source.kind(), io::ErrorKind::NotFound);
        }
        let remaining: Vec<_> = std::fs::read_dir(temp.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect();
        assert_eq!(remaining, [std::ffi::OsString::from("output")]);
    }

    #[test]
    fn audit_d13_fs_rename_failure_preserves_prior_output_and_cleans_staging() {
        fs_failure(Phase::Commit);
    }

    #[test]
    fn audit_d13_fs_parent_sync_failure_reports_installed_output_and_cleans_staging() {
        fs_failure(Phase::SyncParent);
    }

    #[test]
    fn audit_d13_all_precommit_failures_preserve_every_prior_output() {
        for phase in [Phase::Write, Phase::Flush, Phase::Sync, Phase::Validate] {
            for index in 0..2 {
                let mut fs = Memory::new(Some((index, phase)));
                let error = transaction(&mut fs, &files()).unwrap_err();
                assert!(error.source.to_string().contains("injected"), "{error}");
                assert!(error.committed.is_empty());
                assert!(!error.durability_uncertain);
                assert_eq!(fs.visible, Memory::new(None).visible);
            }
        }
    }
    #[test]
    fn audit_d13_rename_failure_never_deletes_old_and_reports_prior_commits() {
        for index in 0..2 {
            let mut fs = Memory::new(Some((index, Phase::Commit)));
            let error = transaction(&mut fs, &files()).unwrap_err();
            assert!(error.source.to_string().contains("injected"), "{error}");
            assert_eq!(error.committed.len(), index);
            assert_eq!(fs.visible[Path::new("b")], b"old b");
            assert_eq!(
                fs.visible[Path::new("a")],
                if index == 0 { b"old a" } else { b"new a" }
            );
        }
    }
    #[test]
    fn audit_d13_postcommit_sync_failure_reports_visible_output_and_uncertain_durability() {
        let mut fs = Memory::new(Some((0, Phase::SyncParent)));
        let error = transaction(&mut fs, &files()).unwrap_err();
        assert_eq!(error.committed, [PathBuf::from("a")]);
        assert!(error.durability_uncertain);
        assert_eq!(fs.visible[Path::new("a")], b"new a");
        assert_eq!(fs.visible[Path::new("b")], b"old b");
    }
    #[test]
    fn audit_d13_validates_the_entire_set_before_the_first_commit() {
        let mut fs = Memory::new(None);
        transaction(&mut fs, &files()).unwrap();
        assert_eq!(fs.visible[Path::new("b")], b"new b");
        let first_commit = fs
            .order
            .iter()
            .position(|(_, p)| *p == Phase::Commit)
            .unwrap();
        let last_validate = fs
            .order
            .iter()
            .rposition(|(_, p)| *p == Phase::Validate)
            .unwrap();
        assert!(last_validate < first_commit);
    }
    #[test]
    fn audit_d35_portable_names_cannot_smuggle_extra_path_authority() {
        for path in [
            "",
            "PRN",
            "AUX",
            "CONIN$",
            "CONOUT$",
            "COM¹.txt",
            "LPT².docx",
            "a<b",
            "a>b",
            "a\"b",
            "a|b",
            "a?b",
            "a*b",
            "../escape",
            "/absolute",
            "ok/../../escape",
            "C:\\escape",
            "a\\b",
            "NUL.txt",
            "con",
            "COM1.docx",
            "LPT9",
            "file:stream",
            "trailing.",
            "trailing ",
            "a/../b",
            "a//b",
            "./a",
            "a/%2e%2e/b",
            "a/%2Ftmp",
            "a/line\n",
            "a\u{061c}b",
            "a\u{200e}b",
            "a\u{200f}b",
            "a\u{202a}b",
            "a\u{202b}b",
            "a\u{202c}b",
            "a\u{202d}b",
            "a\u{202e}b",
            "a\u{2066}b",
            "a\u{2067}b",
            "a\u{2068}b",
            "a\u{2069}b",
            "a\u{feff}b",
        ] {
            assert!(
                validate_relative(Path::new(path)).is_err(),
                "accepted {path:?}"
            );
        }
        assert!(validate_relative(Path::new(&"x".repeat(256))).is_err());
        for path in [
            "page-01.png",
            "media/0123456789abcdef.png",
            "new folder/redline.docx",
            "نام\u{200c}نامه.docx",
            "नाम\u{200d}पत्र.docx",
        ] {
            assert!(validate_relative(Path::new(path)).is_ok(), "refused {path}");
        }
    }
    #[test]
    fn staging_creation_failure_and_duplicate_names_never_commit() {
        let mut fs = Memory::new(None);
        fs.fail_stage = Some(1);
        let error = transaction(&mut fs, &files()).unwrap_err();
        assert!(error.committed.is_empty());
        assert_eq!(fs.visible, Memory::new(None).visible);
        let mut fs = Memory::new(None);
        let error = transaction(
            &mut fs,
            &[("a".into(), b"first".as_slice()), ("a".into(), b"second")],
        )
        .unwrap_err();
        assert_eq!(error.source.kind(), io::ErrorKind::InvalidInput);
        assert!(error.committed.is_empty());
        assert_eq!(fs.visible, Memory::new(None).visible);
        assert!(transaction(&mut fs, &[]).is_ok());
    }

    /// A refused set publishes nothing and leaves no staging behind.
    fn refused(dir: &Path, files: &[(PathBuf, &[u8])], overwrite: bool) {
        let error = publish_paths(files, overwrite).unwrap_err();
        assert!(
            error.source.to_string().contains("duplicate output path"),
            "{error}"
        );
        assert!(error.committed.is_empty(), "{error}");
        assert_no_partials(dir);
    }

    /// Whether `dir`'s volume treats `a` and `b` as one name.
    fn one_name(dir: &Path, a: &str, b: &str) -> bool {
        let probe = tempfile::tempdir_in(dir).unwrap();
        std::fs::write(probe.path().join(a), b"").unwrap();
        probe.path().join(b).exists()
    }

    #[test]
    fn a_parent_step_spelling_of_one_destination_publishes_nothing() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir(temp.path().join("x")).unwrap();
        let (a, stepped) = (temp.path().join("a"), temp.path().join("x/../a"));
        assert_ne!(a, stepped);
        refused(temp.path(), &[(a.clone(), b"1"), (stepped, b"2")], false);
        assert!(!a.exists(), "a refused set must not publish");
    }

    #[cfg(unix)]
    #[test]
    fn a_parent_reached_through_a_directory_symlink_is_one_destination() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir(temp.path().join("real")).unwrap();
        std::os::unix::fs::symlink("real", temp.path().join("alias")).unwrap();
        refused(
            temp.path(),
            &[
                (temp.path().join("real/x"), b"1"),
                (temp.path().join("alias/x"), b"2"),
            ],
            true,
        );
        assert!(!temp.path().join("real/x").exists());
    }

    /// The kernel resolves `jump` before `..`: `left/jump/../out` is
    /// `elsewhere/out`, not `left/out`.
    #[cfg(unix)]
    #[test]
    fn a_parent_step_through_a_symlink_follows_the_filesystem() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("elsewhere/sub")).unwrap();
        std::fs::create_dir(temp.path().join("left")).unwrap();
        std::os::unix::fs::symlink(
            temp.path().join("elsewhere/sub"),
            temp.path().join("left/jump"),
        )
        .unwrap();
        refused(
            temp.path(),
            &[
                (temp.path().join("left/jump/../out"), b"1"),
                (temp.path().join("elsewhere/out"), b"2"),
            ],
            true,
        );
        // `left/out` is a different file: it publishes beside `elsewhere/out`.
        publish_paths(
            &[
                (temp.path().join("left/jump/../out"), b"1"),
                (temp.path().join("left/out"), b"2"),
            ],
            true,
        )
        .unwrap();
        assert_eq!(
            std::fs::read(temp.path().join("elsewhere/out")).unwrap(),
            b"1"
        );
        assert_eq!(std::fs::read(temp.path().join("left/out")).unwrap(), b"2");
    }

    /// Installing replaces a symlink's entry, never its referent: the link
    /// and its target are two destinations.
    #[cfg(unix)]
    #[test]
    fn a_symlink_and_its_referent_are_two_destinations() {
        let temp = tempfile::tempdir().unwrap();
        let (link, target) = (temp.path().join("link"), temp.path().join("target"));
        std::fs::write(&target, b"old").unwrap();
        std::os::unix::fs::symlink("target", &link).unwrap();
        publish_paths(
            &[(link.clone(), b"by link"), (target.clone(), b"by target")],
            true,
        )
        .unwrap();
        assert!(!std::fs::symlink_metadata(&link).unwrap().is_symlink());
        assert_eq!(std::fs::read(&link).unwrap(), b"by link");
        assert_eq!(std::fs::read(&target).unwrap(), b"by target");
    }

    /// Names one only by case are one destination exactly when the volume
    /// says so; a case-sensitive volume keeps both.
    #[test]
    fn case_follows_the_volume() {
        let temp = tempfile::tempdir().unwrap();
        let files = [
            (temp.path().join("Report.txt"), &b"1"[..]),
            (temp.path().join("report.txt"), &b"2"[..]),
        ];
        if one_name(temp.path(), "Report.txt", "report.txt") {
            refused(temp.path(), &files, false);
        } else {
            publish_paths(&files, false).unwrap();
        }
    }

    /// Composed and decomposed `é` are one name on a normalization-
    /// insensitive volume (APFS) and two elsewhere.
    #[test]
    fn unicode_normalization_follows_the_volume() {
        let temp = tempfile::tempdir().unwrap();
        let (composed, decomposed) = ("caf\u{e9}", "cafe\u{301}");
        let files = [
            (temp.path().join(composed), &b"1"[..]),
            (temp.path().join(decomposed), &b"2"[..]),
        ];
        if one_name(temp.path(), composed, decomposed) {
            refused(temp.path(), &files, false);
        } else {
            publish_paths(&files, false).unwrap();
        }
    }

    /// Distinct non-UTF-8 names stay distinct (APFS refuses them outright).
    #[cfg(target_os = "linux")]
    #[test]
    fn distinct_non_utf8_names_are_two_destinations() {
        use std::os::unix::ffi::OsStrExt;
        let temp = tempfile::tempdir().unwrap();
        let name = |byte: u8| temp.path().join(std::ffi::OsStr::from_bytes(&[b'x', byte]));
        publish_paths(&[(name(0xff), b"1"), (name(0xfe), b"2")], false).unwrap();
        assert_eq!(std::fs::read(name(0xff)).unwrap(), b"1");
        assert_eq!(std::fs::read(name(0xfe)).unwrap(), b"2");
    }

    /// An output root resolves its names from the root, whatever the
    /// process's working directory is.
    #[cfg(unix)]
    #[test]
    fn an_output_root_resolves_aliases_from_the_root() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir(temp.path().join("real")).unwrap();
        std::os::unix::fs::symlink("real", temp.path().join("alias")).unwrap();
        let root = OutputRoot::open(temp.path()).unwrap();
        let error = root
            .publish(
                &[
                    (PathBuf::from("real/x"), b"1"),
                    (PathBuf::from("alias/x"), b"2"),
                ],
                true,
            )
            .unwrap_err();
        assert!(
            error.source.to_string().contains("duplicate output path"),
            "{error}"
        );
        assert!(error.committed.is_empty(), "{error}");
        assert!(!temp.path().join("real/x").exists());
        assert_no_partials(temp.path());
    }
}