agent-first-data 0.41.0

Self-describing data and structured CLI contracts for AI agents — field-name suffixes for units and secrets, the afdata CLI for rendering, validation, path guards, and reading or editing structured documents (JSON, TOML, YAML, dotenv, INI, Markdown), plus libraries for Rust, Go, Python, TypeScript, and Bash.
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
//! In-process AFDATA naming and serialized-output checks.

use crate::lint_input::{Visitor, join_pointer, parse_json_number_text, walk};
use crate::suffix::{currency_code, has_registered_suffix, has_suffix_ci};
use crate::{
    ProtocolViolation, is_valid_bcp47, is_valid_rfc3339, is_valid_rfc3339_date,
    is_valid_rfc3339_time, normalize_utc_offset, validate_protocol_event,
};
use serde::Serialize;
use serde_json::{Number, Value};
use std::fmt;

const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;

/// One deterministic AFDATA lint finding.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct LintFinding {
    pub rule_id: String,
    pub pointer: String,
    pub message: String,
}

impl LintFinding {
    fn new(rule_id: &str, pointer: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            rule_id: rule_id.to_owned(),
            pointer: pointer.into(),
            message: message.into(),
        }
    }
}

/// Describes the input to contract validation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LintOptions {
    untyped_text_scalars: bool,
    schema_properties: bool,
}

impl LintOptions {
    /// Typed runtime data, including ordinary fields named `properties`.
    pub const fn new() -> Self {
        Self {
            untyped_text_scalars: false,
            schema_properties: false,
        }
    }

    /// Treat data scalars as untyped text (for dotenv and INI).
    pub const fn untyped_text_scalars(mut self, untyped_text_scalars: bool) -> Self {
        self.untyped_text_scalars = untyped_text_scalars;
        self
    }

    /// Interpret property declarations in a schema or API description.
    pub const fn schema_properties(mut self) -> Self {
        self.schema_properties = true;
        self
    }
}

/// Lint an actual serialized JSON value in-process.
pub fn lint_value(value: &Value, options: LintOptions) -> Vec<LintFinding> {
    lint_value_with_key(value, None, options)
}

/// Lint a field value supplied separately from its key, as in a model update.
/// Findings use JSON pointers relative to the supplied value.
pub fn lint_field_value(key: &str, value: &Value, options: LintOptions) -> Vec<LintFinding> {
    lint_value_with_key(value, Some(key), options)
}

fn lint_value_with_key(value: &Value, key: Option<&str>, options: LintOptions) -> Vec<LintFinding> {
    let mut checks = ContractChecks {
        untyped: options.untyped_text_scalars,
        findings: Vec::new(),
    };
    walk(&mut checks, value, key, "", options.schema_properties);
    checks.findings
}

struct ContractChecks {
    untyped: bool,
    findings: Vec<LintFinding>,
}

impl Visitor for ContractChecks {
    fn field(&mut self, key: &str, value: &Value, pointer: &str) {
        lint_suffix_type(key, value, pointer, self.untyped, &mut self.findings);
    }

    fn number(&mut self, number: &Number, pointer: &str) {
        if crate::formatting::number_is_integer_literal(number)
            && !number
                .as_i64()
                .is_some_and(|n| n.unsigned_abs() <= MAX_SAFE_INTEGER)
        {
            self.findings.push(LintFinding::new(
                "unsafe_integer",
                pointer,
                "integer exceeds JavaScript safe integer range ±(2^53-1)",
            ));
        }
    }

    fn literal(&mut self, name: &str, value: &Value, pointer: &str) {
        if has_suffix_ci(name, "_secret") && !is_redacted_secret_literal(value) {
            self.findings.push(LintFinding::new(
                "secret_schema_value_exposed",
                pointer,
                format!("schema property {name:?} exposes a secret literal"),
            ));
        }
        self.field(name, value, pointer);
    }

    fn property(&mut self, name: &str, schema: &Value, pointer: &str) {
        lint_schema_suffix_type(name, schema, pointer, &mut self.findings);
    }
}

/// Assert the recommended strict protocol profile without spawning the CLI.
pub fn assert_strict_event(value: &Value) -> Result<(), ProtocolViolation> {
    validate_protocol_event(value, true)
}

/// Return all contract violations in typed runtime data.
pub fn assert_no_lint_findings(value: &Value) -> Result<(), Vec<LintFinding>> {
    let findings = lint_value(value, LintOptions::default());
    if findings.is_empty() {
        Ok(())
    } else {
        Err(findings)
    }
}

/// Failure from [`assert_redaction_canary_absent`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RedactionCanaryError {
    EmptyCanary,
    /// The canary is present in the output or in one of its decoded layers.
    Exposed,
    /// Layered encoding was still changing when the decoding budget ran out,
    /// so absence could not be shown. A failure, but not a confirmed leak.
    InspectionLimitExceeded,
}

impl fmt::Display for RedactionCanaryError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyCanary => formatter.write_str("redaction canary must not be empty"),
            Self::Exposed => formatter.write_str("redaction canary remains in serialized output"),
            Self::InspectionLimitExceeded => formatter.write_str(
                "serialized output is still encoded after the inspection limit; canary absence is unproven",
            ),
        }
    }
}

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

/// Verify that a unique test canary is absent from final serialized output.
///
/// Pass the string returned by [`crate::render`] or an HTTP/body serializer,
/// not the pre-redaction input value.
///
/// Every renderer escapes a string before it reaches the stream, so a canary
/// can be present verbatim yet unfindable by a raw substring search: a PEM key
/// carries newlines, a password may carry `"`, a Windows path carries `\`, and
/// a canary inside a `_url` value is percent-encoded. This checks the raw text
/// *and* decoded copies until no escapes change, so nested URL encoding and
/// serialization escapes cannot hide a leak. Decoding the haystack rather than
/// enumerating the escaped spellings of the canary keeps the check from
/// drifting when a renderer changes, and biases it the safe way: an over-eager
/// decode can only raise a false alarm, never pass a real leak. Inspection is
/// bounded to 64 decoding passes; encoding that still changes at that bound
/// fails closed as [`RedactionCanaryError::InspectionLimitExceeded`].
pub fn assert_redaction_canary_absent(
    serialized: &str,
    canary: &str,
) -> Result<(), RedactionCanaryError> {
    if canary.is_empty() {
        return Err(RedactionCanaryError::EmptyCanary);
    }
    let mut current = std::borrow::Cow::Borrowed(serialized);
    // Deep percent chains otherwise remove only two bytes per full scan,
    // making a small encoded prefix plus a large body quadratic to inspect.
    for _ in 0..64 {
        if current.contains(canary) {
            return Err(RedactionCanaryError::Exposed);
        }
        let decoded = decode_output_escapes(&current);
        if decoded == current {
            return Ok(());
        }
        current = std::borrow::Cow::Owned(decoded);
    }
    Err(RedactionCanaryError::InspectionLimitExceeded)
}

/// Undo every escape AFDATA output can introduce: JSON and YAML string escapes,
/// logfmt quoting, and percent-encoding inside a URL.
///
/// Only used to widen the canary search, so an unrecognized escape is left
/// alone rather than guessed at.
fn decode_output_escapes(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'\\' => match decode_backslash_escape(&bytes[index + 1..]) {
                Some((decoded, consumed)) => {
                    out.extend_from_slice(decoded.as_bytes());
                    index += 1 + consumed;
                }
                None => {
                    out.push(bytes[index]);
                    index += 1;
                }
            },
            b'%' => match percent_byte(&bytes[index + 1..]) {
                Some(byte) => {
                    out.push(byte);
                    index += 3;
                }
                None => {
                    out.push(bytes[index]);
                    index += 1;
                }
            },
            other => {
                out.push(other);
                index += 1;
            }
        }
    }
    String::from_utf8_lossy_owned(out)
}

/// Decode one escape body (the bytes after a `\`), returning it with the number
/// of bytes consumed.
fn decode_backslash_escape(rest: &[u8]) -> Option<(String, usize)> {
    let simple = |character: char| Some((character.to_string(), 1));
    match *rest.first()? {
        b'n' => simple('\n'),
        b'r' => simple('\r'),
        b't' => simple('\t'),
        b'b' => simple('\u{0008}'),
        b'f' => simple('\u{000c}'),
        b'v' => simple('\u{000b}'),
        b'0' => simple('\0'),
        b'\\' => simple('\\'),
        b'"' => simple('"'),
        b'/' => simple('/'),
        b'u' => {
            let first = hex4(rest.get(1..)?)?;
            // A non-BMP character is escaped as a surrogate pair; decoding the
            // halves separately would lose the character entirely.
            if (0xd800..0xdc00).contains(&first) {
                let low = rest
                    .get(5..7)
                    .filter(|marker| *marker == b"\\u".as_slice())
                    .and_then(|_| rest.get(7..))
                    .and_then(hex4)
                    .filter(|value| (0xdc00..0xe000).contains(value))?;
                let combined = 0x10000 + ((first - 0xd800) << 10) + (low - 0xdc00);
                return char::from_u32(combined).map(|character| (character.to_string(), 11));
            }
            char::from_u32(first).map(|character| (character.to_string(), 5))
        }
        _ => None,
    }
}

fn hex4(bytes: &[u8]) -> Option<u32> {
    let digits = bytes.get(..4)?;
    std::str::from_utf8(digits)
        .ok()
        .and_then(|text| u32::from_str_radix(text, 16).ok())
}

fn percent_byte(rest: &[u8]) -> Option<u8> {
    let digits = rest.get(..2)?;
    std::str::from_utf8(digits)
        .ok()
        .and_then(|text| u8::from_str_radix(text, 16).ok())
}

fn lint_schema_suffix_type(
    name: &str,
    schema: &Value,
    pointer: &str,
    findings: &mut Vec<LintFinding>,
) {
    let has = |suffix| has_suffix_ci(name, suffix);
    let (types, description): (&[&str], &str) = if has("_bytes") {
        (&["integer"], "an integer byte count")
    } else if has("_epoch_s") || has("_epoch_ms") {
        (&["integer"], "an integer epoch timestamp")
    } else if has("_epoch_ns") {
        (&["string"], "a decimal integer string")
    } else if has("_sats") || has("_msats") {
        (
            &["integer", "string"],
            "an integer or decimal integer string",
        )
    } else if has("_percent") || is_duration_suffix(name) {
        (&["integer", "number"], "a numeric value")
    } else if is_currency_minor_unit_suffix(name) {
        (&["integer"], "an integer currency amount")
    } else if has("_url") {
        (
            &["string", "object"],
            "a URL string or a collection of URLs",
        )
    } else if [
        "_rfc3339",
        "_bcp47",
        "_rfc3339_date",
        "_rfc3339_time",
        "_utc_offset",
    ]
    .iter()
    .any(|s| has(s))
    {
        (&["string"], "a string")
    } else {
        return;
    };
    if let Some(at) = incompatible_schema(schema, types, pointer, true) {
        findings.push(LintFinding::new(
            "suffix_type_mismatch",
            at,
            format!("schema property {name:?} must allow {description}"),
        ));
    }
}

// Return the keyword that demonstrates a conflict. Unknown types of referenced
// or unconstrained branches cannot supply evidence of incompatibility.
fn incompatible_schema(
    schema: &Value,
    expected: &[&str],
    pointer: &str,
    allow_array: bool,
) -> Option<String> {
    let object = schema.as_object()?;
    if let Some(ty) = object.get("type") {
        let check = |name: &str| {
            if name == "array" && allow_array {
                return object.get("items").and_then(|items| {
                    incompatible_schema(
                        items,
                        expected,
                        &join_pointer(pointer, "items"),
                        expected.contains(&"object"),
                    )
                });
            }
            if expected.contains(&name) || (name == "number" && expected.contains(&"integer")) {
                None
            } else {
                Some(join_pointer(pointer, "type"))
            }
        };
        let conflict = match ty {
            Value::String(name) => check(name),
            Value::Array(types)
                if !types.is_empty()
                    && types.iter().all(|ty| ty.as_str().and_then(check).is_some()) =>
            {
                Some(join_pointer(pointer, "type"))
            }
            _ => None,
        };
        if conflict.is_some() {
            return conflict;
        }
    }
    for keyword in ["anyOf", "oneOf", "allOf"] {
        if let Some(Value::Array(branches)) = object.get(keyword) {
            let at = join_pointer(pointer, keyword);
            let mut conflicts = branches.iter().enumerate().map(|(i, branch)| {
                incompatible_schema(branch, expected, &format!("{at}/{i}"), allow_array)
            });
            if keyword == "allOf" {
                if let Some(conflict) = conflicts.find_map(|c| c) {
                    return Some(conflict);
                }
            } else if conflicts.all(|c| c.is_some()) {
                return Some(at);
            }
        }
    }
    None
}

fn is_redacted_secret_literal(value: &Value) -> bool {
    matches!(value, Value::Null) || matches!(value, Value::String(text) if text == "***")
}

fn is_numeric_suffix(key: &str) -> bool {
    let has = |suffix: &str| has_suffix_ci(key, suffix);
    has("_bytes")
        || has("_epoch_s")
        || has("_epoch_ms")
        || has("_sats")
        || has("_msats")
        || has("_percent")
        || is_duration_suffix(key)
        || is_currency_minor_unit_suffix(key)
}

fn lint_suffix_scalar_message(key: &str, value: &Value) -> Option<String> {
    // Suffix recognition uses the convention's own matching rule, not a
    // case-folded approximation: a key the renderer treats as plain must not be
    // held to a suffix's type contract, or the fix the message asks for leaves
    // the field just as untreated as before.
    let has = |suffix: &str| has_suffix_ci(key, suffix);
    if has("_bytes") {
        (!is_non_negative_integer(value))
            .then(|| format!("{key:?} must be a non-negative integer byte count"))
    } else if has("_epoch_s") || has("_epoch_ms") {
        (!is_integer(value)).then(|| format!("{key:?} must be an integer epoch timestamp"))
    } else if has("_epoch_ns") {
        (!is_decimal_integer_string(value))
            .then(|| format!("{key:?} must be a decimal integer string"))
    } else if has("_sats") || has("_msats") {
        (!(is_integer(value) || is_decimal_integer_string(value)))
            .then(|| format!("{key:?} must be an integer or decimal integer string"))
    } else if has("_percent") {
        (!value.is_number()).then(|| format!("{key:?} must be numeric"))
    } else if is_duration_suffix(key) {
        (!value.is_number()).then(|| format!("{key:?} must be a numeric duration"))
    } else if is_currency_minor_unit_suffix(key) {
        (!is_integer(value)).then(|| format!("{key:?} must be an integer currency amount"))
    } else if has("_rfc3339") {
        if value.as_str().is_some_and(is_valid_rfc3339) {
            None
        } else if value.is_string() {
            Some(format!(
                "{key:?} must be an RFC 3339 date-time with a mandatory offset (e.g. \
                 2026-02-14T10:30:00Z)"
            ))
        } else {
            Some(format!("{key:?} must be a string"))
        }
    } else if has("_bcp47") {
        if value.as_str().is_some_and(is_valid_bcp47) {
            None
        } else if value.is_string() {
            Some(format!("{key:?} must be a well-formed BCP 47 language tag"))
        } else {
            Some(format!("{key:?} must be a string"))
        }
    } else if has("_rfc3339_date") {
        if value.as_str().is_some_and(is_valid_rfc3339_date) {
            None
        } else if value.is_string() {
            Some(format!(
                "{key:?} must be an RFC 3339 full-date (YYYY-MM-DD)"
            ))
        } else {
            Some(format!("{key:?} must be a string"))
        }
    } else if has("_rfc3339_time") {
        if value.as_str().is_some_and(is_valid_rfc3339_time) {
            None
        } else if value.is_string() {
            Some(format!(
                "{key:?} must be an RFC 3339 partial-time (HH:MM:SS[.fraction], no Z or offset)"
            ))
        } else {
            Some(format!("{key:?} must be a string"))
        }
    } else if has("_utc_offset") {
        if value.as_str().and_then(normalize_utc_offset).is_some() {
            None
        } else if value.is_string() {
            Some(format!(
                "{key:?} must be a fixed UTC offset (\"UTC\" or ±HH:MM)"
            ))
        } else {
            Some(format!("{key:?} must be a string"))
        }
    } else {
        None
    }
}

fn lint_suffix_type(
    key: &str,
    value: &Value,
    pointer: &str,
    untyped_text_scalars: bool,
    findings: &mut Vec<LintFinding>,
) {
    if value.is_null() || !has_registered_suffix(key) || has_suffix_ci(key, "_secret") {
        return;
    }
    if has_suffix_ci(key, "_url") {
        // Redaction walks a URL-marked collection into its string leaves, so a
        // collection is a shape the convention supports, not a type error. Only
        // the leaves are held to the single-URL rule.
        let message = match url_field_violation(value) {
            UrlFieldCheck::Ok => None,
            UrlFieldCheck::NotAUrl => Some(format!(
                "{key:?} must be a single URL (invalid URL spelling)"
            )),
            UrlFieldCheck::NotAString => Some(format!(
                "{key:?} must be a URL string, or a collection whose leaves are URL strings"
            )),
        };
        if let Some(message) = message {
            findings.push(LintFinding::new(
                "suffix_type_mismatch",
                pointer.to_string(),
                message,
            ));
        }
        return;
    }
    if let Some(items) = value.as_array() {
        for (idx, item) in items.iter().enumerate() {
            if item.is_null() {
                continue;
            }
            let item_pointer = format!("{pointer}/{idx}");
            let message = if item.is_array() {
                Some(format!("{key:?} array elements must be scalar values"))
            } else {
                scalar_message(key, item, untyped_text_scalars)
            };
            if let Some(message) = message {
                findings.push(LintFinding::new(
                    "suffix_type_mismatch",
                    item_pointer,
                    message,
                ));
            }
        }
        return;
    }
    if let Some(message) = scalar_message(key, value, untyped_text_scalars) {
        findings.push(LintFinding::new(
            "suffix_type_mismatch",
            pointer.to_string(),
            message,
        ));
    }
}

fn scalar_message(key: &str, value: &Value, untyped: bool) -> Option<String> {
    if untyped
        && let Some(text) = value.as_str()
        && is_numeric_suffix(key)
    {
        if text.is_empty() {
            return None;
        }
        return match parse_json_number_text(text) {
            Some(number) => lint_suffix_scalar_message(key, &number),
            None => Some(format!("{key:?} must be a decimal numeric text value")),
        };
    }
    lint_suffix_scalar_message(key, value)
}

fn is_integer(value: &Value) -> bool {
    matches!(value, Value::Number(number) if number_is_integer(number))
}

fn is_non_negative_integer(value: &Value) -> bool {
    let Value::Number(number) = value else {
        return false;
    };
    if !number_is_integer(number) {
        return false;
    }
    let text = number.to_string();
    !text.starts_with('-') || decimal_number_is_zero(&text)
}

/// Whether a JSON number's exact mathematical value is an integer.
///
/// `serde_json/arbitrary_precision` preserves the source decimal, so this
/// handles integral-valued decimals and exponents without rounding through
/// f64, while also accepting integers larger than u128.
fn number_is_integer(number: &Number) -> bool {
    decimal_number_is_integer(&number.to_string())
}

fn decimal_number_is_integer(text: &str) -> bool {
    let unsigned = text.trim_prefix('-');
    let exponent_index = unsigned.find(['e', 'E']);
    let (mantissa, exponent_text) = exponent_index.map_or((unsigned, None), |index| {
        (&unsigned[..index], Some(&unsigned[index + 1..]))
    });
    if mantissa
        .bytes()
        .filter(|byte| *byte != b'.')
        .all(|byte| byte == b'0')
    {
        return true;
    }

    let fraction_digits = mantissa
        .split_once('.')
        .map_or(0, |(_, fraction)| fraction.len());
    let exponent = exponent_text.map_or(0, |value| {
        value.parse::<i128>().unwrap_or_else(|_| {
            if value.starts_with('-') {
                i128::MIN
            } else {
                i128::MAX
            }
        })
    });
    let scale = exponent.saturating_sub(i128::try_from(fraction_digits).unwrap_or(i128::MAX));
    if scale >= 0 {
        return true;
    }

    let required_trailing_zeroes = scale.unsigned_abs();
    let digit_count = mantissa.bytes().filter(|byte| *byte != b'.').count();
    if required_trailing_zeroes > digit_count as u128 {
        return false;
    }
    mantissa
        .bytes()
        .filter(|byte| *byte != b'.')
        .rev()
        .take(required_trailing_zeroes as usize)
        .all(|byte| byte == b'0')
}

fn decimal_number_is_zero(text: &str) -> bool {
    let unsigned = text.trim_prefix('-');
    let mantissa = unsigned
        .split_once(['e', 'E'])
        .map_or(unsigned, |(mantissa, _)| mantissa);
    mantissa
        .bytes()
        .filter(|byte| *byte != b'.')
        .all(|byte| byte == b'0')
}

fn is_decimal_integer_string(value: &Value) -> bool {
    let Value::String(text) = value else {
        return false;
    };
    let digits = text.trim_prefix('-');
    !digits.is_empty() && digits.chars().all(|character| character.is_ascii_digit())
}

fn is_duration_suffix(key: &str) -> bool {
    ["_ns", "_us", "_ms", "_s", "_minutes", "_hours", "_days"]
        .iter()
        .any(|suffix| has_suffix_ci(key, suffix))
}

/// Whether a key names a currency minor unit the formatter actually formats.
///
/// `_cents` and `_micro` carry a currency code (`_usd_cents`); a bare
/// `total_cents` is not a registered suffix, and holding it to the integer rule
/// would demand a fix that changes nothing about how the field is rendered.
fn is_currency_minor_unit_suffix(key: &str) -> bool {
    currency_code(key, "_cents").is_some()
        || currency_code(key, "_micro").is_some()
        || has_suffix_ci(key, "_jpy")
}

/// How a `_url`-marked value compares to the shapes redaction handles.
enum UrlFieldCheck {
    Ok,
    NotAUrl,
    NotAString,
}

/// Redaction gives URL treatment to string leaves and walks collections to
/// reach them, so the linter accepts the same shapes and checks the leaves.
fn url_field_violation(value: &Value) -> UrlFieldCheck {
    match value {
        Value::Null => UrlFieldCheck::Ok,
        Value::String(text) => {
            if crate::redaction::valid_url_field(text) {
                UrlFieldCheck::Ok
            } else {
                UrlFieldCheck::NotAUrl
            }
        }
        Value::Array(items) => first_url_violation(items.iter()),
        Value::Object(entries) => first_url_violation(
            entries
                .iter()
                .filter(|(key, _)| !has_suffix_ci(key, "_secret"))
                .map(|(_, value)| value),
        ),
        _ => UrlFieldCheck::NotAString,
    }
}

fn first_url_violation<'value>(values: impl Iterator<Item = &'value Value>) -> UrlFieldCheck {
    for value in values {
        match url_field_violation(value) {
            UrlFieldCheck::Ok => {}
            violation => return violation,
        }
    }
    UrlFieldCheck::Ok
}

#[cfg(test)]
mod tests {
    use super::{
        LintOptions, RedactionCanaryError, assert_no_lint_findings, assert_redaction_canary_absent,
        assert_strict_event, lint_value,
    };
    use crate::suffix::REGISTERED_SUFFIXES;
    use serde_json::{Value, json};

    #[test]
    fn assertions_return_only_contract_violations() {
        let options = LintOptions::default();
        let legal = json!({"build": "8165", "rows": "1,200", "timeout": 5});
        assert_no_lint_findings(&legal).unwrap();
        for (key, value) in legal.as_object().unwrap() {
            assert!(super::lint_field_value(key, value, options).is_empty());
        }

        let mixed = json!({"rows": "1,200", "x~/size_bytes": [0, "8 MB"], "when_rfc3339": "today"});
        let violations = assert_no_lint_findings(&mixed).unwrap_err();
        assert_eq!(violations, lint_value(&mixed, options));
        assert_eq!(violations.len(), 2);
        for (pointer, finding) in ["/when_rfc3339", "/x~0~1size_bytes/1"]
            .into_iter()
            .zip(&violations)
        {
            assert_eq!(finding.pointer, pointer);
            assert_eq!(finding.rule_id, "suffix_type_mismatch");
            assert_eq!(
                serde_json::to_value(finding).unwrap(),
                json!({
                    "rule_id": finding.rule_id, "pointer": pointer, "message": finding.message,
                })
            );
        }
        for (value, pointer) in [(json!("8 MB"), ""), (json!([12, "8 MB"]), "/1")] {
            let findings = super::lint_field_value("total_bytes", &value, options);
            assert_eq!(findings.len(), 1);
            assert_eq!(findings[0].pointer, pointer);
        }
    }

    #[test]
    fn only_integer_literals_outside_the_portable_range_fail() {
        let values = serde_json::from_str(
            r#"[-9007199254740991,9007199254740991,-9007199254740992,9007199254740992,9007199254740992.0,1e19,"9007199254740992"]"#,
        ).unwrap();
        let findings = assert_no_lint_findings(&values).unwrap_err();
        assert_eq!(
            findings
                .iter()
                .map(|f| (f.rule_id.as_str(), f.pointer.as_str()))
                .collect::<Vec<_>>(),
            [("unsafe_integer", "/2"), ("unsafe_integer", "/3")]
        );
    }

    #[test]
    fn schema_declarations_and_instances_have_distinct_roles() {
        let schema = LintOptions::new().schema_properties();
        let literal = json!({"properties":{"option_secret":{"default":"canary"}}});
        assert_no_lint_findings(&literal).unwrap();
        let findings = lint_value(&literal, schema);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].pointer, "/properties/option_secret/default");
        assert!(!findings[0].message.contains("canary"));

        let declarations = json!({"properties":{
            "size_bytes":{"type":"number"}, "size_bYtEs":{"type":"string"},
            "value_Secret":{"example":42}, "LINKS_URL":{"type":["object","array"],"items":{"type":"string"}},
        }});
        assert!(lint_value(&declarations, schema).is_empty());
        assert!(assert_no_lint_findings(&declarations).is_err());
        let nested = json!({"$defs":{"properties":{"properties":{
            "sample":{"default":literal, "example":{"properties":{"size_bytes":{"type":"integer"}}}},
            "bad_ms":{"allOf":[{"type":"array","items":{"type":"string"}}]},
        }}}});
        let errors = lint_value(&nested, schema);
        let pointers: Vec<_> = errors.iter().map(|f| f.pointer.as_str()).collect();
        assert_eq!(
            pointers,
            [
                "/$defs/properties/properties/bad_ms/allOf/0/items/type",
                "/$defs/properties/properties/sample/example/properties/size_bytes"
            ]
        );
    }

    #[test]
    fn schema_const_and_enum_protect_secrets() {
        let options = LintOptions::new().schema_properties();
        let schema = json!({"properties": {
            "api_key_secret": {"type": "string", "const": "sample", "enum": [null, "***", "sample"]}
        }});
        let findings = lint_value(&schema, options);
        assert_eq!(
            findings
                .iter()
                .map(|item| item.pointer.as_str())
                .collect::<Vec<_>>(),
            [
                "/properties/api_key_secret/const",
                "/properties/api_key_secret/enum/2"
            ]
        );
        assert!(
            findings
                .iter()
                .all(|item| item.rule_id == "secret_schema_value_exposed")
        );
        let redacted = json!({"properties": {
            "api_key_secret": {"type": "string", "const": "***", "enum": [null, "***"]}
        }});
        assert!(lint_value(&redacted, options).is_empty());
    }

    #[test]
    fn untyped_input_applies_to_data_inside_schema_documents() {
        let options = LintOptions::new()
            .schema_properties()
            .untyped_text_scalars(true);
        let value = json!({"properties": {
            "bad_ms": {"type":"string"},
            "retry_ms": ["5000", "", null, "5s"],
            "size_bytes": {"example":"1024"},
            "sample": {"example":{"properties":{"size_bytes":"1024"}}},
        }});
        let errors = lint_value(&value, options);
        assert_eq!(
            errors
                .iter()
                .map(|f| f.pointer.as_str())
                .collect::<Vec<_>>(),
            ["/properties/bad_ms/type", "/properties/retry_ms/3"]
        );
    }

    #[test]
    fn url_shape_matches_redaction_at_collection_leaves() {
        let good =
            json!({"links_url":[{"token_secret":42, "next":"/cb"}, " https://example.org/ "]});
        assert_no_lint_findings(&good).unwrap();
        for bad in [
            "prefix=https://host/",
            "user@host",
            "two paths",
            "https://a\u{000b}b",
        ] {
            assert!(assert_no_lint_findings(&json!({"links_url":[bad]})).is_err());
        }
    }

    #[test]
    fn integer_suffixes_accept_integral_decimals_and_signed_currency() {
        let value: Value = serde_json::from_str(
            r#"{
                "price_usd_cents": -1,
                "refund_eur_cents": -3.0,
                "size_bytes": 3.0,
                "created_epoch_ms": 3e0
            }"#,
        )
        .unwrap_or_else(|error| panic!("{error}"));

        assert!(lint_value(&value, LintOptions::default()).is_empty());
    }

    #[test]
    fn registered_currency_suffixes_accept_three_or_four_letter_codes() {
        assert!(super::has_registered_suffix("fare_thb_cents"));
        assert!(super::has_registered_suffix("deposit_usdt_cents"));
        assert!(!super::has_registered_suffix("total_amount_cents"));
        assert!(!super::has_registered_suffix("price_usdtx_cents"));
    }

    #[test]
    fn integer_suffixes_reject_fractional_values_and_negative_bytes() {
        let value: Value = serde_json::from_str(
            r#"{
                "price_usd_cents": 3.5,
                "size_bytes": -1
            }"#,
        )
        .unwrap_or_else(|error| panic!("{error}"));
        let findings = lint_value(&value, LintOptions::default());

        assert_eq!(
            findings
                .iter()
                .filter(|finding| finding.rule_id == "suffix_type_mismatch")
                .count(),
            2
        );
    }

    #[test]
    fn unsafe_integer_finds_values_beyond_u128() {
        let value: Value =
            serde_json::from_str(r#"{"huge_count":340282366920938463463374607431768211456}"#)
                .unwrap_or_else(|error| panic!("{error}"));
        let findings = lint_value(&value, LintOptions::default());

        assert!(
            findings
                .iter()
                .any(|finding| finding.rule_id == "unsafe_integer"),
            "{findings:?}"
        );
    }

    #[test]
    fn assertion_helpers_cover_protocol_lint_and_redaction() {
        let event = json!({
            "kind": "result",
            "result": {"code": "ready"},
            "trace": {}
        });
        assert!(assert_strict_event(&event).is_ok());
        assert!(assert_no_lint_findings(&event).is_ok());
        assert!(assert_redaction_canary_absent("{\"secret\":\"***\"}", "canary-42").is_ok());
        assert_eq!(
            assert_redaction_canary_absent("contains canary-42", "canary-42"),
            Err(RedactionCanaryError::Exposed)
        );
    }

    /// A canary is only useful if escaping cannot hide it. Every case here is a
    /// canary sitting verbatim in the output while a raw substring search
    /// misses it, which is how a leak used to pass this assertion.
    #[test]
    fn redaction_canary_survives_every_output_escape() {
        for (label, canary) in [
            (
                "pem newlines",
                "-----BEGIN KEY-----\nabc\n-----END KEY-----",
            ),
            ("double quote", "p@ss\"word"),
            ("backslash path", "C:\\Users\\me\\key"),
            ("tab", "a\tb"),
            ("non-bmp", "k\u{1f511}ey"),
        ] {
            let rendered = crate::render(
                &json!({ "note": canary }),
                crate::OutputFormat::Json,
                &crate::OutputOptions::default(),
            );
            assert!(
                rendered.contains("note"),
                "{label}: expected the field to survive rendering"
            );
            assert_eq!(
                assert_redaction_canary_absent(&rendered, canary),
                Err(RedactionCanaryError::Exposed),
                "{label}: escaped canary must still be reported, output was {rendered}"
            );
        }
    }

    /// The percent-encoded spelling counts too: a canary can reach the stream
    /// through a URL without ever appearing literally.
    #[test]
    fn redaction_canary_is_found_percent_encoded() {
        assert_eq!(
            assert_redaction_canary_absent("{\"note\":\"https://h/p?q=a%20b%20c\"}", "a b c"),
            Err(RedactionCanaryError::Exposed)
        );
    }

    #[test]
    fn redaction_canary_is_found_through_nested_and_mixed_encoding() {
        for serialized in [
            r#"{"note":"https://h/?next=https%3A%2F%2Fb%2F%3Fq%3D%2573ecret"}"#,
            r#"{"note":"\u002573ecret"}"#,
            r#"{"note":"%5Cu0073ecret"}"#,
            r#"{"note":"%255CuD83D%255CuDD11"}"#,
        ] {
            let canary = if serialized.contains("D83D") {
                "🔑"
            } else {
                "secret"
            };
            assert_eq!(
                assert_redaction_canary_absent(serialized, canary),
                Err(RedactionCanaryError::Exposed),
                "encoded output must still report the canary: {serialized}"
            );
        }
        assert_eq!(
            assert_redaction_canary_absent("%25not-a-canary", "secret"),
            Ok(())
        );
    }

    #[test]
    fn redaction_canary_inspection_fails_closed_on_excessive_encoding_depth() {
        let ordinary = format!("%{}73afe", "25".repeat(15));
        assert_eq!(assert_redaction_canary_absent(&ordinary, "secret"), Ok(()));
        // No canary is present, but inspection may not silently pass an output
        // whose encoding cannot settle inside its fixed work budget.
        let deep = format!("%{}73afe{}", "25".repeat(1000), "x".repeat(4096));
        assert_eq!(
            assert_redaction_canary_absent(&deep, "secret"),
            Err(RedactionCanaryError::InspectionLimitExceeded)
        );
    }

    /// The widened search must not cry wolf: a genuinely redacted secret
    /// reports clean in every format, whatever characters it contained.
    #[test]
    fn redaction_canary_stays_quiet_when_the_value_was_redacted() {
        for canary in [
            "-----BEGIN KEY-----\nabc\n-----END KEY-----",
            "p@ss\"word",
            "C:\\Users\\me\\key",
            "k\u{1f511}ey",
        ] {
            for format in [
                crate::OutputFormat::Json,
                crate::OutputFormat::Yaml,
                crate::OutputFormat::Plain,
            ] {
                let rendered = crate::render(
                    &json!({ "note_secret": canary }),
                    format,
                    &crate::OutputOptions::default(),
                );
                assert_eq!(
                    assert_redaction_canary_absent(&rendered, canary),
                    Ok(()),
                    "redacted output must not report a leak, output was {rendered}"
                );
            }
        }
    }

    #[test]
    fn registry_suffixes_match_the_lint_table() {
        const REGISTRY: &str =
            include_str!("../../skills/agent-first-data/references/registry.json");
        let registry: Value =
            serde_json::from_str(REGISTRY).unwrap_or_else(|error| panic!("{error}"));
        let suffixes = registry["suffixes"]
            .as_array()
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        let mut from_registry: Vec<(String, String)> = suffixes
            .iter()
            .filter_map(|entry| {
                Some((
                    entry["category"].as_str()?.to_string(),
                    entry["suffix"].as_str()?.to_string(),
                ))
            })
            .collect();
        let mut from_table: Vec<(String, String)> = REGISTERED_SUFFIXES
            .iter()
            .flat_map(|(category, suffixes)| {
                suffixes
                    .iter()
                    .map(move |suffix| ((*category).to_string(), (*suffix).to_string()))
            })
            .collect();
        from_registry.sort();
        from_table.sort();
        assert_eq!(from_table, from_registry);
    }
}