agent-first-data 0.19.0

A naming convention that lets AI agents understand your data without being told what it means, plus a CLI and library for reading 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
//! Format-neutral in-memory document value, plus a file-backed document
//! facade with safe, source-preserving edits.
//!
//! [`DocumentFile`] lifts the file-safety and source-preserving edit
//! orchestration that previously lived only in a CLI binary: mutation
//! methods refuse to write through a symlink or (on unix) a hardlinked
//! file, and every write goes to a same-directory temp file that is
//! fsynced, has the original file's permissions re-applied, and is
//! atomically renamed over the target — so a crash or error mid-write never
//! leaves a partial file.
//!
//! This module never redacts values on decode/encode/save/edit — it reads
//! and writes raw values as-is; redaction is the caller's responsibility.
//!
//! # Capability matrix
//!
//! - [`Document`] (in-memory): [`Document::value_mut`] allows arbitrary
//!   in-memory edits; [`Document::encode`] re-renders the value fresh from
//!   scratch — formatting and comments are NOT preserved. No file, no atomic
//!   write.
//! - [`DocumentFile`] (file-backed): reads via [`DocumentFile::value`] (paired
//!   with the free function [`crate::document::get_path`]), and
//!   source-preserving typed write verbs [`DocumentFile::set`]/
//!   [`DocumentFile::unset`]/[`DocumentFile::add`]/[`DocumentFile::remove`];
//!   every write is atomic (symlink/hardlink-guarded temp file + fsync +
//!   permission-preserving rename). There is no `value_mut` — edits go
//!   through the verbs above so the original source's formatting survives.

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

use crate::document::{DocumentError, DocumentResult, Format, KeyedList, Value};

/// A format-neutral in-memory document: a parsed [`Value`] plus the
/// [`Format`] it was parsed from. Has no file or stdin coupling — construct
/// it from a string or any [`std::io::Read`] the caller supplies.
#[derive(Debug, Clone)]
pub struct Document {
    value: Value,
    format: Format,
}

impl Document {
    /// Parse `source` in the given `format`.
    ///
    /// Named `parse` (not `from_str`) deliberately: this takes an explicit
    /// `format` argument, so it is not the single-argument `std::str::FromStr`
    /// contract that `from_str` would imply.
    pub fn parse(source: &str, format: Format) -> DocumentResult<Document> {
        let value = format.load(source)?;
        Ok(Document { value, format })
    }

    /// Read `reader` fully to a `String`, then parse it in the given
    /// `format`.
    ///
    /// Reads only from the supplied `reader` — never touches the process's
    /// own stdin.
    pub fn from_reader<R: std::io::Read>(
        mut reader: R,
        format: Format,
    ) -> DocumentResult<Document> {
        let mut source = String::new();
        reader.read_to_string(&mut source)?;
        Document::parse(&source, format)
    }

    /// Borrow the parsed value.
    pub fn value(&self) -> &Value {
        &self.value
    }

    /// Mutably borrow the parsed value.
    pub fn value_mut(&mut self) -> &mut Value {
        &mut self.value
    }

    /// The format this document was parsed from.
    pub fn format(&self) -> Format {
        self.format
    }

    /// Re-render the current value in its format via [`Format::save`].
    ///
    /// This is a fresh, non-source-preserving render: comments and original
    /// formatting are not retained. Use [`DocumentFile`] when the original
    /// source's formatting must survive an edit.
    pub fn encode(&self) -> DocumentResult<String> {
        self.format.save(&self.value)
    }
}

/// A file-backed document: owns the path, format, original source text, and
/// parsed value.
///
/// Reading (`open`) is always allowed. Mutation methods guard against unsafe
/// targets (symlinks, hardlinked files) and write through a same-directory
/// temp file that is atomically renamed over the original — see
/// [`DocumentFile::save_atomic`].
#[derive(Debug)]
pub struct DocumentFile {
    path: PathBuf,
    format: Format,
    source: String,
    value: Value,
}

impl DocumentFile {
    /// Open and parse `path`.
    ///
    /// `format_override` takes precedence; otherwise the format is detected
    /// from the file extension via [`Format::detect`]. Reading is always
    /// allowed — this does not run the mutation guard.
    pub fn open(
        path: impl AsRef<Path>,
        format_override: Option<Format>,
    ) -> DocumentResult<DocumentFile> {
        let path = path.as_ref().to_path_buf();
        let format = match format_override {
            Some(format) => format,
            None => Format::detect(&path).ok_or_else(|| DocumentError::ParseError {
                format: "format".to_string(),
                detail: format!(
                    "cannot detect format from file extension `{}`; pass an explicit format",
                    path.display()
                ),
            })?,
        };
        let source = fs::read_to_string(&path).map_err(|error| DocumentError::IoError {
            detail: format!("read `{}`: {error}", path.display()),
        })?;
        let value = format.load(&source)?;
        Ok(DocumentFile {
            path,
            format,
            source,
            value,
        })
    }

    /// Open and parse `path` like [`DocumentFile::open`], but first reject any
    /// non-regular file, or any file larger than `max_bytes`, without reading
    /// its contents.
    ///
    /// Use this over [`open`](DocumentFile::open) when reading untrusted or
    /// secret-bearing config, where an unbounded read of an arbitrary path is
    /// a denial-of-service risk.
    pub fn open_capped(
        path: impl AsRef<Path>,
        format_override: Option<Format>,
        max_bytes: u64,
    ) -> DocumentResult<DocumentFile> {
        let path = path.as_ref();
        let metadata = fs::metadata(path).map_err(|error| DocumentError::IoError {
            detail: format!("read `{}`: {error}", path.display()),
        })?;
        if !metadata.is_file() {
            return Err(DocumentError::IoError {
                detail: format!("`{}` is not a regular file", path.display()),
            });
        }
        if metadata.len() > max_bytes {
            return Err(DocumentError::IoError {
                detail: format!(
                    "`{}` exceeds the {max_bytes}-byte read limit",
                    path.display()
                ),
            });
        }
        DocumentFile::open(path, format_override)
    }

    /// The file path this document was opened from.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Borrow the currently parsed value (reflects the last successful
    /// edit, if any).
    pub fn value(&self) -> &Value {
        &self.value
    }

    /// Resolve a dotted `path` against the parsed document and return the value
    /// at that address.
    ///
    /// One-call read counterpart to [`set`](DocumentFile::set): equivalent to
    /// [`value`](DocumentFile::value) followed by
    /// [`crate::document::get_path`], for callers that only need to read one
    /// address out of a file.
    pub fn value_at(&self, path: &str) -> DocumentResult<Value> {
        crate::document::get_path(&self.value, path, &[])
    }

    /// The format this file was opened as.
    pub fn format(&self) -> Format {
        self.format
    }

    /// Borrow the current source text (reflects the last successful edit,
    /// if any).
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Preflight-check that this file is safe to mutate — not a symlink, and
    /// on unix not hardlinked — without performing any write.
    ///
    /// Every mutation method ([`DocumentFile::set`] and friends) already
    /// runs this same guard itself before writing, so calling it directly is
    /// only useful when a caller must front-run a *separate* side effect with
    /// the same guarantee — for example, a CLI that reads a secret from stdin
    /// for `set` should refuse an unsafe target before consuming that input,
    /// not after.
    pub fn ensure_mutable(&self, operation: &str) -> DocumentResult<()> {
        guard_mutation(&self.path, operation)?;
        Ok(())
    }

    /// Set `key` to the typed `value`, preserving the rest of the source
    /// document.
    pub fn set(&mut self, key: &str, value: Value) -> DocumentResult<()> {
        guard_mutation(&self.path, "set")?;
        let mut new_doc = self.value.clone();
        self.format.ensure_writable("set")?;
        crate::document::set_path(&mut new_doc, key, &value, &[])?;
        let target = crate::document::get_path(&new_doc, key, &[])?;
        #[allow(unreachable_patterns)]
        let output = match self.format {
            #[cfg(feature = "toml")]
            Format::Toml => {
                crate::document::format::toml::set_scalar_preserving(&self.source, key, &target)?
            }
            #[cfg(feature = "yaml")]
            Format::Yaml => {
                crate::document::format::yaml::set_scalar_preserving(&self.source, key, &target)?
            }
            Format::Json => {
                crate::document::format::json::set_scalar_preserving(&self.source, key, &target)?
            }
            #[cfg(feature = "dotenv")]
            Format::Dotenv => {
                crate::document::format::dotenv::set_scalar_preserving(&self.source, key, &target)?
            }
            #[cfg(feature = "ini")]
            Format::Ini => {
                crate::document::format::ini::set_scalar_preserving(&self.source, key, &target)?
            }
            #[cfg(feature = "toml")]
            Format::TomlFrontmatter => {
                let parts = crate::document::format::frontmatter::split(
                    &self.source,
                    crate::document::format::frontmatter::Delimiter::Plus,
                )?;
                let new_fm = crate::document::format::toml::set_scalar_preserving(
                    parts.frontmatter,
                    key,
                    &target,
                )?;
                format!("{}{}{}", parts.pre, new_fm, parts.post)
            }
            #[cfg(feature = "yaml")]
            Format::YamlFrontmatter => {
                let parts = crate::document::format::frontmatter::split(
                    &self.source,
                    crate::document::format::frontmatter::Delimiter::Dash,
                )?;
                let new_fm = crate::document::format::yaml::set_scalar_preserving(
                    parts.frontmatter,
                    key,
                    &target,
                )?;
                format!("{}{}{}", parts.pre, new_fm, parts.post)
            }
            _ => self.format.save(&new_doc)?,
        };
        self.save_atomic(&output)?;
        self.source = output;
        self.value = new_doc;
        Ok(())
    }

    /// Add a new element to the keyed list at `key`, identified by
    /// `slug`/`slug_field`, with the given `fields`. Preserves the rest of
    /// the source document.
    ///
    /// Only JSON and YAML backends implement a source-preserving
    /// keyed-collection editor today; other formats return
    /// [`DocumentError::UnsupportedOperation`].
    pub fn add(
        &mut self,
        key: &str,
        slug: &str,
        slug_field: &str,
        fields: &[(String, Value)],
    ) -> DocumentResult<()> {
        guard_mutation(&self.path, "add")?;
        let mut value = self.value.clone();
        self.format.ensure_writable("add")?;
        let keyed_lists = [KeyedList {
            prefix: key,
            slug_field,
        }];
        crate::document::add_keyed(&mut value, key, slug, &keyed_lists, None, fields)?;
        let output: String = match self.format {
            Format::Json => {
                let array = crate::document::get_path(&value, key, &keyed_lists)?;
                let item = array
                    .as_array()
                    .and_then(|items| items.last())
                    .ok_or_else(|| DocumentError::UnsupportedOperation {
                        format: "JSON".to_string(),
                        operation: "add".to_string(),
                        detail: "keyed list did not produce an array item".to_string(),
                    })?;
                crate::document::format::json::append_array_item_preserving(
                    &self.source,
                    key,
                    item,
                )?
            }
            #[cfg(feature = "yaml")]
            Format::Yaml => {
                let array = crate::document::get_path(&value, key, &keyed_lists)?;
                let item = array
                    .as_array()
                    .and_then(|items| items.last())
                    .ok_or_else(|| DocumentError::UnsupportedOperation {
                        format: "YAML".to_string(),
                        operation: "add".to_string(),
                        detail: "keyed list did not produce an array item".to_string(),
                    })?;
                crate::document::format::yaml::append_array_item_preserving(
                    &self.source,
                    key,
                    item,
                )?
            }
            _ => {
                return Err(DocumentError::UnsupportedOperation {
                    format: self.format.name().to_string(),
                    operation: "add".to_string(),
                    detail: "keyed collection source editor is not implemented for this backend"
                        .to_string(),
                });
            }
        };
        self.save_atomic(&output)?;
        self.source = output;
        self.value = value;
        Ok(())
    }

    /// Remove the element identified by `slug`/`slug_field` from the keyed
    /// list at `key`. Preserves the rest of the source document.
    ///
    /// Only JSON and YAML backends implement a source-preserving
    /// keyed-collection editor today; other formats return
    /// [`DocumentError::UnsupportedOperation`].
    pub fn remove(&mut self, key: &str, slug: &str, slug_field: &str) -> DocumentResult<()> {
        guard_mutation(&self.path, "remove")?;
        let mut value = self.value.clone();
        self.format.ensure_writable("remove")?;
        let keyed_lists = [KeyedList {
            prefix: key,
            slug_field,
        }];
        let original_array = crate::document::get_path(&value, key, &keyed_lists)?;
        let removed_index = original_array
            .as_array()
            .and_then(|items| {
                items
                    .iter()
                    .position(|item| item.get(slug_field).and_then(Value::as_str) == Some(slug))
            })
            .ok_or_else(|| DocumentError::SlugNotFound {
                prefix: key.to_string(),
                slug: slug.to_string(),
            })?;
        #[cfg(not(feature = "yaml"))]
        let _ = removed_index;
        crate::document::remove_keyed(&mut value, key, slug, &keyed_lists)?;
        let output: String = match self.format {
            Format::Json => crate::document::format::json::remove_array_item_preserving(
                &self.source,
                key,
                slug,
                slug_field,
            )?,
            #[cfg(feature = "yaml")]
            Format::Yaml => crate::document::format::yaml::remove_array_item_preserving(
                &self.source,
                key,
                removed_index,
            )?,
            _ => {
                return Err(DocumentError::UnsupportedOperation {
                    format: self.format.name().to_string(),
                    operation: "remove".to_string(),
                    detail: "keyed collection source editor is not implemented for this backend"
                        .to_string(),
                });
            }
        };
        self.save_atomic(&output)?;
        self.source = output;
        self.value = value;
        Ok(())
    }

    /// Remove the entry at `key` entirely. Preserves the rest of the source
    /// document.
    pub fn unset(&mut self, key: &str) -> DocumentResult<()> {
        guard_mutation(&self.path, "unset")?;
        let mut value = self.value.clone();
        self.format.ensure_writable("unset")?;
        crate::document::unset_path(&mut value, key)?;
        #[allow(unreachable_patterns)]
        let output = match self.format {
            Format::Json => crate::document::format::json::unset_preserving(&self.source, key)?,
            #[cfg(feature = "toml")]
            Format::Toml => crate::document::format::toml::unset_preserving(&self.source, key)?,
            #[cfg(feature = "yaml")]
            Format::Yaml => crate::document::format::yaml::unset_preserving(&self.source, key)?,
            #[cfg(feature = "dotenv")]
            Format::Dotenv => crate::document::format::dotenv::unset_preserving(&self.source, key)?,
            #[cfg(feature = "ini")]
            Format::Ini => crate::document::format::ini::unset_preserving(&self.source, key)?,
            #[cfg(feature = "toml")]
            Format::TomlFrontmatter => {
                let parts = crate::document::format::frontmatter::split(
                    &self.source,
                    crate::document::format::frontmatter::Delimiter::Plus,
                )?;
                let new_fm =
                    crate::document::format::toml::unset_preserving(parts.frontmatter, key)?;
                format!("{}{}{}", parts.pre, new_fm, parts.post)
            }
            #[cfg(feature = "yaml")]
            Format::YamlFrontmatter => {
                let parts = crate::document::format::frontmatter::split(
                    &self.source,
                    crate::document::format::frontmatter::Delimiter::Dash,
                )?;
                let new_fm =
                    crate::document::format::yaml::unset_preserving(parts.frontmatter, key)?;
                format!("{}{}{}", parts.pre, new_fm, parts.post)
            }
            _ => self.format.save(&value)?,
        };
        self.save_atomic(&output)?;
        self.source = output;
        self.value = value;
        Ok(())
    }

    /// Atomically replace the file's contents with `new_source`: guard
    /// against symlinks/hardlinked files, write to a same-directory temp
    /// file, fsync it, re-apply the original file's permissions, then
    /// `rename` it over the target. No partial write is ever observable —
    /// on any failure the temp file is removed and the original file is
    /// untouched.
    ///
    /// This does not update the in-memory [`DocumentFile::source`] /
    /// [`DocumentFile::value`] — the mutation methods do that themselves
    /// after a successful write.
    ///
    /// Crate-internal: this is the raw-string write seam the typed verbs
    /// (`set`/`unset`/`add`/`remove`) route through after computing a
    /// source-preserving rendering; it is not part of the public API, so
    /// callers cannot bypass the typed verbs to write arbitrary raw text.
    pub(crate) fn save_atomic(&self, new_source: &str) -> DocumentResult<()> {
        write_atomic(&self.path, new_source.as_bytes(), "write")
    }
}

/// Reject mutation of a symlink or (on unix) a hardlinked file. Returns the
/// target's metadata on success so callers that also need to write can reuse
/// it (e.g. to preserve permissions) without a second syscall.
fn guard_mutation(path: &Path, operation: &str) -> DocumentResult<fs::Metadata> {
    let metadata = fs::symlink_metadata(path).map_err(|error| DocumentError::IoError {
        detail: format!("{operation} preflight `{}`: {error}", path.display()),
    })?;
    if metadata.file_type().is_symlink() {
        return Err(DocumentError::UnsupportedOperation {
            format: "filesystem".to_string(),
            operation: operation.to_string(),
            detail: format!("refusing to mutate symlink `{}`", path.display()),
        });
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if metadata.nlink() > 1 {
            return Err(DocumentError::UnsupportedOperation {
                format: "filesystem".to_string(),
                operation: operation.to_string(),
                detail: format!("refusing to mutate hardlinked file `{}`", path.display()),
            });
        }
    }
    Ok(metadata)
}

/// Write `bytes` to `path` atomically: guard, same-directory temp file,
/// fsync, permission preservation, then rename over the target.
fn write_atomic(path: &Path, bytes: &[u8], operation: &str) -> DocumentResult<()> {
    let metadata = guard_mutation(path, operation)?;

    let parent = path.parent().ok_or_else(|| DocumentError::IoError {
        detail: format!(
            "{operation} has no parent directory for `{}`",
            path.display()
        ),
    })?;
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| DocumentError::IoError {
            detail: format!("{operation} path is not valid UTF-8: `{}`", path.display()),
        })?;
    let pid = std::process::id();
    let mut temp_path = None;
    let mut temp_file = None;
    for attempt in 0..32_u32 {
        let candidate = parent.join(format!(".{file_name}.afdata-document.{pid}.{attempt}.tmp"));
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&candidate)
        {
            Ok(file) => {
                temp_path = Some(candidate);
                temp_file = Some(file);
                break;
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => {
                return Err(DocumentError::IoError {
                    detail: format!(
                        "{operation} create temporary file in `{}`: {error}",
                        parent.display()
                    ),
                });
            }
        }
    }
    let temp_path = temp_path.ok_or_else(|| DocumentError::IoError {
        detail: format!(
            "{operation} could not allocate temporary file in `{}`",
            parent.display()
        ),
    })?;
    let mut temp_file = temp_file.ok_or_else(|| DocumentError::IoError {
        detail: format!("{operation} temporary file handle missing"),
    })?;
    let result = (|| -> DocumentResult<()> {
        temp_file
            .write_all(bytes)
            .map_err(|error| DocumentError::IoError {
                detail: format!("{operation} write `{}`: {error}", path.display()),
            })?;
        temp_file
            .sync_all()
            .map_err(|error| DocumentError::IoError {
                detail: format!("{operation} fsync `{}`: {error}", path.display()),
            })?;
        drop(temp_file);
        fs::set_permissions(&temp_path, metadata.permissions()).map_err(|error| {
            DocumentError::IoError {
                detail: format!(
                    "{operation} preserve permissions `{}`: {error}",
                    path.display()
                ),
            }
        })?;
        fs::rename(&temp_path, path).map_err(|error| DocumentError::IoError {
            detail: format!("{operation} atomic replace `{}`: {error}", path.display()),
        })?;
        Ok(())
    })();
    if result.is_err() {
        let _ = fs::remove_file(&temp_path);
    }
    result
}

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

    fn write_temp(dir: &Path, name: &str, contents: &str) -> PathBuf {
        let path = dir.join(name);
        fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn round_trip_open_json() {
        let dir = tempfile::tempdir().unwrap();
        let contents = r#"{"host": "example.com", "port": 993}"#;
        let path = write_temp(dir.path(), "config.json", contents);

        let doc = DocumentFile::open(&path, None).unwrap();

        assert_eq!(doc.format(), Format::Json);
        assert_eq!(
            doc.value().get("host").and_then(Value::as_str),
            Some("example.com")
        );
        assert_eq!(doc.source(), contents);
    }

    #[test]
    fn value_at_reads_a_nested_address() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(
            dir.path(),
            "config.json",
            r#"{"database": {"url": "postgres://x"}}"#,
        );
        let doc = DocumentFile::open(&path, None).unwrap();

        assert_eq!(
            doc.value_at("database.url").unwrap(),
            Value::String("postgres://x".to_string())
        );
        assert_eq!(
            doc.value_at("database.missing").unwrap_err().code(),
            "document_path_not_found"
        );
    }

    #[test]
    fn open_capped_enforces_size_and_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(dir.path(), "config.json", r#"{"k": "v"}"#);

        // Within the cap: opens normally.
        assert!(DocumentFile::open_capped(&path, None, 1024).is_ok());

        // Over the cap: rejected without parsing, as an io failure.
        let err = DocumentFile::open_capped(&path, None, 4).unwrap_err();
        assert_eq!(err.code(), "document_io_failed");
        assert!(err.to_string().contains("read limit"));

        // A directory is not a regular file.
        let dir_err = DocumentFile::open_capped(dir.path(), Some(Format::Json), 1024).unwrap_err();
        assert_eq!(dir_err.code(), "document_io_failed");
    }

    #[cfg(feature = "toml")]
    #[test]
    fn round_trip_open_toml() {
        let dir = tempfile::tempdir().unwrap();
        let contents = "# leading comment\nhost = \"example.com\"\nport = 993\n";
        let path = write_temp(dir.path(), "config.toml", contents);

        let doc = DocumentFile::open(&path, None).unwrap();

        assert_eq!(doc.format(), Format::Toml);
        assert_eq!(
            doc.value().get("host").and_then(Value::as_str),
            Some("example.com")
        );
        assert_eq!(doc.source(), contents);
    }

    #[cfg(feature = "toml")]
    #[test]
    fn set_scalar_preserves_toml_comments_and_formatting() {
        let dir = tempfile::tempdir().unwrap();
        let contents = "# leading comment\nhost = \"example.com\"\nport = 993 # inline comment\n";
        let path = write_temp(dir.path(), "config.toml", contents);
        let mut doc = DocumentFile::open(&path, None).unwrap();

        doc.set("port", Value::Integer(1024)).unwrap();

        let saved = fs::read_to_string(&path).unwrap();
        assert!(saved.contains("# leading comment"));
        assert!(saved.contains("port = 1024"));
        assert_eq!(
            doc.value().get("port").and_then(Value::as_integer),
            Some(1024)
        );
        assert_eq!(doc.source(), saved);
    }

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

        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(dir.path(), "config.json", r#"{"port": 993}"#);
        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
        let mut doc = DocumentFile::open(&path, None).unwrap();

        doc.set("port", Value::Integer(1024)).unwrap();

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

    #[cfg(unix)]
    #[test]
    fn symlink_target_is_rejected_for_mutation() {
        let dir = tempfile::tempdir().unwrap();
        let target = write_temp(dir.path(), "target.json", r#"{"port": 993}"#);
        let link = dir.path().join("link.json");
        std::os::unix::fs::symlink(&target, &link).unwrap();

        // Reading through the symlink is fine.
        let mut doc = DocumentFile::open(&link, None).unwrap();

        // Mutating through it is not.
        let err = doc.set("port", Value::Integer(1024)).unwrap_err();
        assert!(matches!(err, DocumentError::UnsupportedOperation { .. }));

        // The target file was never touched.
        let target_contents = fs::read_to_string(&target).unwrap();
        assert_eq!(target_contents, r#"{"port": 993}"#);
    }

    #[test]
    fn from_reader_parses_in_memory_cursor() {
        let cursor = Cursor::new(br#"{"host": "example.com"}"#.to_vec());

        let doc = Document::from_reader(cursor, Format::Json).unwrap();

        assert_eq!(
            doc.value().get("host").and_then(Value::as_str),
            Some("example.com")
        );
    }

    #[test]
    fn document_from_str_encode_round_trip() {
        let doc = Document::parse(r#"{"a": 1}"#, Format::Json).unwrap();
        let encoded = doc.encode().unwrap();
        let reparsed = Document::parse(&encoded, Format::Json).unwrap();
        assert_eq!(
            reparsed.value().get("a").and_then(Value::as_integer),
            Some(1)
        );
    }
}