Skip to main content

agent_first_data/document/
error.rs

1//! Error types with context and helpful hints.
2
3use std::fmt;
4use std::io;
5
6pub type DocumentResult<T> = Result<T, DocumentError>;
7
8#[derive(Debug, Clone)]
9pub enum DocumentError {
10    EmptyPath,
11    EmptyValues,
12    UnknownSegment {
13        path: String,
14        segment: String,
15    },
16    /// A non-numeric segment addressed an array that nothing claims: no
17    /// [`KeyedList`](crate::document::KeyedList) registration covers it and its
18    /// format states no rule of its own.
19    ///
20    /// The message names the two ways out rather than the internal type that
21    /// happens to be missing — a caller can supply a rule or use an index, and
22    /// neither is discoverable from the name of a Rust struct.
23    UnregisteredArray {
24        path: String,
25    },
26    SlugNotFound {
27        prefix: String,
28        slug: String,
29    },
30    /// A non-numeric segment matched several elements of the array at `prefix`.
31    ///
32    /// Substring matching can produce this, as can an explicit keyed-list field
33    /// when an externally authored document contains duplicate identities.
34    /// Naming several things at once is not an address, and picking the first
35    /// would silently answer a different question than the one asked, so it is
36    /// refused with structural candidate indices.
37    ///
38    /// Candidate text is deliberately absent: an error must not become a route
39    /// for document content to bypass normal output redaction.
40    AmbiguousMatch {
41        prefix: String,
42        segment: String,
43        indices: Vec<usize>,
44    },
45    NonFiniteNumber {
46        path: String,
47    },
48    UnaddressableSlug {
49        prefix: String,
50    },
51    SlugAlreadyExists {
52        prefix: String,
53        slug: String,
54    },
55    NotTraversable {
56        path: String,
57        got: String,
58    },
59    /// An operation over a container's children — a `*` in a path pattern —
60    /// found `null` at `path`. Distinct from [`Self::NotContainer`] because a
61    /// `null` is commonly an unset collection, which a caller may well want to
62    /// read as empty, while a scalar there is a real shape mismatch.
63    NullContainer {
64        path: String,
65    },
66    /// An operation over a container's children found a scalar at `path`.
67    /// `got` is a [`Value::kind_name`](crate::document::Value::kind_name).
68    NotContainer {
69        path: String,
70        got: String,
71    },
72    TypeMismatch {
73        path: String,
74        expected: String,
75        got: String,
76        hint: Option<String>,
77    },
78    PathNotFound {
79        path: String,
80    },
81    IndexOutOfBounds {
82        path: String,
83        index: usize,
84        len: usize,
85    },
86    /// A parser rejected the source. `detail` is the parser's own text, which
87    /// quotes the offending line — see [`Self::redacted_message`].
88    ParseError {
89        format: String,
90        detail: String,
91    },
92    /// A dot-path is malformed: a bad escape, a trailing `\`, a bare `*`, an
93    /// index past the platform's range.
94    ///
95    /// Distinct from [`Self::ParseError`] because nothing here came from the
96    /// document — the caller's own address is what failed to parse, and
97    /// `detail` is afdata's own words about it. Sharing a code with a rejected
98    /// *file* sent readers to inspect the wrong thing.
99    PathSyntax {
100        detail: String,
101    },
102    /// afdata declines to read a source its parser would accept, because it
103    /// cannot answer honestly about it.
104    ///
105    /// `detail` is authored here and names the way out; it holds no document
106    /// text, so [`Self::redacted_message`] keeps it. Distinct from
107    /// [`Self::ParseError`] because the file is not malformed — reporting it as
108    /// a parse failure sends the reader hunting for a syntax error that is not
109    /// there.
110    SourceRefused {
111        format: String,
112        detail: String,
113    },
114    /// A YAML edit targets a node whose bytes are shared: reached through an
115    /// alias, inside a value other sites alias, or inherited through a `<<`
116    /// merge key. Writing it would change a different set of keys than the one
117    /// named, so afdata declines. `detail` is afdata's own words and names the
118    /// way out; it holds no document text.
119    SharedNode {
120        operation: String,
121        path: String,
122        detail: String,
123    },
124    /// A caller argument contradicts itself or the document. `detail` is
125    /// afdata's own words about the argument, never document content.
126    InvalidArgument {
127        detail: String,
128    },
129    /// A staged edit rendered source that this format's own parser rejects or
130    /// that does not read back as the requested value, caught by the read-back
131    /// in `save_atomic` before any bytes reached disk.
132    ///
133    /// `detail` is already redacted: it comes from
134    /// [`Self::redacted_message`] of the rejection, not from its `Display`.
135    WriteWouldCorrupt {
136        format: String,
137        detail: String,
138    },
139    /// No format could be inferred for `path`, so nothing was parsed at all.
140    ///
141    /// Distinct from [`Self::ParseError`] because it is about the file's name,
142    /// never its contents: it carries no document text, and dropping its detail
143    /// as a precaution would throw away the only actionable thing it says.
144    FormatUnknown {
145        path: String,
146    },
147    /// A create-only commit found an existing target. Kept separate from
148    /// [`Self::IoError`] so callers can safely implement idempotent create
149    /// workflows without parsing platform-specific I/O messages.
150    AlreadyExists {
151        path: String,
152    },
153    /// A capped read found more bytes than the caller allowed. Kept separate
154    /// from [`Self::IoError`] for the same reason as [`Self::AlreadyExists`]: a
155    /// caller enforcing a size budget has to tell "too big" from "missing" or
156    /// "unreadable", and should not have to match on a message to do it.
157    TooLarge {
158        path: String,
159        max_bytes: u64,
160    },
161    /// The source held zero bytes and its format has no empty document (an
162    /// empty JSON text is not JSON). `source` names where the bytes came from
163    /// (`stdin` or a path) so the reader looks at the producer, not at syntax.
164    EmptyInput {
165        source: String,
166    },
167    /// The file was installed, but its crash durability could not be confirmed.
168    CommitUncertain {
169        detail: String,
170    },
171    IoError {
172        detail: String,
173    },
174    UnsupportedOperation {
175        format: String,
176        operation: String,
177        detail: String,
178    },
179}
180
181impl fmt::Display for DocumentError {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self {
184            DocumentError::EmptyPath => {
185                write!(f, "empty path provided")
186            }
187            DocumentError::EmptyValues => {
188                write!(f, "at least one value required")
189            }
190            DocumentError::UnknownSegment { path, segment } => {
191                write!(f, "path `{path}` segment `{segment}` not found")
192            }
193            DocumentError::UnregisteredArray { path } => {
194                write!(
195                    f,
196                    "array at `{path}` has no rule for naming an element by its content; \
197                     address an element by index, or name the field that identifies one"
198                )
199            }
200            DocumentError::SlugNotFound { prefix, slug } => {
201                write!(f, "no element with slug `{slug}` found in `{prefix}`")
202            }
203            DocumentError::NonFiniteNumber { path } => {
204                write!(
205                    f,
206                    "non-finite number at document path `{}`",
207                    if path.is_empty() { "<root>" } else { path }
208                )
209            }
210            DocumentError::UnaddressableSlug { prefix } => {
211                write!(
212                    f,
213                    "an element slug under `{prefix}` has no array path spelling: empty, numeric, and append-marker segments are reserved"
214                )
215            }
216            DocumentError::SlugAlreadyExists { prefix, slug } => {
217                write!(f, "slug `{slug}` already exists in `{prefix}`")
218            }
219            DocumentError::AmbiguousMatch {
220                prefix,
221                segment,
222                indices,
223            } => {
224                let candidates = indices
225                    .iter()
226                    .map(usize::to_string)
227                    .collect::<Vec<_>>()
228                    .join(", ");
229                write!(
230                    f,
231                    "segment `{}` matches {} elements of `{}` at indices {}",
232                    segment,
233                    indices.len(),
234                    prefix,
235                    candidates
236                )
237            }
238            // An empty prefix is the document itself: name it, and say what an empty
239            // document parses to, rather than print an empty pair of backticks.
240            DocumentError::NotTraversable { path, got } if path.is_empty() => {
241                if got == "null" {
242                    write!(
243                        f,
244                        "the document is empty (its root is null), cannot traverse into it"
245                    )
246                } else {
247                    write!(f, "the document root is {got}, cannot traverse into it")
248                }
249            }
250            DocumentError::NotTraversable { path, got } => {
251                write!(f, "path `{path}` is {got}, cannot traverse further")
252            }
253            DocumentError::NullContainer { path } if path.is_empty() => {
254                write!(
255                    f,
256                    "the document is empty (its root is null); there are no children"
257                )
258            }
259            DocumentError::NullContainer { path } => {
260                write!(f, "path `{path}` is null, so it has no children")
261            }
262            DocumentError::NotContainer { path, got } if path.is_empty() => {
263                write!(f, "the document root is {got}, which has no children")
264            }
265            DocumentError::NotContainer { path, got } => {
266                write!(f, "path `{path}` is {got}, which has no children")
267            }
268            DocumentError::TypeMismatch {
269                path,
270                expected,
271                got,
272                hint,
273            } => {
274                write!(f, "field `{path}` expects {expected}, got `{got}`")?;
275                if let Some(h) = hint {
276                    write!(f, "\n  hint: {h}")?;
277                }
278                Ok(())
279            }
280            DocumentError::PathNotFound { path } => {
281                write!(f, "path `{path}` not found in document")
282            }
283            DocumentError::IndexOutOfBounds { path, index, len } => {
284                write!(f, "index {index} out of bounds at `{path}` (len {len})")
285            }
286            DocumentError::ParseError { format, detail } => {
287                write!(f, "failed to parse {format}: {detail}")
288            }
289            DocumentError::PathSyntax { detail } => {
290                write!(f, "invalid path: {detail}")
291            }
292            DocumentError::SourceRefused { format, detail } => {
293                write!(f, "refusing to read this {format}: {detail}")
294            }
295            DocumentError::InvalidArgument { detail } => {
296                write!(f, "invalid argument: {detail}")
297            }
298            DocumentError::SharedNode {
299                operation,
300                path,
301                detail,
302            } => write!(f, "cannot {operation} `{path}`: {detail}"),
303            DocumentError::WriteWouldCorrupt { format, detail } => {
304                write!(
305                    f,
306                    "refusing to write: the edited {format} did not read back as the requested document ({detail}); the file is unchanged"
307                )
308            }
309            DocumentError::FormatUnknown { path } => {
310                write!(
311                    f,
312                    "cannot detect the format of `{path}` from its extension; pass an explicit format"
313                )
314            }
315            DocumentError::AlreadyExists { path } => {
316                write!(f, "document target `{path}` already exists")
317            }
318            DocumentError::TooLarge { path, max_bytes } => {
319                write!(f, "`{path}` exceeds the {max_bytes}-byte read limit")
320            }
321            DocumentError::EmptyInput { source } => {
322                write!(
323                    f,
324                    "{source} is empty (zero bytes); there is no document to read"
325                )
326            }
327            DocumentError::IoError { detail } | DocumentError::CommitUncertain { detail } => {
328                write!(f, "io error: {detail}")
329            }
330            DocumentError::UnsupportedOperation {
331                format,
332                operation,
333                detail,
334            } => write!(f, "{format} does not support {operation}: {detail}"),
335        }
336    }
337}
338
339impl std::error::Error for DocumentError {}
340
341impl DocumentError {
342    /// Whether a complete new file may already have been installed.
343    pub const fn commit_uncertain(&self) -> bool {
344        matches!(self, Self::CommitUncertain { .. })
345    }
346
347    /// Stable, program-decidable error code for this failure category.
348    ///
349    /// Multiple variants share a code only when callers should handle them in
350    /// the same way. An ordinary missing path is `document_path_not_found`;
351    /// named array lookup distinguishes a missing slug from an ambiguous one.
352    #[must_use]
353    pub const fn code(&self) -> &'static str {
354        match self {
355            Self::ParseError { .. } => "document_parse_failed",
356            Self::PathSyntax { .. } => "document_invalid_path",
357            Self::SourceRefused { .. } => "document_source_refused",
358            Self::SharedNode { .. } => "document_shared_node",
359            Self::FormatUnknown { .. } => "document_format_unknown",
360            Self::AlreadyExists { .. } => "document_target_exists",
361            Self::TooLarge { .. } => "document_too_large",
362            Self::WriteWouldCorrupt { .. } => "document_write_would_corrupt",
363            Self::PathNotFound { .. }
364            | Self::UnknownSegment { .. }
365            | Self::IndexOutOfBounds { .. }
366            | Self::UnregisteredArray { .. } => "document_path_not_found",
367            Self::NotTraversable { .. } | Self::TypeMismatch { .. } => "document_type_mismatch",
368            Self::NullContainer { .. } => "document_null_value",
369            Self::NotContainer { .. } => "document_not_container",
370            Self::SlugNotFound { .. } => "document_slug_not_found",
371            Self::AmbiguousMatch { .. } => "document_ambiguous_match",
372            Self::NonFiniteNumber { .. } => "document_non_finite_number",
373            Self::UnaddressableSlug { .. } => "document_unaddressable_key",
374            Self::SlugAlreadyExists { .. } => "document_slug_exists",
375            Self::EmptyInput { .. } => "document_empty",
376            Self::IoError { .. } | Self::CommitUncertain { .. } => "document_io_failed",
377            Self::UnsupportedOperation { .. } => "document_unsupported_operation",
378            Self::EmptyPath | Self::EmptyValues | Self::InvalidArgument { .. } => {
379                "document_invalid_argument"
380            }
381        }
382    }
383
384    /// Whether this error means "nothing is at that address": the family a
385    /// caller with a fallback for an absent value is entitled to swallow.
386    ///
387    /// A structural miss (no such key, an index past the end, an array nothing
388    /// names elements of) and a named miss (no element matched) qualify, and so
389    /// does a path that runs *through* a scalar ([`Self::NotTraversable`]):
390    /// nothing is at `b.version` when `b` is a string either.
391    /// [`Self::AmbiguousMatch`] deliberately does not — several elements
392    /// answered, so there is something there, just not one thing — and neither
393    /// does a [`Self::TypeMismatch`], which is a real fault.
394    #[must_use]
395    pub fn is_address_miss(&self) -> bool {
396        matches!(
397            self,
398            Self::PathNotFound { .. }
399                | Self::UnknownSegment { .. }
400                | Self::IndexOutOfBounds { .. }
401                | Self::UnregisteredArray { .. }
402                | Self::SlugNotFound { .. }
403                | Self::NotTraversable { .. }
404        )
405    }
406
407    /// Best-effort, content-free source location for a parse failure.
408    ///
409    /// Returns e.g. `"line 5 column 12"` (or `"line 5"`) for a
410    /// [`DocumentError::ParseError`], and `None` for every other variant or
411    /// when the underlying parser reported no position. The returned string is
412    /// derived from the parser's position only and never contains document
413    /// content, so it is safe to surface even when the parsed file may hold
414    /// secrets.
415    #[must_use]
416    pub fn location(&self) -> Option<String> {
417        let Self::ParseError { detail, .. } = self else {
418            return None;
419        };
420        // A parser diagnostic opens with its own position and echoes the
421        // offending source on the lines below it:
422        //
423        //     TOML parse error at line 2, column 5
424        //       |
425        //     2 | note = "see at line 999 for details" bad
426        //
427        // So the position is on the first line and document content never is.
428        // Searching the whole detail — from either end — can read the echo:
429        // from the end it finds `at line 999`, which is the file's own text.
430        let head = detail.split('\n').next().unwrap_or(detail);
431        let rest = match head.split_once(" at line ") {
432            Some((_, rest)) => rest,
433            None => head.strip_prefix("line ")?,
434        };
435        let line = leading_ascii_digits(rest)?;
436        let column = rest
437            .split_once("column ")
438            .and_then(|(_, tail)| leading_ascii_digits(tail));
439        Some(match column {
440            Some(column) => format!("line {line} column {column}"),
441            None => format!("line {line}"),
442        })
443    }
444
445    /// A display message with any potentially content-bearing detail removed —
446    /// safe to surface when the document may hold secrets.
447    ///
448    /// Two variants can quote material that originates in the document and are
449    /// rewritten here:
450    ///
451    /// - [`DocumentError::ParseError`] renders as `failed to parse {format}`
452    ///   (with the [`location`](Self::location) appended when known), dropping
453    ///   the parser detail, which echoes a snippet of the source.
454    ///
455    /// [`DocumentError::PathSyntax`], [`DocumentError::SourceRefused`] and
456    /// [`DocumentError::InvalidArgument`] keep their detail in full. It is the
457    /// reason they exist as separate variants: their text is written here, about
458    /// the caller's address, argument, or file *encoding* — never lifted from
459    /// document content — and it is the only part that says what to do next.
460    /// Dropping it as a precaution against a leak that cannot happen turned an
461    /// actionable refusal into `failed to parse Markdown`.
462    /// - [`DocumentError::TypeMismatch`] drops `got` and `hint`. When built by
463    ///   [`Self::from_serde`] those carry serde's rendering of the offending
464    ///   value, which is document content.
465    ///
466    /// Every other variant renders the same as its [`std::fmt::Display`], carrying only
467    /// structural context: paths, requested slugs, indices, and type or format
468    /// names. In particular, [`Self::AmbiguousMatch`] carries candidate indices
469    /// rather than matched field values.
470    /// [`DocumentError::NotTraversable`] belongs to that group because `got` is
471    /// a [`Value::kind_name`](crate::document::Value::kind_name), not a value.
472    #[must_use]
473    pub fn redacted_message(&self) -> String {
474        match self {
475            // afdata's own sentence about a binary property list read as the
476            // wrong format: it names the flag and quotes nothing from the file.
477            #[cfg(feature = "plist")]
478            Self::ParseError { detail, .. }
479                if detail == crate::document::format::plist::WRONG_FORMAT_DETAIL
480                    || detail == crate::document::format::plist::WRONG_FORMAT_XML_DETAIL =>
481            {
482                self.to_string()
483            }
484            Self::ParseError { format, .. } => match self.location() {
485                Some(location) => format!("failed to parse {format} at {location}"),
486                None => format!("failed to parse {format}"),
487            },
488            Self::TypeMismatch { path, expected, .. } => {
489                if expected.is_empty() {
490                    format!("field `{path}` has the wrong type")
491                } else {
492                    format!("field `{path}` expects {expected}")
493                }
494            }
495            other => other.to_string(),
496        }
497    }
498
499    /// Wrap a serde deserialization failure as a `TypeMismatch` so callers that
500    /// do a read-modify-write cycle (set_path → serde round-trip) surface a
501    /// consistent error style rather than a raw serde message.
502    pub fn from_serde(path: impl Into<String>, err: impl std::fmt::Display) -> Self {
503        let msg = err.to_string();
504        // serde messages look like "invalid type: string \"x\", expected u16 at …"
505        // Strip the trailing " at line N column M" to keep the hint concise.
506        let hint = msg
507            .split(" at line ")
508            .next()
509            .unwrap_or(&msg)
510            .trim()
511            .to_string();
512        DocumentError::TypeMismatch {
513            path: path.into(),
514            expected: String::new(),
515            got: hint,
516            hint: None,
517        }
518    }
519}
520
521impl From<io::Error> for DocumentError {
522    fn from(err: io::Error) -> Self {
523        DocumentError::IoError {
524            detail: err.to_string(),
525        }
526    }
527}
528
529fn leading_ascii_digits(text: &str) -> Option<&str> {
530    let end = text.bytes().take_while(u8::is_ascii_digit).count();
531    (end > 0).then_some(&text[..end])
532}
533
534#[cfg(test)]
535mod tests {
536    use super::DocumentError;
537
538    #[test]
539    fn document_error_codes_are_stable() {
540        let cases = [
541            (DocumentError::EmptyPath, "document_invalid_argument"),
542            (DocumentError::EmptyValues, "document_invalid_argument"),
543            (
544                DocumentError::UnknownSegment {
545                    path: "root.key".to_string(),
546                    segment: "key".to_string(),
547                },
548                "document_path_not_found",
549            ),
550            (
551                DocumentError::UnregisteredArray {
552                    path: "items".to_string(),
553                },
554                "document_path_not_found",
555            ),
556            (
557                DocumentError::SlugNotFound {
558                    prefix: "items".to_string(),
559                    slug: "missing".to_string(),
560                },
561                "document_slug_not_found",
562            ),
563            (
564                DocumentError::SlugAlreadyExists {
565                    prefix: "items".to_string(),
566                    slug: "existing".to_string(),
567                },
568                "document_slug_exists",
569            ),
570            (
571                DocumentError::AmbiguousMatch {
572                    prefix: "items".to_string(),
573                    segment: "look".to_string(),
574                    indices: vec![0, 2],
575                },
576                "document_ambiguous_match",
577            ),
578            (
579                DocumentError::NotTraversable {
580                    path: "root".to_string(),
581                    got: "string".to_string(),
582                },
583                "document_type_mismatch",
584            ),
585            (
586                DocumentError::TypeMismatch {
587                    path: "root.key".to_string(),
588                    expected: "integer".to_string(),
589                    got: "string".to_string(),
590                    hint: None,
591                },
592                "document_type_mismatch",
593            ),
594            (
595                DocumentError::PathNotFound {
596                    path: "root.key".to_string(),
597                },
598                "document_path_not_found",
599            ),
600            (
601                DocumentError::EmptyInput {
602                    source: "stdin".to_string(),
603                },
604                "document_empty",
605            ),
606            (
607                DocumentError::IndexOutOfBounds {
608                    path: "items".to_string(),
609                    index: 2,
610                    len: 1,
611                },
612                "document_path_not_found",
613            ),
614            (
615                DocumentError::ParseError {
616                    format: "JSON".to_string(),
617                    detail: "invalid input".to_string(),
618                },
619                "document_parse_failed",
620            ),
621            (
622                DocumentError::IoError {
623                    detail: "unreadable".to_string(),
624                },
625                "document_io_failed",
626            ),
627            (
628                DocumentError::AlreadyExists {
629                    path: "config.toml".to_string(),
630                },
631                "document_target_exists",
632            ),
633            (
634                DocumentError::TooLarge {
635                    path: "config.toml".to_string(),
636                    max_bytes: 1024,
637                },
638                "document_too_large",
639            ),
640            (
641                DocumentError::UnsupportedOperation {
642                    format: "INI".to_string(),
643                    operation: "set".to_string(),
644                    detail: "unsupported".to_string(),
645                },
646                "document_unsupported_operation",
647            ),
648        ];
649
650        for (error, expected) in cases {
651            assert_eq!(error.code(), expected);
652        }
653    }
654
655    #[test]
656    fn location_extracts_position_without_content() {
657        // The real layout a parser produces: its own position first, then the
658        // offending source echoed below. The echo here carries `at line 999`
659        // out of the document, and a search from the end reads exactly that —
660        // reporting a wrong line and leaking a document-derived number through
661        // `redacted_message`, which promises never to surface file content.
662        let err = DocumentError::ParseError {
663            format: "TOML".to_string(),
664            detail: "TOML parse error at line 5, column 12\n  |\n\
665                     5 | note = \"see at line 999 for TOPSECRET\" bad\n  |     ^"
666                .to_string(),
667        };
668        assert_eq!(err.location().as_deref(), Some("line 5 column 12"));
669        assert!(!err.redacted_message().contains("999"));
670        assert!(!err.redacted_message().contains("TOPSECRET"));
671
672        let no_column = DocumentError::ParseError {
673            format: "JSON".to_string(),
674            detail: "boom at line 3".to_string(),
675        };
676        assert_eq!(no_column.location().as_deref(), Some("line 3"));
677
678        // No position, and non-parse variants, carry no location.
679        assert!(
680            DocumentError::ParseError {
681                format: "INI".to_string(),
682                detail: "sensitive value".to_string(),
683            }
684            .location()
685            .is_none()
686        );
687        assert!(
688            DocumentError::PathNotFound {
689                path: "a.b".to_string(),
690            }
691            .location()
692            .is_none()
693        );
694    }
695
696    #[test]
697    fn redacted_message_drops_parser_detail() {
698        let err = DocumentError::ParseError {
699            format: "YAML".to_string(),
700            detail: "unexpected TOPSECRET at line 5 column 12".to_string(),
701        };
702        let redacted = err.redacted_message();
703        assert_eq!(redacted, "failed to parse YAML at line 5 column 12");
704        assert!(!redacted.contains("TOPSECRET"));
705
706        // Structural variants pass through unchanged.
707        let path_err = DocumentError::PathNotFound {
708            path: "database.url".to_string(),
709        };
710        assert_eq!(path_err.redacted_message(), path_err.to_string());
711    }
712
713    #[test]
714    fn redacted_message_drops_the_offending_value() {
715        // `from_serde` keeps serde's rendering, which quotes the value that
716        // failed the type check — document content, and a secret as often as not.
717        let err = DocumentError::from_serde(
718            "credentials.token",
719            "invalid type: string \"sk-live-TOPSECRET\", expected u16",
720        );
721        assert!(err.to_string().contains("sk-live-TOPSECRET"));
722        let redacted = err.redacted_message();
723        assert!(!redacted.contains("sk-live-TOPSECRET"), "{redacted}");
724        assert!(redacted.contains("credentials.token"), "{redacted}");
725    }
726
727    #[test]
728    fn ambiguous_match_reports_indices_without_document_content() {
729        let err = DocumentError::AmbiguousMatch {
730            prefix: "h1.0.h2".to_string(),
731            segment: "look".to_string(),
732            indices: vec![0, 2],
733        };
734        assert_eq!(
735            err.redacted_message(),
736            "segment `look` matches 2 elements of `h1.0.h2` at indices 0, 2"
737        );
738        assert!(!err.redacted_message().contains("Quick look"));
739    }
740
741    #[test]
742    fn not_traversable_names_the_type_not_the_value() {
743        // This one is safe by construction rather than by redaction: `got` is a
744        // kind name, so even `Display` cannot echo the leaf.
745        let err = DocumentError::NotTraversable {
746            path: "token_secret.inner".to_string(),
747            got: crate::document::Value::String("sk-live-TOPSECRET".to_string())
748                .kind_name()
749                .to_string(),
750        };
751        assert_eq!(
752            err.to_string(),
753            "path `token_secret.inner` is string, cannot traverse further"
754        );
755        assert_eq!(err.redacted_message(), err.to_string());
756    }
757
758    #[test]
759    fn not_traversable_at_the_root_names_the_document() {
760        let empty = DocumentError::NotTraversable {
761            path: String::new(),
762            got: "null".to_string(),
763        };
764        assert_eq!(
765            empty.to_string(),
766            "the document is empty (its root is null), cannot traverse into it"
767        );
768        let scalar = DocumentError::NotTraversable {
769            path: String::new(),
770            got: "string".to_string(),
771        };
772        assert_eq!(
773            scalar.to_string(),
774            "the document root is string, cannot traverse into it"
775        );
776    }
777}