agent-config 0.3.0

Install hooks/integrations into AI coding harnesses (Claude Code, Cursor, Gemini CLI, OpenCode, Codex CLI, Cline, Windsurf, ...) without learning each one's filesystem layout.
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
//! Atomic file writes, first-touch backups, and Unix permission helpers.
//!
//! Every write through this module:
//! 1. Writes to `<path>.<rand>.tmp` in the same directory.
//! 2. Calls `fsync` on the temp file's contents.
//! 3. Renames temp → `<path>` (POSIX atomic; on Windows uses `MOVEFILE_REPLACE_EXISTING`).
//!
//! If the target file already exists and a backup is requested, we copy
//! `<path>` → `<path>.bak` *first*. Existing backups are treated as the
//! first-touch snapshot and are left in place.

use std::fs;
use std::io::Write as _;
use std::path::{Component, Path, PathBuf};

use crate::error::AgentConfigError;

/// Hard ceiling on bytes the library will read from any harness config or
/// rules file. Set high enough to never trip in practice (typical configs
/// are <100 KiB) and low enough to keep memory bounded on a malicious
/// or runaway file.
pub(crate) const MAX_CONFIG_BYTES: u64 = 8 * 1024 * 1024;

/// Read `path`, returning `Ok(None)` if it does not exist. The size cap is
/// checked from `metadata()` before allocating, so an oversized sparse file
/// surfaces [`AgentConfigError::ConfigTooLarge`] without materializing its
/// bytes. Returning `Option` instead of collapsing missing into an empty
/// `Vec` lets callers distinguish absence from a 0-byte file in one syscall.
pub(crate) fn read_capped(path: &Path) -> Result<Option<Vec<u8>>, AgentConfigError> {
    let meta = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(AgentConfigError::io(path, e)),
    };
    if meta.len() > MAX_CONFIG_BYTES {
        return Err(AgentConfigError::ConfigTooLarge {
            path: path.to_path_buf(),
            size: meta.len(),
            limit: MAX_CONFIG_BYTES,
        });
    }
    let bytes = std::fs::read(path).map_err(|e| AgentConfigError::io(path, e))?;
    Ok(Some(bytes))
}

/// Like [`read_capped`] but treats a missing file as an empty buffer.
pub(crate) fn read_capped_or_empty(path: &Path) -> Result<Vec<u8>, AgentConfigError> {
    Ok(read_capped(path)?.unwrap_or_default())
}

pub(crate) fn read_to_string_capped(path: &Path) -> Result<String, AgentConfigError> {
    let bytes = read_capped_or_empty(path)?;
    String::from_utf8(bytes).map_err(|e| {
        AgentConfigError::io(
            path,
            std::io::Error::new(std::io::ErrorKind::InvalidData, e),
        )
    })
}

/// Result of [`write_atomic`] / [`patch_in_place`].
#[derive(Debug, Default, Clone)]
pub(crate) struct WriteOutcome {
    /// The target path that ended up with new content.
    pub path: PathBuf,
    /// Whether the file existed before this call.
    pub existed: bool,
    /// Path of the `.bak` file if one was created (None if file was new or
    /// content was identical).
    pub backup: Option<PathBuf>,
    /// True if the new content is byte-identical to what was already on disk.
    pub no_change: bool,
}

/// Atomically replace the contents of `path` with `content`.
///
/// If the file already exists and `make_backup` is true, copy it to `<path>.bak`
/// first unless that backup already exists.
/// Creates parent directories if they don't exist. If `content` is byte-equal
/// to the existing file, this is a no-op (no temp file, no backup).
pub(super) fn write_atomic(
    path: &Path,
    content: &[u8],
    make_backup: bool,
) -> Result<WriteOutcome, AgentConfigError> {
    let existed = match fs::read(path) {
        Ok(current) => {
            if current == content {
                return Ok(WriteOutcome {
                    path: path.to_path_buf(),
                    existed: true,
                    backup: None,
                    no_change: true,
                });
            }
            true
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
        Err(e) => return Err(AgentConfigError::io(path, e)),
    };

    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() && !parent.exists() {
            fs::create_dir_all(parent).map_err(|e| AgentConfigError::io(parent, e))?;
        }
    }

    let backup_path = if existed && make_backup && !backup_path(path).exists() {
        match create_backup(path) {
            Ok(backup) => Some(backup),
            Err(AgentConfigError::BackupExists(_)) => None,
            Err(e) => return Err(e),
        }
    } else {
        None
    };

    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));

    let file_name = path
        .file_name()
        .ok_or_else(|| {
            AgentConfigError::PathResolution(format!("path has no file name: {path:?}"))
        })?
        .to_string_lossy()
        .into_owned();

    // Use NamedTempFile in the destination's parent so rename is same-filesystem.
    let mut tmp = tempfile::Builder::new()
        .prefix(&format!(".{file_name}."))
        .suffix(".tmp")
        .tempfile_in(&parent)
        .map_err(|e| AgentConfigError::io(&parent, e))?;

    tmp.write_all(content)
        .map_err(|e| AgentConfigError::io(tmp.path(), e))?;
    tmp.as_file_mut()
        .sync_all()
        .map_err(|e| AgentConfigError::io(tmp.path(), e))?;

    tmp.persist(path)
        .map_err(|e| AgentConfigError::io(path, e.error))?;

    Ok(WriteOutcome {
        path: path.to_path_buf(),
        existed,
        backup: backup_path,
        no_change: false,
    })
}

/// Copy `path` → `<path>.bak`, refusing if a backup already exists.
fn create_backup(path: &Path) -> Result<PathBuf, AgentConfigError> {
    let mut bak = path.as_os_str().to_owned();
    bak.push(".bak");
    let bak = PathBuf::from(bak);

    let mut src = fs::File::open(path).map_err(|e| AgentConfigError::io(path, e))?;
    let mut dst = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&bak)
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::AlreadyExists {
                AgentConfigError::BackupExists(bak.clone())
            } else {
                AgentConfigError::io(&bak, e)
            }
        })?;
    std::io::copy(&mut src, &mut dst).map_err(|e| AgentConfigError::io(&bak, e))?;
    dst.sync_all().map_err(|e| AgentConfigError::io(&bak, e))?;
    Ok(bak)
}

/// Set Unix mode on a file. No-op on non-Unix platforms.
#[cfg(unix)]
pub(super) fn chmod(path: &Path, mode: u32) -> Result<(), AgentConfigError> {
    use std::os::unix::fs::PermissionsExt;
    let mut p = fs::metadata(path)
        .map_err(|e| AgentConfigError::io(path, e))?
        .permissions();
    p.set_mode(mode);
    fs::set_permissions(path, p).map_err(|e| AgentConfigError::io(path, e))?;
    Ok(())
}

/// No-op on Windows.
#[cfg(not(unix))]
pub(super) fn chmod(_path: &Path, _mode: u32) -> Result<(), AgentConfigError> {
    Ok(())
}

/// Remove a file, ignoring NotFound. Returns true if a file was actually removed.
pub(super) fn remove_if_exists(path: &Path) -> Result<bool, AgentConfigError> {
    match fs::remove_file(path) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(AgentConfigError::io(path, e)),
    }
}

/// Read `path` as UTF-8, returning an empty string if the file does not exist.
/// Routes through [`read_to_string_capped`] so an oversized config surfaces
/// [`AgentConfigError::ConfigTooLarge`] instead of consuming unbounded memory.
/// `read_to_string_capped` already returns an empty buffer for missing paths,
/// preserving the original "or_empty" semantics.
pub(crate) fn read_to_string_or_empty(path: &Path) -> Result<String, AgentConfigError> {
    read_to_string_capped(path)
}

/// Restore `<path>.bak` over `path` only when the backup already matches the
/// desired post-uninstall bytes. No-op if no backup exists, the backup is
/// stale, or the backup exceeds the read cap. The oversize case mirrors
/// `planning::plan_restore_backup_or_remove`: a giant `.bak` cannot be the
/// small config we wrote, so we fall through to a fresh write rather than
/// propagating `ConfigTooLarge`.
pub(super) fn restore_backup_if_matches(
    path: &Path,
    desired_content: &[u8],
) -> Result<bool, AgentConfigError> {
    let bak = backup_path(path);
    let backup_content = match read_capped(&bak) {
        Ok(Some(content)) => content,
        Ok(None) => return Ok(false),
        Err(AgentConfigError::ConfigTooLarge { .. }) => return Ok(false),
        Err(e) => return Err(e),
    };
    if backup_content != desired_content {
        return Ok(false);
    }
    fs::rename(&bak, path).map_err(|e| AgentConfigError::io(&bak, e))?;
    Ok(true)
}

/// `<path>.bak`, the path [`write_atomic`] uses for first-touch backups.
pub(crate) fn backup_path(path: &Path) -> PathBuf {
    let mut bak = path.as_os_str().to_owned();
    bak.push(".bak");
    PathBuf::from(bak)
}

/// Append a newline if `s` does not already end with one.
pub(crate) fn ensure_trailing_newline(s: &str) -> String {
    if s.ends_with('\n') {
        s.to_string()
    } else {
        format!("{s}\n")
    }
}

/// Verify that `path` cannot escape `root`.
///
/// This canonicalizes `root`, then walks the existing components between the
/// local root and `path`, rejecting symlink components before following them.
/// Missing tail components are allowed, but the deepest existing ancestor must
/// still canonicalize under `root`. Existing symlink targets are rejected too,
/// since backup/write paths would otherwise follow the link.
pub(crate) fn ensure_contained(path: &Path, root: &Path) -> Result<(), AgentConfigError> {
    let canonical_root = fs::canonicalize(root).map_err(|e| AgentConfigError::io(root, e))?;
    let root_abs = lexical_absolute(root)?;
    let path_abs = lexical_absolute(path)?;

    let deepest_existing = if let Ok(relative) = path_abs.strip_prefix(&root_abs) {
        deepest_existing_descendant(&root_abs, relative)?
    } else if let Ok(relative) = path_abs.strip_prefix(&canonical_root) {
        deepest_existing_descendant(&canonical_root, relative)?
    } else {
        deepest_existing_ancestor(&path_abs)?
    };

    let canonical_existing = fs::canonicalize(&deepest_existing)
        .map_err(|e| AgentConfigError::io(&deepest_existing, e))?;
    if !canonical_existing.starts_with(&canonical_root) {
        return Err(AgentConfigError::PathResolution(format!(
            "resolved path {} escapes project root {}",
            canonical_existing.display(),
            canonical_root.display()
        )));
    }
    Ok(())
}

fn lexical_absolute(path: &Path) -> Result<PathBuf, AgentConfigError> {
    if path.is_absolute() {
        Ok(path.to_path_buf())
    } else {
        let cwd = std::env::current_dir().map_err(|e| AgentConfigError::io(Path::new("."), e))?;
        Ok(cwd.join(path))
    }
}

fn validate_relative_components(relative: &Path) -> Result<(), AgentConfigError> {
    for component in relative.components() {
        match component {
            Component::Normal(_) | Component::CurDir => {}
            Component::ParentDir => {
                return Err(AgentConfigError::PathResolution(format!(
                    "path {} escapes project root via parent directory component",
                    relative.display()
                )));
            }
            Component::Prefix(_) | Component::RootDir => {
                return Err(AgentConfigError::PathResolution(format!(
                    "expected relative path beneath project root, got {}",
                    relative.display()
                )));
            }
        }
    }
    Ok(())
}

fn deepest_existing_descendant(root: &Path, relative: &Path) -> Result<PathBuf, AgentConfigError> {
    validate_relative_components(relative)?;

    let mut current = root.to_path_buf();
    let mut deepest = current.clone();
    let components: Vec<Component<'_>> = relative.components().collect();

    for (index, component) in components.iter().enumerate() {
        match component {
            Component::Normal(part) => current.push(part),
            Component::CurDir => continue,
            Component::ParentDir | Component::Prefix(_) | Component::RootDir => unreachable!(),
        }

        match fs::symlink_metadata(&current) {
            Ok(meta) if meta.file_type().is_symlink() => {
                return Err(AgentConfigError::PathResolution(format!(
                    "refusing to access path through symlink at {}",
                    current.display()
                )));
            }
            Ok(meta) => {
                if index + 1 < components.len() && !meta.is_dir() {
                    return Err(AgentConfigError::PathResolution(format!(
                        "path component {} is not a directory",
                        current.display()
                    )));
                }
                deepest = current.clone();
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
            Err(e) => return Err(AgentConfigError::io(&current, e)),
        }
    }

    Ok(deepest)
}

fn deepest_existing_ancestor(path: &Path) -> Result<PathBuf, AgentConfigError> {
    let mut current = path.to_path_buf();
    loop {
        match fs::symlink_metadata(&current) {
            Ok(meta) if meta.file_type().is_symlink() => {
                return Err(AgentConfigError::PathResolution(format!(
                    "refusing to access path through symlink at {}",
                    current.display()
                )));
            }
            Ok(_) => return Ok(current),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                if !current.pop() {
                    return Err(AgentConfigError::PathResolution(format!(
                        "could not find existing ancestor for {}",
                        path.display()
                    )));
                }
            }
            Err(e) => return Err(AgentConfigError::io(&current, e)),
        }
    }
}

/// Reject the path if it is a symlink.
///
/// Uses `fs::symlink_metadata` to detect symlinks without following them.
/// Returns [`AgentConfigError::PathResolution`] if `path` itself is a symlink.
/// Does **not** inspect parent components — use
/// [`reject_symlink_components`] for global writes where the entire path
/// must be free of symlinks.
#[allow(dead_code)]
pub(crate) fn reject_symlink(path: &Path) -> Result<(), AgentConfigError> {
    match fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_symlink() => Err(AgentConfigError::PathResolution(
            format!("refusing to write through symlink at {}", path.display()),
        )),
        Ok(_) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(AgentConfigError::io(path, e)),
    }
}

/// Reject `path` if any existing component along the way is a symlink.
///
/// Walks the lexically-absolute form of `path` from root toward leaf; for
/// every existing prefix it calls `fs::symlink_metadata` and returns
/// [`AgentConfigError::PathResolution`] if that component is a symlink.
/// Missing tail components are allowed (write_atomic creates them); they
/// cannot be symlinks because they don't exist yet.
///
/// Used for `Scope::Global` writes so a symlinked `~/.claude` or `~/.cursor`
/// (or any ancestor) cannot redirect writes outside the user's intended
/// config tree.
pub(crate) fn reject_symlink_components(path: &Path) -> Result<(), AgentConfigError> {
    let path_abs = lexical_absolute(path)?;
    let mut current = PathBuf::new();
    for component in path_abs.components() {
        match component {
            Component::RootDir => {
                current.push(component.as_os_str());
            }
            Component::Prefix(prefix) => {
                current.push(prefix.as_os_str());
            }
            Component::Normal(part) => {
                current.push(part);
            }
            Component::CurDir => continue,
            Component::ParentDir => {
                return Err(AgentConfigError::PathResolution(format!(
                    "refusing to resolve {} containing a parent-directory component",
                    path.display()
                )));
            }
        }

        match fs::symlink_metadata(&current) {
            Ok(meta) if meta.file_type().is_symlink() => {
                return Err(AgentConfigError::PathResolution(format!(
                    "refusing to write through symlink at {}",
                    current.display()
                )));
            }
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
            Err(e) => return Err(AgentConfigError::io(&current, e)),
        }
    }
    Ok(())
}

/// Like [`write_atomic`], but first verifies that `path` stays within `root`
/// and is not a symlink. Intended for `Scope::Local` writes where the caller
/// supplies a project root that must contain all writes.
#[allow(dead_code)]
pub(crate) fn write_atomic_contained(
    path: &Path,
    content: &[u8],
    make_backup: bool,
    root: &Path,
) -> Result<WriteOutcome, AgentConfigError> {
    reject_symlink(path)?;
    ensure_contained(path, root)?;
    write_atomic(path, content, make_backup)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Barrier};
    use std::thread;
    use tempfile::tempdir;

    fn run_two<A, B, FA, FB>(a: FA, b: FB) -> (A, B)
    where
        A: Send + 'static,
        B: Send + 'static,
        FA: FnOnce() -> A + Send + 'static,
        FB: FnOnce() -> B + Send + 'static,
    {
        let barrier = Arc::new(Barrier::new(3));
        let a_barrier = Arc::clone(&barrier);
        let b_barrier = Arc::clone(&barrier);
        let a_thread = thread::spawn(move || {
            a_barrier.wait();
            a()
        });
        let b_thread = thread::spawn(move || {
            b_barrier.wait();
            b()
        });
        barrier.wait();
        (
            a_thread.join().expect("first writer panicked"),
            b_thread.join().expect("second writer panicked"),
        )
    }

    fn write_succeeded_or_windows_replace_race(
        result: Result<WriteOutcome, AgentConfigError>,
    ) -> bool {
        match result {
            Ok(_) => true,
            Err(AgentConfigError::Io { source, .. })
                if cfg!(windows) && source.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                false
            }
            Err(e) => panic!("unexpected write_atomic error: {e:?}"),
        }
    }

    #[test]
    fn writes_new_file_no_backup() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.json");
        let out = write_atomic(&path, b"hello", true).unwrap();
        assert!(!out.existed);
        assert!(out.backup.is_none());
        assert!(!out.no_change);
        assert_eq!(fs::read(&path).unwrap(), b"hello");
    }

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

        let out = write_atomic(&path, b"new", true).unwrap();
        assert!(out.existed);
        let bak = out.backup.expect("expected backup path");
        assert_eq!(fs::read(&bak).unwrap(), b"old");
        assert_eq!(fs::read(&path).unwrap(), b"new");
    }

    #[test]
    fn identical_content_is_noop() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.json");
        fs::write(&path, b"same").unwrap();
        let out = write_atomic(&path, b"same", true).unwrap();
        assert!(out.no_change);
        assert!(out.backup.is_none());
        assert!(!backup_path(&path).exists(), "no backup on no-op");
    }

    #[test]
    fn existing_backup_is_preserved_while_target_updates() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.json");
        let bak = backup_path(&path);

        fs::write(&path, b"original").unwrap();
        fs::write(&bak, b"important-old-backup").unwrap();

        let out = write_atomic(&path, b"new", true).unwrap();
        assert!(out.backup.is_none());
        assert_eq!(fs::read(&bak).unwrap(), b"important-old-backup");
        assert_eq!(fs::read(&path).unwrap(), b"new");
    }

    #[test]
    fn creates_parent_dirs() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("nested/deeply/under/file.txt");
        write_atomic(&path, b"x", false).unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"x");
    }

    #[test]
    fn restore_backup_round_trip() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("f.txt");
        fs::write(&path, b"v1").unwrap();
        write_atomic(&path, b"v2", true).unwrap();
        assert!(restore_backup_if_matches(&path, b"v1").unwrap());
        assert_eq!(fs::read(&path).unwrap(), b"v1");
        assert!(!backup_path(&path).exists());
    }

    #[test]
    fn restore_backup_skips_stale_backup() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("f.txt");
        fs::write(&path, b"v1").unwrap();
        write_atomic(&path, b"v2", true).unwrap();

        assert!(!restore_backup_if_matches(&path, b"").unwrap());
        assert_eq!(fs::read(&path).unwrap(), b"v2");
        assert_eq!(fs::read(backup_path(&path)).unwrap(), b"v1");
    }

    #[test]
    fn remove_if_exists_handles_missing() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("ghost");
        assert!(!remove_if_exists(&path).unwrap());
        fs::write(&path, b"x").unwrap();
        assert!(remove_if_exists(&path).unwrap());
    }

    #[test]
    fn read_to_string_or_empty_handles_missing_and_present() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("maybe.md");
        assert_eq!(read_to_string_or_empty(&path).unwrap(), "");
        fs::write(&path, b"hello").unwrap();
        assert_eq!(read_to_string_or_empty(&path).unwrap(), "hello");
    }

    #[cfg(not(unix))]
    #[test]
    fn chmod_is_noop_on_non_unix() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("missing.sh");
        chmod(&path, 0o755).unwrap();
        assert!(!path.exists());
    }

    #[test]
    fn concurrent_writes_without_backup_leave_complete_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.json");
        let path_a = path.clone();
        let path_b = path.clone();
        let a = br#"{"winner":"a","padding":"aaaaaaaaaaaaaaaa"}"#.to_vec();
        let b = br#"{"winner":"b","padding":"bbbbbbbbbbbbbbbb"}"#.to_vec();
        let expect_a = a.clone();
        let expect_b = b.clone();

        let (ra, rb) = run_two(
            move || write_atomic(&path_a, &a, false),
            move || write_atomic(&path_b, &b, false),
        );

        // Windows can reject one simultaneous replace with AccessDenied. Shared
        // integration paths serialize writes with file locks; this lower-level
        // helper only needs to leave a complete final file when raced directly.
        let a_succeeded = write_succeeded_or_windows_replace_race(ra);
        let b_succeeded = write_succeeded_or_windows_replace_race(rb);
        assert!(
            a_succeeded || b_succeeded,
            "at least one concurrent writer should succeed"
        );
        let final_bytes = fs::read(&path).unwrap();
        assert!(
            final_bytes == expect_a || final_bytes == expect_b,
            "final file should be one complete write, got {:?}",
            String::from_utf8_lossy(&final_bytes)
        );
    }

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

        let (ra, rb) = run_two(
            move || write_atomic(&path_a, b"new-a", true),
            move || write_atomic(&path_b, b"new-b", true),
        );

        let a_succeeded = write_succeeded_or_windows_replace_race(ra);
        let b_succeeded = write_succeeded_or_windows_replace_race(rb);
        assert!(
            a_succeeded || b_succeeded,
            "at least one concurrent writer should succeed"
        );
        assert_eq!(fs::read(backup_path(&path)).unwrap(), b"original");
        let final_bytes = fs::read(&path).unwrap();
        assert!(final_bytes == b"new-a" || final_bytes == b"new-b");
    }

    #[test]
    fn ensure_contained_allows_path_under_root() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("sub").join("config.json");
        fs::create_dir_all(dir.path().join("sub")).unwrap();
        fs::write(&file, b"{}").unwrap();
        ensure_contained(&file, dir.path()).unwrap();
    }

    #[test]
    fn ensure_contained_rejects_path_outside_root() {
        let dir = tempdir().unwrap();
        let outside = dir.path().join("outside");
        fs::create_dir_all(&outside).unwrap();
        let file = outside.join("config.json");
        fs::write(&file, b"{}").unwrap();
        let root = dir.path().join("inside");
        fs::create_dir_all(&root).unwrap();
        let err = ensure_contained(&file, &root).unwrap_err();
        assert!(matches!(err, AgentConfigError::PathResolution(_)));
    }

    #[test]
    fn ensure_contained_allows_nonexistent_parent() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("new").join("config.json");
        assert!(!file.parent().unwrap().exists());
        ensure_contained(&file, dir.path()).unwrap();
    }

    #[test]
    #[cfg(unix)]
    fn ensure_contained_rejects_symlink_escape() {
        use std::os::unix::fs::symlink;
        let dir = tempdir().unwrap();
        let project = dir.path().join("project");
        let escape = dir.path().join("escape");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&escape).unwrap();
        fs::write(escape.join("secret"), b"leaked").unwrap();
        let link = project.join("evil-link");
        symlink(&escape, &link).unwrap();
        let target = link.join("config.json");
        let err = ensure_contained(&target, &project).unwrap_err();
        assert!(
            matches!(err, AgentConfigError::PathResolution(ref msg) if msg.contains("symlink"))
        );
    }

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

        let dir = tempdir().unwrap();
        let project = dir.path().join("project");
        let escape = dir.path().join("escape");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&escape).unwrap();
        let link = project.join(".opencode");
        symlink(&escape, &link).unwrap();

        let target = link.join("plugins").join("hook.ts");
        assert!(!target.parent().unwrap().exists());
        let err = ensure_contained(&target, &project).unwrap_err();
        assert!(
            matches!(err, AgentConfigError::PathResolution(ref msg) if msg.contains("symlink"))
        );
    }

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

        let dir = tempdir().unwrap();
        let project = dir.path().join("project");
        let escape = dir.path().join("escape");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&escape).unwrap();
        let outside_file = escape.join("config.json");
        fs::write(&outside_file, b"outside").unwrap();
        let link = project.join("config.json");
        symlink(&outside_file, &link).unwrap();

        let err = ensure_contained(&link, &project).unwrap_err();
        assert!(
            matches!(err, AgentConfigError::PathResolution(ref msg) if msg.contains("symlink"))
        );
    }

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

        let dir = tempdir().unwrap();
        let project = dir.path().join("project");
        let escape = dir.path().join("escape");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&escape).unwrap();
        let link = project.join(".opencode");
        symlink(&escape, &link).unwrap();

        let target = link.join("plugins").join("hook.ts");
        let err = write_atomic_contained(&target, b"export {}", true, &project).unwrap_err();
        assert!(
            matches!(err, AgentConfigError::PathResolution(ref msg) if msg.contains("symlink"))
        );
        assert!(!escape.join("plugins").exists());
    }

    #[test]
    #[cfg(unix)]
    fn reject_symlink_detects_symlink() {
        use std::os::unix::fs::symlink;
        let dir = tempdir().unwrap();
        let target = dir.path().join("real");
        fs::write(&target, b"real").unwrap();
        let link = dir.path().join("link");
        symlink(&target, &link).unwrap();
        let err = reject_symlink(&link).unwrap_err();
        assert!(
            matches!(err, AgentConfigError::PathResolution(ref msg) if msg.contains("symlink"))
        );
    }

    #[test]
    fn reject_symlink_allows_regular_file() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("config.json");
        fs::write(&file, b"{}").unwrap();
        reject_symlink(&file).unwrap();
    }

    #[test]
    fn reject_symlink_allows_nonexistent() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("ghost");
        reject_symlink(&file).unwrap();
    }

    #[test]
    fn read_capped_rejects_oversized_files() {
        let dir = tempdir().unwrap();
        let big = dir.path().join("big.json");
        let f = std::fs::File::create(&big).unwrap();
        // sparse: set logical length above the cap without actually writing 8 MiB.
        f.set_len(MAX_CONFIG_BYTES + 1).unwrap();
        let err = read_capped(&big).unwrap_err();
        assert!(
            matches!(err, AgentConfigError::ConfigTooLarge { size, limit, .. } if size > limit)
        );
    }

    #[test]
    fn read_capped_returns_none_for_missing_file() {
        let dir = tempdir().unwrap();
        let missing = dir.path().join("nope.json");
        assert!(read_capped(&missing).unwrap().is_none());
    }

    #[test]
    fn read_capped_distinguishes_missing_from_empty() {
        let dir = tempdir().unwrap();
        let empty = dir.path().join("empty.json");
        std::fs::write(&empty, b"").unwrap();
        assert_eq!(read_capped(&empty).unwrap(), Some(Vec::<u8>::new()));
        let missing = dir.path().join("absent.json");
        assert!(read_capped(&missing).unwrap().is_none());
    }

    #[test]
    fn read_capped_reads_small_file() {
        let dir = tempdir().unwrap();
        let small = dir.path().join("small.json");
        std::fs::write(&small, b"{}").unwrap();
        assert_eq!(read_capped(&small).unwrap(), Some(b"{}".to_vec()));
    }

    #[test]
    fn read_capped_or_empty_collapses_missing() {
        let dir = tempdir().unwrap();
        let missing = dir.path().join("nope.json");
        assert!(read_capped_or_empty(&missing).unwrap().is_empty());
    }

    #[test]
    fn read_to_string_capped_rejects_invalid_utf8() {
        let dir = tempdir().unwrap();
        let bad = dir.path().join("bad.txt");
        std::fs::write(&bad, [0xFF, 0xFE, 0xFD]).unwrap();
        let err = read_to_string_capped(&bad).unwrap_err();
        assert!(matches!(err, AgentConfigError::Io { .. }));
    }
}