agent-first-data 0.40.0

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
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
//! One atomic file installation, shared by every writer in this crate.
//!
//! Installing a file so that a crash can never expose a half-written one is a
//! fixed sequence — private same-directory temporary file, write, permissions,
//! fsync the file, atomically install it over the target, fsync the directory
//! entry — and each step has a way to be got subtly wrong. Writing that
//! sequence a second time somewhere else is how one copy ends up durable and
//! the other only looks it: a `rename` that is never followed by a parent
//! directory fsync returns success while the new directory entry may still be
//! lost to a power cut.
//!
//! So the sequence lives here once, and callers bring only what is genuinely
//! theirs: the pre-write guard (what may be overwritten is a policy question,
//! and different writers answer it differently) and the error type. Failures
//! name the step that failed through [`AtomicError`], whose `Display` is the
//! tail of a caller's own message — `write: ` + `install \`p\`: …`.

use std::fs::{self, File, OpenOptions};
use std::io::Write as _;
use std::path::{Path, PathBuf};

/// Atomically replace a regular file, preserving its permissions. On Unix a
/// new file starts owner-only (`0600`); Windows has no mode bits, so a new file
/// takes the directory's inherited ACL. Symbolic links and special files are refused; parent
/// directories must already exist. A directory-sync error reports an uncertain
/// durable commit through [`AtomicError::commit_uncertain`].
///
/// This is the default form of [`AtomicWrite`]; use that for explicit
/// permission bits or a write that refuses an existing target.
///
/// Hard links are not checked. The new file is renamed over the path, so a
/// target with other hard links is split from them: this path gets the new
/// bytes and every other link keeps the old file. A caller that needs a
/// hard-linked target refused writes through
/// [`DocumentFile`](crate::document::DocumentFile) instead, whose
/// [`ensure_mutable`](crate::document::DocumentFile::ensure_mutable) guard (run
/// by `save` and by a replacing `create_atomic`) refuses one on Unix.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), AtomicError> {
    AtomicWrite::new(bytes).write(path)
}

pub(crate) fn validate_unix_mode(mode: Option<u32>) -> std::io::Result<()> {
    if let Some(mode) = mode
        && mode & !0o777 != 0
    {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("unix mode {mode:o} contains bits outside 0o777"),
        ));
    }
    Ok(())
}

/// How the finished temporary file becomes the target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InstallMode {
    /// `rename` over the target. Replaces whatever is at the path — including a
    /// symbolic link, which is replaced rather than followed.
    Replace,
    /// `hard_link`, which refuses to install over an existing target. The
    /// caller distinguishes that refusal by [`AtomicError::target_exists`].
    NewOnly,
}

/// One atomic file write and its options: [`write_atomic`] is the default form.
///
/// ```no_run
/// # use agent_first_data::AtomicWrite;
/// # use std::path::Path;
/// # fn demo() -> Result<(), agent_first_data::AtomicError> {
/// let secret = AtomicWrite::new(b"token_secret = \"...\"\n");
/// #[cfg(unix)]
/// let secret = secret.mode(0o600);
/// match secret.new_only().write(Path::new("credentials.toml")) {
///     Err(error) if error.target_exists() => { /* keep the file that is there */ }
///     other => other?,
/// }
/// # Ok(()) }
/// ```
///
/// By default the write replaces a regular file and keeps that file's own
/// permissions; a new file starts owner-only on Unix. The options:
///
/// - [`mode`](Self::mode) sets explicit permission bits on the new file, over
///   either default. Unix only: Windows has no mode bits, so the method does
///   not exist there and a caller that needs one writes the `cfg(unix)` itself
///   rather than have the request silently ignored. A new Windows file takes
///   the directory's inherited ACL.
/// - [`new_only`](Self::new_only) refuses an existing target of any kind. The
///   target is never touched; the refusal is
///   [`AtomicError::target_exists`].
///
/// Every form keeps the full sequence: private same-directory temporary file,
/// write, permissions, file fsync, atomic install, directory fsync.
#[derive(Debug, Clone)]
pub struct AtomicWrite<'a> {
    bytes: &'a [u8],
    install_mode: InstallMode,
    unix_mode: Option<u32>,
    /// `Some` when the caller has already inspected the target under its own
    /// policy and hands over the metadata to keep; `None` lets
    /// [`write`](Self::write) inspect it.
    caller_guarded: Option<Option<fs::Metadata>>,
}

impl<'a> AtomicWrite<'a> {
    /// A write of the complete new contents with the default behavior.
    pub fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            install_mode: InstallMode::Replace,
            unix_mode: None,
            caller_guarded: None,
        }
    }

    /// Give the new file these permission bits (`0o600`), overriding both the
    /// replaced file's permissions and the owner-only default. Unix only.
    #[cfg(unix)]
    #[must_use]
    pub fn mode(mut self, bits: u32) -> Self {
        self.unix_mode = Some(bits);
        self
    }

    /// Refuse an existing target instead of replacing it. The refusal is
    /// reported by [`AtomicError::target_exists`], including when the name is
    /// taken between the check and the install.
    #[must_use]
    pub fn new_only(mut self) -> Self {
        self.install_mode = InstallMode::NewOnly;
        self
    }

    /// Write `self` to `path`. Every failure before the install leaves the
    /// original untouched and removes the temporary file. A failure at the
    /// final parent directory fsync — the one [`AtomicError::commit_uncertain`]
    /// reports — means the new file may already be in place without confirmed
    /// durability.
    pub fn write(self, path: &Path) -> Result<(), AtomicError> {
        self.write_with(path, |file, bytes| file.write_all(bytes))
    }

    /// Crate-internal: set unix bits without the `cfg(unix)` the public
    /// [`mode`](Self::mode) carries; ignored where the platform has none.
    pub(crate) fn with_unix_mode(mut self, unix_mode: Option<u32>) -> Self {
        self.unix_mode = unix_mode;
        self
    }

    /// Crate-internal: the caller already guarded the target under its own
    /// policy (what may be overwritten differs between writers) and supplies
    /// its metadata for ownership and permission preservation.
    pub(crate) fn with_target_metadata(mut self, metadata: Option<fs::Metadata>) -> Self {
        self.caller_guarded = Some(metadata);
        self
    }

    fn write_with(
        mut self,
        path: &Path,
        write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
    ) -> Result<(), AtomicError> {
        validate_unix_mode(self.unix_mode)
            .map_err(|error| AtomicError::at(AtomicStep::Guard, path, error))?;
        if let Some(metadata) = self.caller_guarded.take() {
            return install_with_writer(path, &self, metadata, write);
        }
        // A new-only write never looks at the target: whatever is there, even a
        // symlink or directory, is "exists" and is refused by the install.
        let metadata = if self.install_mode == InstallMode::NewOnly {
            None
        } else {
            match fs::symlink_metadata(path) {
                Ok(metadata) if metadata.file_type().is_file() => Some(metadata),
                Ok(_) => {
                    return Err(AtomicError::at(
                        AtomicStep::Guard,
                        path,
                        std::io::Error::new(
                            std::io::ErrorKind::InvalidInput,
                            "atomic target must be a regular file, not a symlink, directory, or special file",
                        ),
                    ));
                }
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
                Err(error) => return Err(AtomicError::at(AtomicStep::Guard, path, error)),
            }
        };
        install_with_writer(path, &self, metadata, write)
    }
}

/// The step of an atomic installation that failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AtomicStep {
    /// Inspecting the target without following links.
    Guard,
    /// The target has no parent directory to write the temporary file into.
    NoParent,
    /// The target's own file name is not valid UTF-8.
    NonUtf8Name,
    /// Creating the private temporary file.
    Temp,
    /// Every candidate temporary name was taken.
    TempExhausted,
    /// Writing the new bytes.
    Write,
    /// Re-applying the replaced file's permissions.
    PreservePermissions,
    /// Re-applying the replaced file's Unix owner and group: a group the mode
    /// grants access to must be kept, an owner only where the process may.
    #[cfg(unix)]
    PreserveOwnership,
    /// Applying explicitly requested permission bits. Unix only, because the
    /// bits themselves are: the step does not exist on a platform that has no
    /// mode to set, and a variant no code can construct is a step a reader
    /// would look for and never find.
    #[cfg(unix)]
    SetPermissions,
    /// Flushing the temporary file to storage.
    Sync,
    /// Installing the temporary file over the target.
    Install,
    /// Recording the new directory entry.
    SyncParent,
}

/// A failed atomic installation: which step, which path, and the OS error.
#[derive(Debug)]
pub struct AtomicError {
    /// The step that failed.
    pub step: AtomicStep,
    /// The path that step was about — the target, its temporary file, or the
    /// parent directory, depending on the step.
    pub path: PathBuf,
    /// The underlying OS error, absent only where the step had none.
    pub source: Option<std::io::Error>,
}

impl AtomicError {
    fn at(step: AtomicStep, path: &Path, source: std::io::Error) -> Self {
        Self {
            step,
            path: path.to_path_buf(),
            source: Some(source),
        }
    }

    /// Whether this is a [`new_only`](AtomicWrite::new_only) write refusing an
    /// existing target, which is a caller-visible outcome rather than an I/O
    /// fault. The target was not touched. Never true for a replacing write.
    pub fn target_exists(&self) -> bool {
        self.step == AtomicStep::Install
            && self
                .source
                .as_ref()
                .is_some_and(|error| error.kind() == std::io::ErrorKind::AlreadyExists)
    }

    /// Whether the target may already carry the new bytes.
    ///
    /// Only the final directory fsync can fail after the installation itself
    /// succeeded: the file is complete and in place, but its survival across a
    /// crash is unconfirmed. Every other step fails before the install and
    /// leaves the original untouched.
    pub fn commit_uncertain(&self) -> bool {
        self.step == AtomicStep::SyncParent
    }
}

impl std::fmt::Display for AtomicError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let path = self.path.display();
        let phrase = match self.step {
            AtomicStep::Guard => "inspect",
            AtomicStep::NoParent => {
                return write!(formatter, "has no parent directory for `{path}`");
            }
            AtomicStep::NonUtf8Name => {
                return write!(formatter, "path is not valid UTF-8: `{path}`");
            }
            AtomicStep::TempExhausted => {
                return write!(formatter, "could not allocate temporary file in `{path}`");
            }
            AtomicStep::Temp => "temporary file in",
            AtomicStep::Write => "write",
            #[cfg(unix)]
            AtomicStep::PreserveOwnership => "preserve owner and group of",
            AtomicStep::PreservePermissions => "preserve permissions",
            #[cfg(unix)]
            AtomicStep::SetPermissions => "set permissions on",
            AtomicStep::Sync => "fsync",
            AtomicStep::Install => "install",
            AtomicStep::SyncParent => "fsync parent directory",
        };
        write!(formatter, "{phrase} `{path}`")?;
        match &self.source {
            Some(source) => write!(formatter, ": {source}"),
            None => Ok(()),
        }
    }
}

/// The smallest `NAME_MAX` across the platforms this runs on.
const MAX_NAME_BYTES: usize = 255;

/// Compose a temporary file name that stays within one path component's limit.
///
/// The marker, pid, and attempt add about 35 bytes. A target whose own name is
/// close to `NAME_MAX` would push the composed name past it, and the failure
/// would surface at install time — after the caller had already done its work,
/// on a file it opened successfully. Truncating the stem keeps the write
/// possible; uniqueness still comes from the pid and attempt, with `create_new`
/// retrying the rare collision.
fn temp_file_name(file_name: &str, pid: u32, attempt: u32) -> String {
    let suffix = format!(".afdata.{pid}.{attempt}.tmp");
    // One byte for the leading dot that hides the temporary file.
    let budget = MAX_NAME_BYTES.saturating_sub(suffix.len() + 1);
    let stem = &file_name[..file_name.floor_char_boundary(budget)];
    format!(".{stem}{suffix}")
}

/// Split a target into the directory the temporary file must share with it and
/// the target's own name. Sharing the directory is what makes the final install
/// a rename within one filesystem, which is the atomic operation this relies on.
fn parent_and_name(path: &Path) -> Result<(&Path, String), AtomicError> {
    let parent = match path.parent() {
        Some(parent) if parent.as_os_str().is_empty() => Path::new("."),
        Some(parent) => parent,
        None => {
            return Err(AtomicError {
                step: AtomicStep::NoParent,
                path: path.to_path_buf(),
                source: None,
            });
        }
    };
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| AtomicError {
            step: AtomicStep::NonUtf8Name,
            path: path.to_path_buf(),
            source: None,
        })?
        .to_string();
    Ok((parent, file_name))
}

fn allocate_private_temp(parent: &Path, file_name: &str) -> Result<(PathBuf, File), AtomicError> {
    let pid = std::process::id();
    for attempt in 0..32_u32 {
        let candidate = parent.join(temp_file_name(file_name, pid, attempt));
        let mut options = OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt as _;
            // Nothing may read the new contents through the temporary name
            // before the caller's own permissions are applied below.
            options.mode(0o600);
        }
        match options.open(&candidate) {
            Ok(file) => return Ok((candidate, file)),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(AtomicError::at(AtomicStep::Temp, parent, error)),
        }
    }
    Err(AtomicError {
        step: AtomicStep::TempExhausted,
        path: parent.to_path_buf(),
        source: None,
    })
}

#[cfg(unix)]
fn sync_parent(parent: &Path) -> Result<(), AtomicError> {
    File::open(parent)
        .and_then(|directory| directory.sync_all())
        .map_err(|error| AtomicError::at(AtomicStep::SyncParent, parent, error))
}

#[cfg(not(unix))]
fn sync_parent(_parent: &Path) -> Result<(), AtomicError> {
    // Rust does not expose a portable directory handle on non-unix targets.
    // The file itself is still synced before its atomic installation.
    Ok(())
}

/// Give the temporary file the replaced file's owner and group, as far as that
/// keeps access where it was.
///
/// The owner is restored when the process may; a writer that is not the owner
/// cannot give a file away, and becoming its owner widens nothing, because the
/// owner bits then apply to the one who could already write it. The group is
/// different: installed under another group, the group bits would hand this
/// content to that group. So a group that cannot be restored refuses the write,
/// unless the final `mode` grants the group nothing.
#[cfg(unix)]
fn preserve_ownership(file: &File, target: &fs::Metadata, mode: u32) -> std::io::Result<()> {
    use std::os::unix::fs::{MetadataExt as _, fchown};
    let current = file.metadata()?;
    let uid = (current.uid() != target.uid()).then_some(target.uid());
    let gid = (current.gid() != target.gid()).then_some(target.gid());
    if uid.is_none() && gid.is_none() {
        return Ok(());
    }
    let denied = |error: &std::io::Error| error.kind() == std::io::ErrorKind::PermissionDenied;
    let result = match fchown(file, uid, gid) {
        Err(error) if uid.is_some() && gid.is_some() && denied(&error) => fchown(file, None, gid),
        Err(error) if uid.is_some() && gid.is_none() && denied(&error) => Ok(()),
        other => other,
    };
    match result {
        Err(error) if mode & 0o070 == 0 && denied(&error) => Ok(()),
        other => other,
    }
}

fn write_temp(
    mut temp_file: File,
    temp_path: &Path,
    target: &Path,
    request: &AtomicWrite<'_>,
    metadata: Option<fs::Metadata>,
    write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
) -> Result<(), AtomicError> {
    write(&mut temp_file, request.bytes)
        .map_err(|error| AtomicError::at(AtomicStep::Write, target, error))?;
    if let Some(metadata) = metadata {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let mode = request
                .unix_mode
                .unwrap_or_else(|| metadata.permissions().mode());
            preserve_ownership(&temp_file, &metadata, mode)
                .map_err(|error| AtomicError::at(AtomicStep::PreserveOwnership, target, error))?;
        }
        if request.unix_mode.is_none() {
            temp_file
                .set_permissions(metadata.permissions())
                .map_err(|error| AtomicError::at(AtomicStep::PreservePermissions, target, error))?;
        }
    }
    #[cfg(unix)]
    if let Some(unix_mode) = request.unix_mode {
        use std::os::unix::fs::PermissionsExt as _;
        temp_file
            .set_permissions(fs::Permissions::from_mode(unix_mode))
            .map_err(|error| AtomicError::at(AtomicStep::SetPermissions, target, error))?;
    }
    temp_file
        .sync_all()
        .map_err(|error| AtomicError::at(AtomicStep::Sync, temp_path, error))
}

/// Install `request` at `path` atomically, with the caller's own guard already
/// decided: `metadata` belongs to the replaced file.
///
// The writer seam keeps disk-full, short-write, and interrupted-process
// regressions at the primitive that owns publication, without exposing a
// callback or partial-file API to callers.
fn install_with_writer(
    path: &Path,
    request: &AtomicWrite<'_>,
    metadata: Option<fs::Metadata>,
    write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
) -> Result<(), AtomicError> {
    let (parent, file_name) = parent_and_name(path)?;
    let (temp_path, temp_file) = allocate_private_temp(parent, &file_name)?;
    let result = (|| -> Result<(), AtomicError> {
        write_temp(temp_file, &temp_path, path, request, metadata, write)?;
        match request.install_mode {
            InstallMode::Replace => {
                fs::rename(&temp_path, path)
                    .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
            }
            InstallMode::NewOnly => {
                fs::hard_link(&temp_path, path)
                    .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
                // The file is installed from here on. Failing to unlink the
                // temporary link leaves a stray file, but reporting an error
                // would tell the caller the commit did not happen — and a retry
                // would then refuse a target that this call in fact created.
                let _ = fs::remove_file(&temp_path);
            }
        }
        sync_parent(parent)?;
        Ok(())
    })();
    if let Err(error) = &result {
        // A parent-directory fsync failure comes after the install, where the
        // temporary name no longer refers to anything to clean up.
        if !error.commit_uncertain() {
            let _ = fs::remove_file(&temp_path);
        }
    }
    result
}

impl std::error::Error for AtomicError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().map(|error| error as _)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
    use super::*;

    #[test]
    fn temp_name_stays_within_one_path_component() {
        let long = "x".repeat(400);
        let name = temp_file_name(&long, 1234, 0);
        assert!(name.len() <= MAX_NAME_BYTES, "{} bytes", name.len());
        assert!(name.starts_with('.'));
        assert!(name.ends_with(".tmp"));
    }

    #[test]
    fn temp_name_truncates_on_a_character_boundary() {
        let long = "é".repeat(300);
        let name = temp_file_name(&long, 1234, 0);
        assert!(name.is_char_boundary(name.len()));
        assert!(name.len() <= MAX_NAME_BYTES);
    }

    #[test]
    fn bare_relative_paths_use_the_current_directory() {
        let (parent, file_name) = parent_and_name(Path::new("config.json")).unwrap();

        assert_eq!(parent, Path::new("."));
        assert_eq!(file_name, "config.json");
    }

    #[test]
    fn replace_installs_new_bytes_and_leaves_no_temporary_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        fs::write(&path, b"old").unwrap();

        AtomicWrite::new(b"new").write(&path).unwrap();

        assert_eq!(fs::read(&path).unwrap(), b"new");
        let strays: Vec<_> = fs::read_dir(dir.path())
            .unwrap()
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
            .collect();
        assert!(strays.is_empty(), "temporary files left behind");
    }

    #[test]
    fn new_only_refuses_an_existing_target_without_touching_it() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        fs::write(&path, b"original").unwrap();

        let error = AtomicWrite::new(b"new")
            .new_only()
            .write(&path)
            .unwrap_err();

        assert!(error.target_exists());
        assert_eq!(fs::read(&path).unwrap(), b"original");
    }

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

        let dir = tempfile::tempdir().unwrap();
        let outside = dir.path().join("outside.txt");
        fs::write(&outside, b"untouched").unwrap();
        let link = dir.path().join("link.txt");
        symlink(&outside, &link).unwrap();

        AtomicWrite::new(b"new")
            .with_target_metadata(None)
            .write(&link)
            .unwrap();

        assert_eq!(fs::read(&outside).unwrap(), b"untouched");
        assert!(
            !fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(fs::read(&link).unwrap(), b"new");
    }

    #[cfg(unix)]
    #[test]
    fn explicit_unix_mode_wins_over_the_private_temporary_mode() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("readable.md");

        AtomicWrite::new(b"body").mode(0o644).write(&path).unwrap();

        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o644);
    }

    #[test]
    fn a_missing_parent_directory_fails_before_any_write() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("absent").join("config.json");

        let error = AtomicWrite::new(b"new").write(&path).unwrap_err();

        assert_eq!(error.step, AtomicStep::Temp);
        assert!(!error.commit_uncertain());
        assert!(!path.exists());
    }
    #[test]
    fn failed_writes_preserve_previous_bytes_and_remove_temporary_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.json");
        fs::write(&path, b"old complete value").unwrap();
        for error in [
            std::io::Error::from_raw_os_error(28),
            std::io::Error::from(std::io::ErrorKind::Interrupted),
            std::io::Error::from(std::io::ErrorKind::WriteZero),
        ] {
            let error = AtomicWrite::new(b"new")
                .write_with(&path, |file, _| {
                    file.write_all(b"partial")?;
                    Err(error)
                })
                .unwrap_err();
            assert_eq!(error.step, AtomicStep::Write);
            assert!(!error.commit_uncertain());
            assert_eq!(fs::read(&path).unwrap(), b"old complete value");
            assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
        }
    }

    /// Metadata of a file whose owner and group this process cannot take on,
    /// or `None` on a runner privileged enough to apply them.
    #[cfg(unix)]
    fn foreign_ownership(probe: &Path) -> Option<fs::Metadata> {
        use std::os::unix::fs::MetadataExt as _;
        let foreign = fs::metadata("/").unwrap();
        if fs::metadata(probe).unwrap().uid() == foreign.uid()
            || std::os::unix::fs::chown(probe, None, Some(foreign.gid())).is_ok()
        {
            return None;
        }
        Some(foreign)
    }

    #[cfg(unix)]
    #[test]
    fn refused_ownership_change_does_not_install_the_temporary_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.json");
        fs::write(&path, b"old complete value").unwrap();
        let Some(foreign) = foreign_ownership(&path) else {
            return;
        };
        // `/` grants its group access, so a group this process cannot keep
        // would hand the new contents to a different group.
        let error = AtomicWrite::new(b"new complete value")
            .with_target_metadata(Some(foreign))
            .write(&path)
            .unwrap_err();
        assert_eq!(error.step, AtomicStep::PreserveOwnership);
        assert!(!error.commit_uncertain());
        assert_eq!(fs::read(&path).unwrap(), b"old complete value");
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    #[cfg(unix)]
    #[test]
    fn unkeepable_ownership_is_accepted_when_the_mode_grants_the_group_nothing() {
        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.json");
        fs::write(&path, b"old complete value").unwrap();
        let Some(foreign) = foreign_ownership(&path) else {
            return;
        };
        let before = fs::metadata(&path).unwrap();
        AtomicWrite::new(b"new complete value")
            .with_target_metadata(Some(foreign))
            .mode(0o600)
            .write(&path)
            .unwrap();
        let after = fs::metadata(&path).unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"new complete value");
        assert_eq!((after.uid(), after.gid()), (before.uid(), before.gid()));
        assert_eq!(after.permissions().mode() & 0o777, 0o600);
    }

    #[test]
    fn write_all_retries_short_writes_and_interruptions_before_publish() {
        struct ShortWriter<'a> {
            file: &'a mut File,
            interrupted: bool,
        }
        impl std::io::Write for ShortWriter<'_> {
            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
                if !self.interrupted {
                    self.interrupted = true;
                    return Err(std::io::ErrorKind::Interrupted.into());
                }
                self.file.write(&bytes[..bytes.len().min(2)])
            }
            fn flush(&mut self) -> std::io::Result<()> {
                self.file.flush()
            }
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.json");
        let bytes = b"new complete value";
        AtomicWrite::new(bytes)
            .write_with(&path, |file, bytes| {
                ShortWriter {
                    file,
                    interrupted: false,
                }
                .write_all(bytes)
            })
            .unwrap();
        assert_eq!(fs::read(&path).unwrap(), bytes);
    }

    #[test]
    fn interrupted_process_leaves_uncommitted_temporary_file_not_target() {
        const CHILD_PATH: &str = "AFDATA_TEST_INTERRUPTED_ATOMIC_PATH";
        if let Some(path) = std::env::var_os(CHILD_PATH) {
            let _ = AtomicWrite::new(b"new").write_with(Path::new(&path), |file, _| {
                file.write_all(b"partial")?;
                file.sync_all()?;
                std::process::exit(86);
            });
            panic!("child did not reach the interrupted write");
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.json");
        write_atomic(&path, b"old complete value").unwrap();
        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "atomic_file::tests::interrupted_process_leaves_uncommitted_temporary_file_not_target"])
            .env(CHILD_PATH, &path).status().unwrap();
        assert_eq!(status.code(), Some(86));
        assert_eq!(fs::read(&path).unwrap(), b"old complete value");
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
        write_atomic(&path, b"new complete value").unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"new complete value");
    }

    #[cfg(unix)]
    #[test]
    fn public_write_refuses_a_symlink_target() {
        let dir = tempfile::tempdir().unwrap();
        let outside = dir.path().join("outside");
        fs::write(&outside, b"untouched").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&outside, &link).unwrap();
        let error = AtomicWrite::new(b"x").write(&link).unwrap_err();
        assert_eq!(error.step, AtomicStep::Guard);
        assert_eq!(fs::read(&outside).unwrap(), b"untouched");
    }

    #[cfg(unix)]
    fn mode_of(path: &Path) -> u32 {
        use std::os::unix::fs::PermissionsExt as _;
        fs::metadata(path).unwrap().permissions().mode() & 0o777
    }

    #[cfg(unix)]
    #[test]
    fn mode_applies_to_a_new_file_and_overrides_an_existing_one() {
        let dir = tempfile::tempdir().unwrap();
        let fresh = dir.path().join("fresh");
        AtomicWrite::new(b"x").mode(0o640).write(&fresh).unwrap();
        assert_eq!(mode_of(&fresh), 0o640);

        let existing = dir.path().join("existing");
        write_atomic(&existing, b"old").unwrap();
        AtomicWrite::new(b"new")
            .mode(0o604)
            .write(&existing)
            .unwrap();
        assert_eq!(mode_of(&existing), 0o604);
        assert_eq!(fs::read(&existing).unwrap(), b"new");
    }

    #[cfg(unix)]
    #[test]
    fn default_write_keeps_existing_mode_and_starts_new_files_private() {
        use std::os::unix::fs::PermissionsExt as _;
        let dir = tempfile::tempdir().unwrap();
        let existing = dir.path().join("existing");
        fs::write(&existing, b"old").unwrap();
        fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
        write_atomic(&existing, b"new").unwrap();
        assert_eq!(mode_of(&existing), 0o644);

        let fresh = dir.path().join("fresh");
        write_atomic(&fresh, b"x").unwrap();
        assert_eq!(mode_of(&fresh), 0o600);
    }

    #[test]
    fn new_only_creates_an_absent_target_and_leaves_no_temporary_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("fresh.json");
        AtomicWrite::new(b"created")
            .new_only()
            .write(&path)
            .unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"created");
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    #[test]
    fn public_new_only_refuses_an_existing_target_byte_identical() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("keep.json");
        fs::write(&path, b"original").unwrap();
        let error = AtomicWrite::new(b"other")
            .new_only()
            .write(&path)
            .unwrap_err();
        assert!(error.target_exists());
        assert!(!error.commit_uncertain());
        assert_eq!(fs::read(&path).unwrap(), b"original");
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
    }
}