heddle-objects 0.2.1

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
use std::{
    fs::{self, OpenOptions},
    io::{self, Write},
    path::{Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
    time::{SystemTime, UNIX_EPOCH},
};

static TEMP_PATH_COUNTER: AtomicU64 = AtomicU64::new(0);

/// POSIX `ENOSPC`. Identical on Linux and macOS. Windows surfaces disk-full
/// as `ERROR_DISK_FULL` (112) or `ERROR_HANDLE_DISK_FULL` (39); we cover
/// those by also checking `ErrorKind::StorageFull` (stable as of 1.83) and
/// the older `ErrorKind::Other` "no space" message text as a fallback.
const ENOSPC: i32 = 28;

/// POSIX `ENOTEMPTY`. Linux=39, macOS/BSD=66. Windows surfaces this as
/// `ERROR_DIR_NOT_EMPTY` (145). `ErrorKind::DirectoryNotEmpty` covers the
/// portable case, but the raw codes are the canonical signal — Rust may
/// still surface raw OS errors for paths the kernel reports unusually.
const ENOTEMPTY_LINUX: i32 = 39;
const ENOTEMPTY_MACOS: i32 = 66;
const ENOTEMPTY_WINDOWS: i32 = 145;

/// POSIX `EACCES`. Same code on Linux and macOS. `ErrorKind::PermissionDenied`
/// covers Windows `ERROR_ACCESS_DENIED` (5) too.
const EACCES: i32 = 13;

/// POSIX `ENOENT`. Same code on Linux and macOS. `ErrorKind::NotFound` covers
/// Windows `ERROR_FILE_NOT_FOUND` (2) and `ERROR_PATH_NOT_FOUND` (3).
const ENOENT: i32 = 2;

/// POSIX `EROFS`. Linux=30, macOS=30. `ErrorKind::ReadOnlyFilesystem` is
/// the portable variant (stable as of 1.83).
const EROFS: i32 = 30;

/// POSIX `EXDEV` ("cross-device link"). Linux=18, macOS=18.
/// `ErrorKind::CrossesDevices` is the portable variant (stable as of 1.83).
const EXDEV: i32 = 18;

/// Returns true when an `io::Error` indicates the filesystem is out of
/// space. Centralised here because it's the same predicate used by
/// `write_file_atomic` (the inner helper) and by the higher-level
/// `cmd_snapshot` recovery path that prints the actionable message.
pub fn is_out_of_space(err: &io::Error) -> bool {
    if err.raw_os_error() == Some(ENOSPC) {
        return true;
    }
    // `ErrorKind::StorageFull` is the portable kind. It maps to ENOSPC
    // on Unix and the Windows disk-full codes. Available since Rust
    // 1.83; the workspace MSRV is well past that.
    if err.kind() == io::ErrorKind::StorageFull {
        return true;
    }
    // `write_all` translates a short write into `WriteZero`. On a full
    // disk, kernel can return a short write rather than ENOSPC outright
    // (especially over network filesystems), so a `WriteZero` we couldn't
    // otherwise classify is treated as out-of-space — overly inclusive
    // here is safer than missing the signal.
    if err.kind() == io::ErrorKind::WriteZero {
        return true;
    }
    false
}

/// Returns true when an `io::Error` indicates a directory could not be
/// removed because it still contained entries. The apply planner
/// intentionally skips heddle-ignored entries (`.git/`, `target/`,
/// `node_modules/`, etc.); when tracked content is removed and the parent
/// directory still holds those ignored siblings, `remove_dir` returns
/// this signal. We need both `ErrorKind::DirectoryNotEmpty` and the raw
/// codes — Linux=39, macOS/BSD=66, Windows=145 — because Rust does not
/// always translate every kernel surface into the portable `ErrorKind`.
pub fn is_directory_not_empty(err: &io::Error) -> bool {
    if err.kind() == io::ErrorKind::DirectoryNotEmpty {
        return true;
    }
    matches!(
        err.raw_os_error(),
        Some(ENOTEMPTY_LINUX) | Some(ENOTEMPTY_MACOS) | Some(ENOTEMPTY_WINDOWS)
    )
}

/// Returns true when an `io::Error` indicates the operation was denied
/// for permissions reasons (`EACCES` on Unix, `ERROR_ACCESS_DENIED` on
/// Windows). The portable `ErrorKind::PermissionDenied` covers most
/// surfaces; the raw `EACCES` check handles oddball platforms that
/// surface the OS code without translating to the portable kind.
pub fn is_permission_denied(err: &io::Error) -> bool {
    if err.kind() == io::ErrorKind::PermissionDenied {
        return true;
    }
    err.raw_os_error() == Some(EACCES)
}

/// Returns true when an `io::Error` indicates the path referenced by an
/// operation does not exist (`ENOENT` on Unix, `ERROR_FILE_NOT_FOUND` /
/// `ERROR_PATH_NOT_FOUND` on Windows). Use this *only* at call sites
/// where the operation expected the path to exist — the predicate alone
/// can't distinguish "I expected this" from "I checked optionally".
pub fn is_not_found(err: &io::Error) -> bool {
    if err.kind() == io::ErrorKind::NotFound {
        return true;
    }
    err.raw_os_error() == Some(ENOENT)
}

/// Returns true when an `io::Error` indicates the underlying filesystem
/// is mounted read-only (`EROFS` on Unix). The portable
/// `ErrorKind::ReadOnlyFilesystem` is preferred when present; we also
/// match the raw OS code because some platforms (notably older macOS
/// surfaces and certain remote filesystems) do not always translate.
pub fn is_read_only_filesystem(err: &io::Error) -> bool {
    if err.kind() == io::ErrorKind::ReadOnlyFilesystem {
        return true;
    }
    err.raw_os_error() == Some(EROFS)
}

/// Returns true when an `io::Error` indicates a `rename` (or other
/// link-style operation) attempted to bridge two filesystems (`EXDEV`).
/// This is what trips when `temp_path` lands on a different mount than
/// the destination — typically because `TMPDIR` is on a different volume,
/// or the parent directory itself is a bind mount. We match both the
/// portable `ErrorKind::CrossesDevices` and the raw `EXDEV` code.
pub fn is_cross_device_link(err: &io::Error) -> bool {
    if err.kind() == io::ErrorKind::CrossesDevices {
        return true;
    }
    err.raw_os_error() == Some(EXDEV)
}

pub fn temp_path(path: &Path) -> PathBuf {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let file_name = path
        .file_name()
        .and_then(|s| s.to_str())
        .filter(|s| !s.is_empty())
        .unwrap_or("heddle-tmp");
    let unique = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let counter = TEMP_PATH_COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    parent.join(format!(".{file_name}.tmp-{pid}-{unique}-{counter}"))
}

pub fn sync_directory(path: &Path) -> io::Result<()> {
    let dir = OpenOptions::new().read(true).open(path)?;
    dir.sync_all()
}

/// Wrap an `io::Error` raised while writing `path` so that ENOSPC carries
/// an actionable message naming the path. Non-ENOSPC errors pass through
/// unchanged. The wrapped error's `raw_os_error()` still returns 28, and
/// [`is_out_of_space`] still detects it — callers (e.g. `cmd_snapshot`)
/// rely on this for stable exit-code mapping.
///
/// Thin wrapper over [`enrich_fs_error`] for the historical "writing"
/// call sites. New code should prefer `enrich_fs_error(path, "writing", err)`
/// directly so the operation name is explicit at the call site.
fn enrich_write_error(path: &Path, err: io::Error) -> io::Error {
    enrich_fs_error(path, "writing", err)
}

/// Wrap an `io::Error` produced by a filesystem operation against `path`
/// with a heddle-context message naming both the operation and the path.
///
/// The mapping covers the cases users actually hit and the messages we
/// promise from heddle's CLI surface:
/// - **ENOTEMPTY** — usually `remove_dir` against a directory that still
///   holds heddle-ignored content (`.git/`, `target/`, `node_modules/`).
///   The high-level fix is to leave the directory in place, but when the
///   error does surface (e.g. a path the planner *did* expect to remove),
///   the message names the path so the user can investigate.
/// - **EACCES** — naming the path and the action ("removing", "writing",
///   "renaming") is enough for the user to inspect mode bits.
/// - **ENOENT** — caller-driven: only enriched when the operation
///   expected the path to exist (so optional reads like a missing index
///   pass through unchanged via the `is_not_found` predicate).
/// - **EROFS** — points the user at the filesystem mount, not at heddle.
/// - **EXDEV** — points the user at the temp path / mount mismatch.
/// - **ENOSPC** — same actionable disk-full message the snapshot path
///   already relies on.
///
/// `op` is a verb in the present-progressive ("writing", "removing",
/// "renaming", "creating") so the resulting message reads naturally:
///   `"could not remove `<path>` because it contains content..."`.
///
/// The wrapped error preserves `raw_os_error()` (callers still classify
/// disk-full via [`is_out_of_space`]) and exposes the original `io::Error`
/// through the `Error::source` chain (so `RUST_BACKTRACE=1` and
/// `anyhow`'s chain printer still surface the OS error).
pub fn enrich_fs_error(path: &Path, op: &'static str, err: io::Error) -> io::Error {
    if is_out_of_space(&err) {
        let msg = format!(
            "out of disk space {op} {}: free disk space and re-run the command — your working tree is unchanged",
            path.display()
        );
        return io::Error::new(
            io::ErrorKind::StorageFull,
            EnrichedFsError { msg, source: err },
        );
    }
    if is_directory_not_empty(&err) {
        let msg = format!(
            "could not remove directory `{}` because it contains content (heddle-ignored or otherwise) — leaving in place",
            path.display()
        );
        return io::Error::new(
            io::ErrorKind::DirectoryNotEmpty,
            EnrichedFsError { msg, source: err },
        );
    }
    if is_read_only_filesystem(&err) {
        let msg = format!(
            "filesystem is read-only — `{}` cannot be modified",
            path.display()
        );
        return io::Error::new(
            io::ErrorKind::ReadOnlyFilesystem,
            EnrichedFsError { msg, source: err },
        );
    }
    if is_permission_denied(&err) {
        let msg = format!(
            "permission denied {op} `{}` — check filesystem permissions",
            path.display()
        );
        return io::Error::new(
            io::ErrorKind::PermissionDenied,
            EnrichedFsError { msg, source: err },
        );
    }
    if is_not_found(&err) {
        let msg = format!("could not find `{}` for {op}", path.display());
        return io::Error::new(
            io::ErrorKind::NotFound,
            EnrichedFsError { msg, source: err },
        );
    }
    if is_cross_device_link(&err) {
        let msg = format!(
            "cannot rename across filesystems — temp file for `{}` lives on a different mount; set TMPDIR to the same filesystem as the destination",
            path.display()
        );
        return io::Error::new(
            io::ErrorKind::CrossesDevices,
            EnrichedFsError { msg, source: err },
        );
    }
    err
}

/// Wrap an `EXDEV` error from `fs::rename` with both the source temp path
/// and the destination — the user needs both to understand which mount
/// boundary the rename tripped on. Other error kinds delegate to
/// [`enrich_fs_error`] using the destination as the principal path.
pub fn enrich_rename_error(src: &Path, dst: &Path, err: io::Error) -> io::Error {
    if is_cross_device_link(&err) {
        let msg = format!(
            "cannot rename across filesystems — temp file at `{}` cannot be renamed to `{}`; set TMPDIR to the same filesystem as the destination",
            src.display(),
            dst.display()
        );
        return io::Error::new(
            io::ErrorKind::CrossesDevices,
            EnrichedFsError { msg, source: err },
        );
    }
    enrich_fs_error(dst, "renaming", err)
}

#[derive(Debug)]
struct EnrichedFsError {
    msg: String,
    source: io::Error,
}

impl std::fmt::Display for EnrichedFsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for EnrichedFsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

pub fn write_file_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(parent).map_err(|e| enrich_fs_error(parent, "creating", e))?;

    let tmp = temp_path(path);
    let inner = (|| -> io::Result<()> {
        let mut file = OpenOptions::new()
            .create(true)
            .truncate(true)
            .write(true)
            .open(&tmp)?;
        file.write_all(bytes)?;
        file.sync_all()?;
        Ok(())
    })();

    if let Err(err) = inner {
        // Best-effort cleanup. On ENOSPC the tempfile may itself be the
        // cause of the disk pressure; removing it gives the user back
        // some slack before they re-run.
        let _ = fs::remove_file(&tmp);
        return Err(enrich_write_error(path, err));
    }

    fs::rename(&tmp, path).map_err(|e| enrich_rename_error(&tmp, path, e))?;
    sync_directory(parent).map_err(|e| enrich_fs_error(parent, "syncing", e))
}

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

    fn enospc_io_error() -> io::Error {
        io::Error::from_raw_os_error(ENOSPC)
    }

    #[test]
    fn is_out_of_space_detects_enospc_raw() {
        assert!(is_out_of_space(&enospc_io_error()));
    }

    #[test]
    fn is_out_of_space_detects_storage_full_kind() {
        let err = io::Error::new(io::ErrorKind::StorageFull, "mock disk full");
        assert!(is_out_of_space(&err));
    }

    #[test]
    fn is_out_of_space_detects_write_zero() {
        let err = io::Error::new(io::ErrorKind::WriteZero, "short write");
        assert!(is_out_of_space(&err));
    }

    #[test]
    fn is_out_of_space_rejects_unrelated_errors() {
        assert!(!is_out_of_space(&io::Error::new(
            io::ErrorKind::NotFound,
            "missing"
        )));
        assert!(!is_out_of_space(&io::Error::new(
            io::ErrorKind::PermissionDenied,
            "nope"
        )));
        assert!(!is_out_of_space(&io::Error::other("generic")));
    }

    #[test]
    fn is_directory_not_empty_detects_kind() {
        let err = io::Error::new(io::ErrorKind::DirectoryNotEmpty, "still has children");
        assert!(is_directory_not_empty(&err));
    }

    #[test]
    fn is_directory_not_empty_detects_raw_codes() {
        for code in [ENOTEMPTY_LINUX, ENOTEMPTY_MACOS, ENOTEMPTY_WINDOWS] {
            assert!(
                is_directory_not_empty(&io::Error::from_raw_os_error(code)),
                "expected raw OS error {code} to classify as ENOTEMPTY"
            );
        }
    }

    #[test]
    fn is_directory_not_empty_rejects_unrelated() {
        assert!(!is_directory_not_empty(&io::Error::new(
            io::ErrorKind::NotFound,
            "missing"
        )));
        assert!(!is_directory_not_empty(&enospc_io_error()));
    }

    #[test]
    fn is_permission_denied_detects_kind_and_raw() {
        assert!(is_permission_denied(&io::Error::new(
            io::ErrorKind::PermissionDenied,
            "nope"
        )));
        assert!(is_permission_denied(&io::Error::from_raw_os_error(EACCES)));
    }

    #[test]
    fn is_not_found_detects_kind_and_raw() {
        assert!(is_not_found(&io::Error::new(
            io::ErrorKind::NotFound,
            "missing"
        )));
        assert!(is_not_found(&io::Error::from_raw_os_error(ENOENT)));
    }

    #[test]
    fn is_read_only_filesystem_detects_raw() {
        assert!(is_read_only_filesystem(&io::Error::from_raw_os_error(
            EROFS
        )));
    }

    #[test]
    fn is_cross_device_link_detects_raw() {
        assert!(is_cross_device_link(&io::Error::from_raw_os_error(EXDEV)));
    }

    #[test]
    fn enrich_fs_error_passes_through_unclassified() {
        let path = Path::new("/tmp/example");
        let original = io::Error::other("weird");
        let wrapped = enrich_fs_error(path, "writing", original);
        // Unclassified errors are returned untouched.
        assert_eq!(wrapped.kind(), io::ErrorKind::Other);
        assert_eq!(wrapped.to_string(), "weird");
    }

    #[test]
    fn enrich_fs_error_wraps_enospc_with_path_and_recovery_hint() {
        let path = Path::new("/repo/.heddle/state/abc.bin");
        let wrapped = enrich_fs_error(path, "writing", enospc_io_error());

        // Stable kind so the CLI exit-code mapper finds it.
        assert_eq!(wrapped.kind(), io::ErrorKind::StorageFull);
        // Message names the failure, the path, and the recovery.
        let msg = wrapped.to_string();
        assert!(
            msg.contains("out of disk space"),
            "missing failure name: {msg}"
        );
        assert!(
            msg.contains("/repo/.heddle/state/abc.bin"),
            "missing path: {msg}"
        );
        assert!(
            msg.contains("free disk space") && msg.contains("re-run"),
            "missing recovery hint: {msg}"
        );
        assert!(
            msg.contains("working tree is unchanged"),
            "missing reassurance: {msg}"
        );
        // Source chain preserved so callers that walk `source()` (e.g.
        // anyhow's chain printer) can still see the original ENOSPC.
        let src = std::error::Error::source(&wrapped as &dyn std::error::Error)
            .or_else(|| wrapped.get_ref().and_then(|e| e.source()))
            .expect("source preserved");
        assert!(src.to_string().to_lowercase().contains("space"));
    }

    #[test]
    fn enrich_fs_error_wraps_enotempty_with_directory_message() {
        let path = Path::new("/repo/web");
        let wrapped = enrich_fs_error(
            path,
            "removing",
            io::Error::from_raw_os_error(ENOTEMPTY_MACOS),
        );
        assert_eq!(wrapped.kind(), io::ErrorKind::DirectoryNotEmpty);
        let msg = wrapped.to_string();
        assert!(
            msg.contains("could not remove directory"),
            "missing action: {msg}"
        );
        assert!(msg.contains("/repo/web"), "missing path: {msg}");
        assert!(
            msg.contains("heddle-ignored"),
            "missing heddle-ignored hint: {msg}"
        );
        assert!(
            msg.contains("leaving in place"),
            "missing reassurance: {msg}"
        );
        // raw_os_error() does NOT round-trip — `io::Error::new(kind, source)`
        // synthesizes a new error whose `raw_os_error()` is None — but the
        // source chain still exposes the original OS code for callers that
        // walk it.
        let src = wrapped.get_ref().and_then(|e| e.source()).expect("source");
        let original = src
            .downcast_ref::<io::Error>()
            .expect("original io::Error preserved");
        assert_eq!(original.raw_os_error(), Some(ENOTEMPTY_MACOS));
    }

    #[test]
    fn enrich_fs_error_wraps_eacces_with_op_and_path() {
        let path = Path::new("/repo/.heddle/state/index.bin");
        let wrapped = enrich_fs_error(path, "writing", io::Error::from_raw_os_error(EACCES));
        assert_eq!(wrapped.kind(), io::ErrorKind::PermissionDenied);
        let msg = wrapped.to_string();
        assert!(msg.starts_with("permission denied writing"), "msg: {msg}");
        assert!(msg.contains("/repo/.heddle/state/index.bin"), "msg: {msg}");
        assert!(msg.contains("check filesystem permissions"), "msg: {msg}");
    }

    #[test]
    fn enrich_fs_error_wraps_enoent_with_op_and_path() {
        let path = Path::new("/repo/.heddle");
        let wrapped = enrich_fs_error(path, "opening", io::Error::from_raw_os_error(ENOENT));
        assert_eq!(wrapped.kind(), io::ErrorKind::NotFound);
        let msg = wrapped.to_string();
        assert!(msg.contains("could not find"), "missing action: {msg}");
        assert!(msg.contains("/repo/.heddle"), "missing path: {msg}");
        assert!(msg.contains("for opening"), "missing op: {msg}");
    }

    #[test]
    fn enrich_fs_error_wraps_erofs_with_path() {
        let path = Path::new("/mnt/readonly/.heddle/state/index.bin");
        let wrapped = enrich_fs_error(path, "writing", io::Error::from_raw_os_error(EROFS));
        assert_eq!(wrapped.kind(), io::ErrorKind::ReadOnlyFilesystem);
        let msg = wrapped.to_string();
        assert!(msg.contains("filesystem is read-only"), "msg: {msg}");
        assert!(
            msg.contains("/mnt/readonly/.heddle/state/index.bin"),
            "msg: {msg}"
        );
        assert!(msg.contains("cannot be modified"), "msg: {msg}");
    }

    #[test]
    fn enrich_rename_error_wraps_exdev_with_src_and_dst() {
        let src = Path::new("/tmp-mount/.x.tmp-1234");
        let dst = Path::new("/repo/.heddle/state/index.bin");
        let wrapped = enrich_rename_error(src, dst, io::Error::from_raw_os_error(EXDEV));
        assert_eq!(wrapped.kind(), io::ErrorKind::CrossesDevices);
        let msg = wrapped.to_string();
        assert!(
            msg.contains("cannot rename across filesystems"),
            "msg: {msg}"
        );
        assert!(msg.contains("/tmp-mount/.x.tmp-1234"), "missing src: {msg}");
        assert!(
            msg.contains("/repo/.heddle/state/index.bin"),
            "missing dst: {msg}"
        );
        assert!(msg.contains("TMPDIR"), "missing recovery hint: {msg}");
    }

    #[test]
    fn enrich_rename_error_falls_through_to_generic_for_other_kinds() {
        let src = Path::new("/tmp/.x.tmp");
        let dst = Path::new("/repo/file");
        let wrapped = enrich_rename_error(src, dst, io::Error::from_raw_os_error(EACCES));
        // Non-EXDEV rename failures get the generic `enrich_fs_error`
        // treatment, which preserves the dst path and the "renaming" op.
        assert_eq!(wrapped.kind(), io::ErrorKind::PermissionDenied);
        let msg = wrapped.to_string();
        assert!(msg.starts_with("permission denied renaming"), "msg: {msg}");
        assert!(msg.contains("/repo/file"), "missing dst: {msg}");
    }

    #[test]
    fn enrich_write_error_passes_through_non_enospc_unclassified() {
        // The historical helper now delegates to `enrich_fs_error`, so a
        // generic Other error still passes through unchanged.
        let path = Path::new("/tmp/example");
        let original = io::Error::other("weird");
        let wrapped = enrich_write_error(path, original);
        assert_eq!(wrapped.kind(), io::ErrorKind::Other);
        assert_eq!(wrapped.to_string(), "weird");
    }

    #[test]
    fn write_file_atomic_round_trip() {
        let dir = tempfile::TempDir::new().unwrap();
        let target = dir.path().join("nested/under/here/file.bin");
        write_file_atomic(&target, b"hello").unwrap();
        assert_eq!(fs::read(&target).unwrap(), b"hello");
    }
}