agent-first-data 0.28.1

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
//! Error types with context and helpful hints.

use std::fmt;
use std::io;

pub type DocumentResult<T> = Result<T, DocumentError>;

#[derive(Debug, Clone)]
pub enum DocumentError {
    EmptyPath,
    EmptyValues,
    UnknownSegment {
        path: String,
        segment: String,
    },
    UnregisteredArray {
        path: String,
    },
    SlugNotFound {
        prefix: String,
        slug: String,
    },
    SlugAlreadyExists {
        prefix: String,
        slug: String,
    },
    NotTraversable {
        path: String,
        got: String,
    },
    TypeMismatch {
        path: String,
        expected: String,
        got: String,
        hint: Option<String>,
    },
    PathNotFound {
        path: String,
    },
    IndexOutOfBounds {
        path: String,
        index: usize,
        len: usize,
    },
    /// A parser rejected the source. `detail` is the parser's own text, which
    /// quotes the offending line — see [`Self::redacted_message`].
    ParseError {
        format: String,
        detail: String,
    },
    /// A staged edit rendered source this format's own parser rejects, caught
    /// by the read-back in `save_atomic` before any bytes reached disk.
    ///
    /// `detail` is already redacted: it comes from
    /// [`Self::redacted_message`] of the rejection, not from its `Display`.
    WriteWouldCorrupt {
        format: String,
        detail: String,
    },
    /// No format could be inferred for `path`, so nothing was parsed at all.
    ///
    /// Distinct from [`Self::ParseError`] because it is about the file's name,
    /// never its contents: it carries no document text, and dropping its detail
    /// as a precaution would throw away the only actionable thing it says.
    FormatUnknown {
        path: String,
    },
    IoError {
        detail: String,
    },
    UnsupportedOperation {
        format: String,
        operation: String,
        detail: String,
    },
}

impl fmt::Display for DocumentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DocumentError::EmptyPath => {
                write!(f, "empty path provided")
            }
            DocumentError::EmptyValues => {
                write!(f, "at least one value required")
            }
            DocumentError::UnknownSegment { path, segment } => {
                write!(f, "path `{}` segment `{}` not found", path, segment)
            }
            DocumentError::UnregisteredArray { path } => {
                write!(f, "array at `{}` not registered in KeyedList", path)
            }
            DocumentError::SlugNotFound { prefix, slug } => {
                write!(f, "no element with slug `{}` found in `{}`", slug, prefix)
            }
            DocumentError::SlugAlreadyExists { prefix, slug } => {
                write!(f, "slug `{}` already exists in `{}`", slug, prefix)
            }
            DocumentError::NotTraversable { path, got } => {
                write!(f, "path `{}` is {}, cannot traverse further", path, got)
            }
            DocumentError::TypeMismatch {
                path,
                expected,
                got,
                hint,
            } => {
                write!(f, "field `{}` expects {}, got `{}`", path, expected, got)?;
                if let Some(h) = hint {
                    write!(f, "\n  hint: {}", h)?;
                }
                Ok(())
            }
            DocumentError::PathNotFound { path } => {
                write!(f, "path `{}` not found in document", path)
            }
            DocumentError::IndexOutOfBounds { path, index, len } => {
                write!(
                    f,
                    "index {} out of bounds at `{}` (len {})",
                    index, path, len
                )
            }
            DocumentError::ParseError { format, detail } => {
                write!(f, "failed to parse {}: {}", format, detail)
            }
            DocumentError::WriteWouldCorrupt { format, detail } => {
                write!(
                    f,
                    "refusing to write: the edit produced {} this parser rejects ({}); the file is unchanged",
                    format, detail
                )
            }
            DocumentError::FormatUnknown { path } => {
                write!(
                    f,
                    "cannot detect format from file extension `{}`; pass an explicit format",
                    path
                )
            }
            DocumentError::IoError { detail } => {
                write!(f, "io error: {}", detail)
            }
            DocumentError::UnsupportedOperation {
                format,
                operation,
                detail,
            } => write!(f, "{} does not support {}: {}", format, operation, detail),
        }
    }
}

impl std::error::Error for DocumentError {}

impl DocumentError {
    /// Stable, program-decidable error code for this failure category.
    ///
    /// Multiple variants can share a code when callers should handle them in
    /// the same way. In particular, all read-address failures report
    /// `document_path_not_found`.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        match self {
            Self::ParseError { .. } => "document_parse_failed",
            Self::FormatUnknown { .. } => "document_format_unknown",
            Self::WriteWouldCorrupt { .. } => "document_write_would_corrupt",
            Self::PathNotFound { .. }
            | Self::UnknownSegment { .. }
            | Self::IndexOutOfBounds { .. }
            | Self::UnregisteredArray { .. } => "document_path_not_found",
            Self::NotTraversable { .. } | Self::TypeMismatch { .. } => "document_type_mismatch",
            Self::SlugNotFound { .. } => "document_slug_not_found",
            Self::SlugAlreadyExists { .. } => "document_slug_exists",
            Self::IoError { .. } => "document_io_failed",
            Self::UnsupportedOperation { .. } => "document_unsupported_operation",
            Self::EmptyPath | Self::EmptyValues => "document_invalid_argument",
        }
    }

    /// Best-effort, content-free source location for a parse failure.
    ///
    /// Returns e.g. `"line 5 column 12"` (or `"line 5"`) for a
    /// [`DocumentError::ParseError`], and `None` for every other variant or
    /// when the underlying parser reported no position. The returned string is
    /// derived from the parser's position only and never contains document
    /// content, so it is safe to surface even when the parsed file may hold
    /// secrets.
    #[must_use]
    pub fn location(&self) -> Option<String> {
        let Self::ParseError { detail, .. } = self else {
            return None;
        };
        let rest = &detail[detail.find("line ")? + 5..];
        let line: String = rest.chars().take_while(char::is_ascii_digit).collect();
        if line.is_empty() {
            return None;
        }
        let column = rest
            .find("column ")
            .map(|start| &rest[start + 7..])
            .map(|tail| {
                tail.chars()
                    .take_while(char::is_ascii_digit)
                    .collect::<String>()
            })
            .filter(|value| !value.is_empty());
        Some(match column {
            Some(column) => format!("line {line} column {column}"),
            None => format!("line {line}"),
        })
    }

    /// A display message with any potentially content-bearing detail removed —
    /// safe to surface when the document may hold secrets.
    ///
    /// Two variants quote material that originates in the document and are
    /// rewritten here:
    ///
    /// - [`DocumentError::ParseError`] renders as `failed to parse {format}`
    ///   (with the [`location`](Self::location) appended when known), dropping
    ///   the parser detail, which echoes a snippet of the source.
    /// - [`DocumentError::TypeMismatch`] drops `got` and `hint`. When built by
    ///   [`Self::from_serde`] those carry serde's rendering of the offending
    ///   value, which is document content.
    ///
    /// Every other variant renders the same as its [`Display`], carrying only
    /// structural context: paths, slugs, indices, and type or format names.
    /// [`DocumentError::NotTraversable`] belongs to that group because `got` is
    /// a [`Value::kind_name`](crate::document::Value::kind_name), not a value.
    #[must_use]
    pub fn redacted_message(&self) -> String {
        match self {
            Self::ParseError { format, .. } => match self.location() {
                Some(location) => format!("failed to parse {format} at {location}"),
                None => format!("failed to parse {format}"),
            },
            Self::TypeMismatch { path, expected, .. } => {
                if expected.is_empty() {
                    format!("field `{path}` has the wrong type")
                } else {
                    format!("field `{path}` expects {expected}")
                }
            }
            other => other.to_string(),
        }
    }

    /// Wrap a serde deserialization failure as a `TypeMismatch` so callers that
    /// do a read-modify-write cycle (set_path → serde round-trip) surface a
    /// consistent error style rather than a raw serde message.
    pub fn from_serde(path: impl Into<String>, err: impl std::fmt::Display) -> Self {
        let msg = err.to_string();
        // serde messages look like "invalid type: string \"x\", expected u16 at …"
        // Strip the trailing " at line N column M" to keep the hint concise.
        let hint = msg
            .split(" at line ")
            .next()
            .unwrap_or(&msg)
            .trim()
            .to_string();
        DocumentError::TypeMismatch {
            path: path.into(),
            expected: String::new(),
            got: hint,
            hint: None,
        }
    }
}

impl From<io::Error> for DocumentError {
    fn from(err: io::Error) -> Self {
        DocumentError::IoError {
            detail: err.to_string(),
        }
    }
}

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

    #[test]
    fn document_error_codes_are_stable() {
        let cases = [
            (DocumentError::EmptyPath, "document_invalid_argument"),
            (DocumentError::EmptyValues, "document_invalid_argument"),
            (
                DocumentError::UnknownSegment {
                    path: "root.key".to_string(),
                    segment: "key".to_string(),
                },
                "document_path_not_found",
            ),
            (
                DocumentError::UnregisteredArray {
                    path: "items".to_string(),
                },
                "document_path_not_found",
            ),
            (
                DocumentError::SlugNotFound {
                    prefix: "items".to_string(),
                    slug: "missing".to_string(),
                },
                "document_slug_not_found",
            ),
            (
                DocumentError::SlugAlreadyExists {
                    prefix: "items".to_string(),
                    slug: "existing".to_string(),
                },
                "document_slug_exists",
            ),
            (
                DocumentError::NotTraversable {
                    path: "root".to_string(),
                    got: "string".to_string(),
                },
                "document_type_mismatch",
            ),
            (
                DocumentError::TypeMismatch {
                    path: "root.key".to_string(),
                    expected: "integer".to_string(),
                    got: "string".to_string(),
                    hint: None,
                },
                "document_type_mismatch",
            ),
            (
                DocumentError::PathNotFound {
                    path: "root.key".to_string(),
                },
                "document_path_not_found",
            ),
            (
                DocumentError::IndexOutOfBounds {
                    path: "items".to_string(),
                    index: 2,
                    len: 1,
                },
                "document_path_not_found",
            ),
            (
                DocumentError::ParseError {
                    format: "JSON".to_string(),
                    detail: "invalid input".to_string(),
                },
                "document_parse_failed",
            ),
            (
                DocumentError::IoError {
                    detail: "unreadable".to_string(),
                },
                "document_io_failed",
            ),
            (
                DocumentError::UnsupportedOperation {
                    format: "INI".to_string(),
                    operation: "set".to_string(),
                    detail: "unsupported".to_string(),
                },
                "document_unsupported_operation",
            ),
        ];

        for (error, expected) in cases {
            assert_eq!(error.code(), expected);
        }
    }

    #[test]
    fn location_extracts_position_without_content() {
        let err = DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: "secret: [ TOPSECRET at line 5 column 12".to_string(),
        };
        assert_eq!(err.location().as_deref(), Some("line 5 column 12"));

        let no_column = DocumentError::ParseError {
            format: "JSON".to_string(),
            detail: "boom at line 3".to_string(),
        };
        assert_eq!(no_column.location().as_deref(), Some("line 3"));

        // No position, and non-parse variants, carry no location.
        assert!(
            DocumentError::ParseError {
                format: "INI".to_string(),
                detail: "sensitive value".to_string(),
            }
            .location()
            .is_none()
        );
        assert!(
            DocumentError::PathNotFound {
                path: "a.b".to_string(),
            }
            .location()
            .is_none()
        );
    }

    #[test]
    fn redacted_message_drops_parser_detail() {
        let err = DocumentError::ParseError {
            format: "YAML".to_string(),
            detail: "unexpected TOPSECRET at line 5 column 12".to_string(),
        };
        let redacted = err.redacted_message();
        assert_eq!(redacted, "failed to parse YAML at line 5 column 12");
        assert!(!redacted.contains("TOPSECRET"));

        // Structural variants pass through unchanged.
        let path_err = DocumentError::PathNotFound {
            path: "database.url".to_string(),
        };
        assert_eq!(path_err.redacted_message(), path_err.to_string());
    }

    #[test]
    fn redacted_message_drops_the_offending_value() {
        // `from_serde` keeps serde's rendering, which quotes the value that
        // failed the type check — document content, and a secret as often as not.
        let err = DocumentError::from_serde(
            "credentials.token",
            "invalid type: string \"sk-live-TOPSECRET\", expected u16",
        );
        assert!(err.to_string().contains("sk-live-TOPSECRET"));
        let redacted = err.redacted_message();
        assert!(!redacted.contains("sk-live-TOPSECRET"), "{redacted}");
        assert!(redacted.contains("credentials.token"), "{redacted}");
    }

    #[test]
    fn not_traversable_names_the_type_not_the_value() {
        // This one is safe by construction rather than by redaction: `got` is a
        // kind name, so even `Display` cannot echo the leaf.
        let err = DocumentError::NotTraversable {
            path: "token_secret.inner".to_string(),
            got: crate::document::Value::String("sk-live-TOPSECRET".to_string())
                .kind_name()
                .to_string(),
        };
        assert_eq!(
            err.to_string(),
            "path `token_secret.inner` is string, cannot traverse further"
        );
        assert_eq!(err.redacted_message(), err.to_string());
    }
}