agent-first-data 0.37.0

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
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
1081
1082
1083
1084
use crate::output::OutputFormat;
use crate::redaction::{OutputOptions, PlainStyle, REDACTED_MARKER};
use serde_json::Value;

/// Render a value as a string in the given format with the given options.
///
/// The single `value × format × options → String` entry point. JSON and YAML
/// are structure-preserving and ignore [`PlainStyle`]; plain honors it. All
/// three redact through `options.redaction` before rendering.
pub fn render(value: &Value, format: OutputFormat, options: &OutputOptions) -> String {
    match format {
        OutputFormat::Json => serialize_json_output(&options.redaction.value(value)),
        OutputFormat::Yaml => render_yaml(value, options),
        OutputFormat::Plain => render_plain(value, options),
    }
}

pub(crate) fn serialize_json_output(value: &Value) -> String {
    match serde_json::to_string(value) {
        Ok(s) => s,
        Err(err) => serde_json::json!({
            "error": "output_json_failed",
            "detail": err.to_string(),
        })
        .to_string(),
    }
}

/// Format as multi-line YAML with the given output options.
///
/// YAML output ignores [`PlainStyle`] and always preserves original keys and values after
/// redaction, the same structure-preserving semantics as JSON.
pub(crate) fn render_yaml(value: &Value, output_options: &OutputOptions) -> String {
    let mut lines = vec!["---".to_string()];
    let v = output_options.redaction.value(value);
    render_yaml_raw(&v, 0, &mut lines);
    lines.join("\n")
}

/// Format as single-line logfmt with the given output options.
pub(crate) fn render_plain(value: &Value, output_options: &OutputOptions) -> String {
    let mut pairs: Vec<(String, String)> = Vec::new();
    let v = output_options.redaction.value(value);
    if !v.is_object() {
        return plain_scalar(&v);
    }
    match output_options.style {
        PlainStyle::Readable => collect_plain_pairs(&v, "", &mut pairs),
        PlainStyle::Raw => collect_plain_pairs_raw(&v, "", &mut pairs),
    }
    if pairs.is_empty() {
        return "{}".to_string();
    }
    pairs.sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16()));
    pairs
        .into_iter()
        .map(|(k, v)| format!("{}={}", quote_logfmt_key(&k), quote_logfmt_value(&v)))
        .collect::<Vec<_>>()
        .join(" ")
}

// ═══════════════════════════════════════════
// Suffix Processing
// ═══════════════════════════════════════════

/// Whether a key carries `suffix_lower` under the AFDATA matching rule.
///
/// Shared with the linter on purpose: a linter that recognizes a suffix the
/// renderer does not will certify a field as handled that nothing handles.
pub(crate) fn has_suffix_ci(key: &str, suffix_lower: &str) -> bool {
    strip_suffix_ci(key, suffix_lower).is_some()
}

/// Strip a suffix matching exact lowercase or exact uppercase only.
pub(crate) fn strip_suffix_ci(key: &str, suffix_lower: &str) -> Option<String> {
    if let Some(s) = key.strip_suffix(suffix_lower) {
        return Some(s.to_string());
    }
    let suffix_upper: String = suffix_lower
        .chars()
        .map(|c| c.to_ascii_uppercase())
        .collect();
    if let Some(s) = key.strip_suffix(&suffix_upper) {
        return Some(s.to_string());
    }
    None
}

/// Extract currency code from `_{code}_cents` / `_{CODE}_CENTS` pattern.
fn try_strip_generic_cents(key: &str) -> Option<(String, String)> {
    let code = extract_currency_code(key)?;
    let suffix_len = code.len() + "_cents".len() + 1; // _{code}_cents
    let stripped = &key[..key.len() - suffix_len];
    if stripped.is_empty() {
        return None;
    }
    Some((stripped.to_string(), code.to_string()))
}

/// Extract currency code from `_{code}_micro` / `_{CODE}_MICRO` pattern.
fn try_strip_generic_micro(key: &str) -> Option<(String, String)> {
    let code = extract_currency_code_micro(key)?;
    let suffix_len = code.len() + "_micro".len() + 1; // _{code}_micro
    let stripped = &key[..key.len() - suffix_len];
    if stripped.is_empty() {
        return None;
    }
    Some((stripped.to_string(), code.to_string()))
}

/// Accept an integer value, including an integral-valued float (`3.0` → `3`).
/// Non-integral floats and out-of-range values return `None`. This keeps the
/// four language implementations consistent: JS/TS cannot distinguish `3` from
/// `3.0` after JSON parsing, so the value's integrality — not its lexical form —
/// decides whether an integer-required suffix applies.
fn as_int(value: &Value) -> Option<i64> {
    if let Some(i) = value.as_i64() {
        return Some(i);
    }
    if value.is_u64() {
        return value.as_u64()?.try_into().ok();
    }
    // An integer literal that neither `as_i64` nor `as_u64` accepted is out of
    // i64 range. Converting `i64::MIN - 1` through f64 would round it back into
    // range, formatting a plausible but wrong amount on a money field. The
    // positive side is already refused by the `is_u64` check above. Floating
    // literals below are also checked on their exact decimal digits.
    if let Value::Number(number) = value
        && number_is_integer_literal(number)
    {
        return None;
    }
    let Value::Number(number) = value else {
        return None;
    };
    integral_float_text(&number.to_string())?.parse().ok()
}

/// Whether the producer wrote this number as an integer literal.
///
/// Shared with the linter: both need to tell "the author wrote an integer" from
/// "the value happens to be integral", and they must not answer it differently.
pub(crate) fn number_is_integer_literal(number: &serde_json::Number) -> bool {
    !number.to_string().contains(['.', 'e', 'E'])
}

/// Like [`as_int`] but for non-negative integers (rejects negatives).
fn as_uint(value: &Value) -> Option<u64> {
    if let Some(u) = value.as_u64() {
        return Some(u);
    }
    if value.as_i64() == Some(0) {
        return Some(0);
    }
    if let Value::Number(number) = value
        && number_is_integer_literal(number)
    {
        return None;
    }
    let Value::Number(number) = value else {
        return None;
    };
    let integer = integral_float_text(&number.to_string())?;
    if integer == "-0" {
        return Some(0);
    }
    integer.parse().ok()
}

/// The exact digits of an integer-valued number or decimal integer string, of
/// any magnitude. Bitcoin amounts and `_epoch_ns` only append a unit or
/// divide, so unlike money suffixes they are not bounded by `i64`: an integer
/// literal keeps its digits, and a float literal counts when its value is an
/// integer below 1e21 (the canonical number form's integer range). A numeric
/// `-0` is zero.
fn integer_text(value: &Value) -> Option<String> {
    match value {
        Value::Number(number) => {
            let literal = number.to_string();
            let integer = if number_is_integer_literal(number) {
                literal
            } else {
                integral_float_text(&literal)?
            };
            Some(if integer == "-0" { "0".into() } else { integer })
        }
        Value::String(s) if is_decimal_integer_string(s) => Some(s.clone()),
        _ => None,
    }
}

fn is_decimal_integer_string(s: &str) -> bool {
    let digits = s.strip_prefix('-').unwrap_or(s);
    !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
}

/// Floor-divide an integer nanosecond count of any size to milliseconds.
/// `i128` spans ±1.7e38 ns, far beyond the RFC 3339 year range, so a count it
/// cannot hold is out of range for the same reason a smaller one can be.
fn epoch_ns_to_ms(value: &Value) -> Option<i64> {
    let ns = integer_text(value)?.parse::<i128>().ok()?;
    ns.div_euclid(1_000_000).try_into().ok()
}

/// Try suffix-driven processing. Returns `Some((stripped_key, formatted_value))`
/// when the suffix matches and the type is valid; `None` for no match or a type
/// mismatch.
fn try_process_field(key: &str, value: &Value) -> Option<(String, String)> {
    // Group 1: compound timestamp suffixes
    if let Some(stripped) = strip_suffix_ci(key, "_epoch_ms") {
        return as_int(value)
            .and_then(|ms| format_rfc3339_ms(ms).map(|formatted| (stripped, formatted)));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_epoch_s") {
        return as_int(value)
            .and_then(|s| s.checked_mul(1000))
            .and_then(|ms| format_rfc3339_ms(ms).map(|formatted| (stripped, formatted)));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_epoch_ns") {
        return epoch_ns_to_ms(value)
            .and_then(|ms| format_rfc3339_ms(ms).map(|formatted| (stripped, formatted)));
    }

    // Group 2: compound currency suffixes
    if let Some(stripped) = strip_suffix_ci(key, "_usd_cents") {
        return as_int(value).map(|n| {
            let (sign, magnitude) = signed_magnitude(n);
            (
                stripped,
                format!("{sign}${}.{:02}", magnitude / 100, magnitude % 100),
            )
        });
    }
    if let Some(stripped) = strip_suffix_ci(key, "_eur_cents") {
        return as_int(value).map(|n| {
            let (sign, magnitude) = signed_magnitude(n);
            (
                stripped,
                format!("{sign}€{}.{:02}", magnitude / 100, magnitude % 100),
            )
        });
    }
    if let Some((stripped, code)) = try_strip_generic_cents(key) {
        return as_int(value).map(|n| {
            let (sign, magnitude) = signed_magnitude(n);
            (
                stripped,
                format!(
                    "{sign}{}.{:02} {}",
                    magnitude / 100,
                    magnitude % 100,
                    code.to_uppercase()
                ),
            )
        });
    }
    if let Some((stripped, code)) = try_strip_generic_micro(key) {
        return as_int(value).map(|n| {
            let (sign, magnitude) = signed_magnitude(n);
            (
                stripped,
                format!(
                    "{sign}{}.{:06} {}",
                    magnitude / 1_000_000,
                    magnitude % 1_000_000,
                    code.to_uppercase()
                ),
            )
        });
    }

    // Group 3: multi-char suffixes
    if let Some(stripped) = strip_suffix_ci(key, "_rfc3339") {
        return value.as_str().map(|s| (stripped, s.to_string()));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_minutes") {
        return value
            .is_number()
            .then(|| (stripped, format!("{} minutes", number_str(value))));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_hours") {
        return value
            .is_number()
            .then(|| (stripped, format!("{} hours", number_str(value))));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_days") {
        return value
            .is_number()
            .then(|| (stripped, format!("{} days", number_str(value))));
    }

    // Group 4: single-unit suffixes
    if let Some(stripped) = strip_suffix_ci(key, "_msats") {
        return integer_text(value).map(|n| (stripped, format!("{n}msats")));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_sats") {
        return integer_text(value).map(|n| (stripped, format!("{n}sats")));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_bytes") {
        return as_uint(value).map(|n| (stripped, format_bytes_human(n)));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_percent") {
        return value
            .is_number()
            .then(|| (stripped, format!("{}%", number_str(value))));
    }
    // Group 5: short suffixes (last to avoid false positives)
    if let Some(stripped) = strip_suffix_ci(key, "_jpy") {
        return as_int(value).map(|n| {
            let (sign, magnitude) = signed_magnitude(n);
            (
                stripped,
                format!("{sign}¥{}", format_with_commas(magnitude)),
            )
        });
    }
    if let Some(stripped) = strip_suffix_ci(key, "_ns") {
        return value
            .is_number()
            .then(|| (stripped, format!("{}ns", number_str(value))));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_us") {
        return value
            .is_number()
            .then(|| (stripped, format!("{}μs", number_str(value))));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_ms") {
        return format_ms_value(value).map(|v| (stripped, v));
    }
    if let Some(stripped) = strip_suffix_ci(key, "_s") {
        return value
            .is_number()
            .then(|| (stripped, format!("{}s", number_str(value))));
    }

    None
}

/// True when a field already carries the redaction marker, i.e. redaction ran
/// over it and hid the value.
fn is_redacted(value: &Value) -> bool {
    value.as_str() == Some(REDACTED_MARKER)
}

/// Process object fields: strip keys, format values, detect collisions.
fn process_object_fields<'a>(
    map: &'a serde_json::Map<String, Value>,
) -> Vec<(String, &'a Value, Option<String>)> {
    let mut entries: Vec<(String, &'a str, &'a Value, Option<String>)> = Vec::new();
    for (key, value) in map {
        if let Some(stripped) = strip_suffix_ci(key, "_secret") {
            // Dropping `_secret` is the readable half of an actual redaction: the
            // marker has done its job once the value reads `***`. When the value
            // was *not* redacted — policy `Off`, or a field outside `trace` under
            // `TraceOnly` — the suffix is the only thing telling a downstream
            // reader that `api_key_secret=sk-live-xxx` is a credential, so it
            // stays.
            let display_key = if is_redacted(value) {
                stripped
            } else {
                key.clone()
            };
            entries.push((display_key, key.as_str(), value, None));
            continue;
        }
        match try_process_field(key, value) {
            Some((stripped, formatted)) => {
                entries.push((stripped, key.as_str(), value, Some(formatted)));
            }
            None => {
                entries.push((key.clone(), key.as_str(), value, None));
            }
        }
    }

    // Detect collisions
    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for (stripped, _, _, _) in &entries {
        *counts.entry(stripped.clone()).or_insert(0) += 1;
    }

    // Resolve collisions: revert both key and formatted value
    let mut result: Vec<(String, &'a Value, Option<String>)> = entries
        .into_iter()
        .map(|(stripped, original, value, formatted)| {
            if counts.get(&stripped).copied().unwrap_or(0) > 1 && original != stripped.as_str() {
                (original.to_string(), value, None)
            } else {
                (stripped, value, formatted)
            }
        })
        .collect();

    result.sort_by(|(a, _, _), (b, _, _)| a.encode_utf16().cmp(b.encode_utf16()));
    result
}

// ═══════════════════════════════════════════
// Formatting Helpers
// ═══════════════════════════════════════════

fn number_str(value: &Value) -> String {
    match value {
        Value::Number(n) => format_number(n),
        _ => String::new(),
    }
}

/// Render a JSON number canonically for YAML/plain output: a float literal
/// whose value is an integer below 1e21 in magnitude renders as that integer
/// (`3.0` → `3`, `-0.0` → `-0`, `1.5e2` → `150`); everything else keeps its
/// digits, placed by [`place_decimal_point`]. Go, Python and TypeScript apply
/// the same rule to native floats and to decoded literals alike, so the four
/// implementations stay byte-identical.
///
/// Decided on the literal's text rather than through `f64`, which would round
/// `9007199254740993.0` to `…992`: rendering may change a number's spelling,
/// never its digits.
fn format_number(n: &serde_json::Number) -> String {
    let literal = n.to_string();
    integral_float_text(&literal)
        .or_else(|| place_decimal_point(&literal))
        .unwrap_or_else(|| normalize_exponent(&literal))
}

/// Spell a non-integral float literal with the notation ECMAScript's
/// `Number#toString` picks: positional when the value lies in [1e-6, 1e21),
/// exponent form otherwise. Each runtime's native formatter switches at a
/// different magnitude (ryu below 1e-5, Python and Go below 1e-4, Go also from
/// 1e6), so the choice is made here, on the digits as written. `None` for
/// integer literals and exponents beyond `i64`, which keep their spelling.
fn place_decimal_point(literal: &str) -> Option<String> {
    if !literal.contains(['.', 'e', 'E']) {
        return None;
    }
    let (sign, unsigned) = match literal.strip_prefix('-') {
        Some(rest) => ("-", rest),
        None => ("", literal),
    };
    let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
        Some(index) => (&unsigned[..index], &unsigned[index + 1..]),
        None => (unsigned, "0"),
    };
    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
    let digits = format!("{whole}{fraction}");
    let leading = digits.bytes().take_while(|digit| *digit == b'0').count();
    let significant = &digits[leading..];
    if significant.is_empty() {
        return None;
    }
    // `point`: how many significant digits precede the decimal point.
    let point = i64::try_from(whole.len())
        .ok()?
        .checked_sub(i64::try_from(leading).ok()?)?
        .checked_add(exponent.parse::<i64>().ok()?)?;
    let text = if (1..=21).contains(&point) {
        let split = usize::try_from(point).ok()?.min(significant.len());
        let (integer, rest) = significant.split_at(split);
        if rest.is_empty() {
            // An integral value at or beyond the point is integral_float_text's.
            return None;
        }
        format!("{integer}.{rest}")
    } else if (-5..=0).contains(&point) {
        let zeros = "0".repeat(usize::try_from(-point).ok()?);
        format!("0.{zeros}{significant}")
    } else {
        let (first, rest) = significant.split_at(1);
        let scale = point.checked_sub(1)?;
        let marker = if scale < 0 { "-" } else { "+" };
        let rest = if rest.is_empty() {
            String::new()
        } else {
            format!(".{rest}")
        };
        format!("{first}{rest}e{marker}{}", scale.unsigned_abs())
    };
    Some(format!("{sign}{text}"))
}

/// The exact integer a float literal denotes, when it denotes one below 1e21
/// in magnitude. `None` for integer literals (already canonical), fractional
/// values, and anything at or beyond 1e21, which keeps exponent form.
fn integral_float_text(literal: &str) -> Option<String> {
    if !literal.contains(['.', 'e', 'E']) {
        return None;
    }
    let (negative, unsigned) = match literal.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, literal),
    };
    let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
        Some(index) => (&unsigned[..index], &unsigned[index + 1..]),
        None => (unsigned, "0"),
    };
    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
    let digits = format!("{whole}{fraction}");
    if digits.bytes().all(|digit| digit == b'0') {
        return Some(if negative { "-0" } else { "0" }.into());
    }
    let exponent = exponent.parse::<i64>().ok()?;
    // Where the decimal point falls in `digits` once the exponent is applied.
    let point = i64::try_from(whole.len()).ok()?.checked_add(exponent)?;
    let split = usize::try_from(point.clamp(0, i64::try_from(digits.len()).ok()?)).ok()?;
    if digits[split..].bytes().any(|digit| digit != b'0') {
        return None;
    }
    let padding = usize::try_from(point)
        .unwrap_or(0)
        .saturating_sub(digits.len());
    let integer = format!("{}{}", &digits[..split], "0".repeat(padding.min(22)));
    let integer = integer.trim_start_matches('0');
    if integer.len() > 21 {
        return None;
    }
    let integer = if integer.is_empty() { "0" } else { integer };
    Some(if negative {
        format!("-{integer}")
    } else {
        integer.to_string()
    })
}

fn normalize_exponent(s: &str) -> String {
    let Some(e) = s.find(['e', 'E']) else {
        return s.to_string();
    };
    let mantissa = &s[..e];
    let mut exp = &s[e + 1..];
    // An unsigned exponent is a positive one: spell it `e+` like every
    // native float formatter, so a decoded literal renders the same.
    let mut sign = "+";
    if exp.starts_with(['+', '-']) {
        sign = &exp[..1];
        exp = &exp[1..];
    }
    let exp = exp.trim_start_matches('0');
    let exp = if exp.is_empty() { "0" } else { exp };
    format!("{mantissa}e{sign}{exp}")
}

/// Format ms as seconds: 3 decimal places, trim trailing zeros, min 1 decimal.
fn format_ms_as_seconds(ms: f64) -> String {
    let formatted = format!("{:.3}", ms / 1000.0);
    let trimmed = formatted.trim_end_matches('0');
    if trimmed.ends_with('.') {
        format!("{}0s", trimmed)
    } else {
        format!("{}s", trimmed)
    }
}

/// Split a signed integer into its sign text and magnitude.
///
/// Taking the magnitude before dividing keeps currency formatting identical
/// across the four languages: Rust and Go truncate toward zero while Python
/// floors toward negative infinity, so `-499 / 100` does not agree, but
/// `-(499 / 100)` does.
fn signed_magnitude(value: i64) -> (&'static str, u64) {
    if value < 0 {
        ("-", value.unsigned_abs())
    } else {
        ("", value as u64)
    }
}

/// Format `_ms` value: < 1000 → `{n}ms`, >= 1000 → seconds.
fn format_ms_value(value: &Value) -> Option<String> {
    // A decoded literal beyond f64 parses as infinity; it cannot be converted
    // to seconds, so it keeps its raw key and digits as in the other SDKs.
    let n = value.as_f64().filter(|n| n.is_finite())?;
    if n.abs() >= 1000.0 {
        Some(format_ms_as_seconds(n))
    } else {
        Some(format!("{}ms", number_str(value)))
    }
}

/// Convert unix milliseconds (signed) to RFC 3339 with UTC timezone.
const MIN_RFC3339_MS: i64 = -62135596800000;
const MAX_RFC3339_MS: i64 = 253402300799999;

fn format_rfc3339_ms(ms: i64) -> Option<String> {
    use chrono::{DateTime, Utc};
    if !(MIN_RFC3339_MS..=MAX_RFC3339_MS).contains(&ms) {
        return None;
    }
    let secs = ms.div_euclid(1000);
    let nanos = (ms.rem_euclid(1000) * 1_000_000) as u32;
    DateTime::from_timestamp(secs, nanos).map(|dt| {
        dt.with_timezone(&Utc)
            .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
    })
}

/// Format non-negative bytes as human-readable binary size.
pub(crate) fn format_bytes_human(bytes: u64) -> String {
    const KIB: f64 = 1024.0;
    const MIB: f64 = KIB * 1024.0;
    const GIB: f64 = MIB * 1024.0;
    const TIB: f64 = GIB * 1024.0;

    let b = bytes as f64;
    if b >= TIB {
        format!("{:.1}TiB", b / TIB)
    } else if b >= GIB {
        format!("{:.1}GiB", b / GIB)
    } else if b >= MIB {
        format!("{:.1}MiB", b / MIB)
    } else if b >= KIB {
        format!("{:.1}KiB", b / KIB)
    } else {
        format!("{bytes}B")
    }
}

/// Format a number with thousands separators.
pub(crate) fn format_with_commas(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, c) in s.chars().enumerate() {
        if i > 0 && (s.len() - i).is_multiple_of(3) {
            result.push(',');
        }
        result.push(c);
    }
    result
}

/// Extract currency code from a `_{code}_cents` / `_{CODE}_CENTS` suffix.
pub(crate) fn extract_currency_code(key: &str) -> Option<&str> {
    let without_cents = key
        .strip_suffix("_cents")
        .or_else(|| key.strip_suffix("_CENTS"))?;
    extract_currency_code_from_stem(without_cents)
}

/// Extract currency code from a `_{code}_micro` / `_{CODE}_MICRO` suffix.
pub(crate) fn extract_currency_code_micro(key: &str) -> Option<&str> {
    let without_micro = key
        .strip_suffix("_micro")
        .or_else(|| key.strip_suffix("_MICRO"))?;
    extract_currency_code_from_stem(without_micro)
}

fn extract_currency_code_from_stem(stem: &str) -> Option<&str> {
    let last_underscore = stem.rfind('_')?;
    let code = &stem[last_underscore + 1..];
    if code.is_empty()
        || !(3..=4).contains(&code.len())
        || !code.bytes().all(|b| b.is_ascii_alphabetic())
    {
        return None;
    }
    Some(code)
}

// ═══════════════════════════════════════════
// YAML Rendering (structure-preserving)
// ═══════════════════════════════════════════

fn render_yaml_raw(value: &Value, indent: usize, lines: &mut Vec<String>) {
    let prefix = "  ".repeat(indent);
    match value {
        Value::Object(map) => {
            for key in sorted_value_keys(map) {
                render_yaml_field_raw(&prefix, &key, &map[&key], indent, lines);
            }
        }
        Value::Array(arr) => {
            render_yaml_array_raw(arr, indent, lines);
        }
        _ => {
            lines.push(format!("{}{}", prefix, yaml_scalar(value)));
        }
    }
}

fn render_yaml_field_raw(
    prefix: &str,
    key: &str,
    value: &Value,
    indent: usize,
    lines: &mut Vec<String>,
) {
    match value {
        Value::Object(inner) if !inner.is_empty() => {
            lines.push(format!("{}{}:", prefix, yaml_key(key)));
            render_yaml_raw(value, indent + 1, lines);
        }
        Value::Object(_) => {
            lines.push(format!("{}{}: {{}}", prefix, yaml_key(key)));
        }
        Value::Array(arr) => {
            if arr.is_empty() {
                lines.push(format!("{}{}: []", prefix, yaml_key(key)));
            } else {
                lines.push(format!("{}{}:", prefix, yaml_key(key)));
                render_yaml_array_raw(arr, indent + 1, lines);
            }
        }
        _ => {
            lines.push(format!(
                "{}{}: {}",
                prefix,
                yaml_key(key),
                yaml_scalar(value)
            ));
        }
    }
}

fn render_yaml_array_raw(arr: &[Value], indent: usize, lines: &mut Vec<String>) {
    let prefix = "  ".repeat(indent);
    for item in arr {
        match item {
            Value::Object(inner) if !inner.is_empty() => {
                lines.push(format!("{}-", prefix));
                render_yaml_raw(item, indent + 1, lines);
            }
            Value::Array(nested) if !nested.is_empty() => {
                lines.push(format!("{}-", prefix));
                render_yaml_array_raw(nested, indent + 1, lines);
            }
            Value::Object(_) => {
                lines.push(format!("{}- {{}}", prefix));
            }
            Value::Array(_) => {
                lines.push(format!("{}- []", prefix));
            }
            _ => {
                lines.push(format!("{}- {}", prefix, yaml_scalar(item)));
            }
        }
    }
}

fn escape_yaml_str(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len());
    for character in s.chars() {
        match character {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            '\x08' => escaped.push_str("\\b"),
            '\x0c' => escaped.push_str("\\f"),
            '\x0b' => escaped.push_str("\\v"),
            '\0' => escaped.push_str("\\0"),
            control if control <= '\u{001f}' => {
                use std::fmt::Write as _;
                let _ = write!(escaped, "\\u{:04x}", control as u32);
            }
            other => escaped.push(other),
        }
    }
    escaped
}

fn yaml_key(key: &str) -> String {
    if is_safe_key(key) && !is_ambiguous_yaml_key(key) {
        key.to_string()
    } else {
        format!("\"{}\"", escape_yaml_str(key))
    }
}

fn is_ambiguous_yaml_key(key: &str) -> bool {
    let lower = key.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "true" | "false" | "null" | "~" | ".nan" | ".inf" | "+.inf" | "-.inf"
    ) || matches!(
        lower.strip_prefix(['+', '-']).unwrap_or(&lower),
        "inf" | "infinity" | "nan"
    ) || is_decimal_yaml_key(key)
}

fn is_decimal_yaml_key(key: &str) -> bool {
    let mut bytes = key.bytes().peekable();
    if matches!(bytes.peek(), Some(b'+' | b'-')) {
        bytes.next();
    }
    let mut digits = 0;
    while bytes.next_if(u8::is_ascii_digit).is_some() {
        digits += 1;
    }
    if bytes.next_if_eq(&b'.').is_some() {
        while bytes.next_if(u8::is_ascii_digit).is_some() {
            digits += 1;
        }
    }
    if digits == 0 {
        return false;
    }
    if matches!(bytes.peek(), Some(b'e' | b'E')) {
        bytes.next();
        if matches!(bytes.peek(), Some(b'+' | b'-')) {
            bytes.next();
        }
        let mut exponent_digits = 0;
        while bytes.next_if(u8::is_ascii_digit).is_some() {
            exponent_digits += 1;
        }
        if exponent_digits == 0 {
            return false;
        }
    }
    bytes.next().is_none()
}

fn quote_logfmt_key(key: &str) -> String {
    if is_safe_key(key) {
        key.to_string()
    } else {
        quote_logfmt_value(key)
    }
}

fn is_safe_key(key: &str) -> bool {
    !key.is_empty()
        && key
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}

fn yaml_scalar(value: &Value) -> String {
    match value {
        Value::String(s) => format!("\"{}\"", escape_yaml_str(s)),
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => format_number(n),
        Value::Object(_) | Value::Array(_) => {
            format!("\"{}\"", escape_yaml_str(&embedded_json(value)))
        }
    }
}

// ═══════════════════════════════════════════
// Plain Rendering (logfmt)
// ═══════════════════════════════════════════

fn collect_plain_pairs(value: &Value, prefix: &str, pairs: &mut Vec<(String, String)>) {
    if let Value::Object(map) = value {
        let processed = process_object_fields(map);
        for (display_key, v, formatted) in processed {
            let full_key = if prefix.is_empty() {
                display_key
            } else {
                format!("{}.{}", prefix, display_key)
            };
            if let Some(fv) = formatted {
                pairs.push((full_key, fv));
            } else {
                match v {
                    Value::Object(map) if map.is_empty() => {
                        pairs.push((full_key, "{}".to_string()));
                    }
                    Value::Object(_) => collect_plain_pairs(v, &full_key, pairs),
                    Value::Array(arr) if arr.is_empty() => {
                        pairs.push((full_key, "[]".to_string()));
                    }
                    Value::Array(arr) => {
                        let joined = arr.iter().map(plain_scalar).collect::<Vec<_>>().join(",");
                        pairs.push((full_key, joined));
                    }
                    Value::Null => pairs.push((full_key, String::new())),
                    _ => pairs.push((full_key, plain_scalar(v))),
                }
            }
        }
    }
}

fn collect_plain_pairs_raw(value: &Value, prefix: &str, pairs: &mut Vec<(String, String)>) {
    if let Value::Object(map) = value {
        for key in sorted_value_keys(map) {
            let v = &map[&key];
            let full_key = if prefix.is_empty() {
                key.clone()
            } else {
                format!("{}.{}", prefix, key)
            };
            match v {
                Value::Object(map) if map.is_empty() => {
                    pairs.push((full_key, "{}".to_string()));
                }
                Value::Object(_) => collect_plain_pairs_raw(v, &full_key, pairs),
                Value::Array(arr) if arr.is_empty() => {
                    pairs.push((full_key, "[]".to_string()));
                }
                Value::Array(arr) => {
                    let joined = arr.iter().map(plain_scalar).collect::<Vec<_>>().join(",");
                    pairs.push((full_key, joined));
                }
                Value::Null => pairs.push((full_key, String::new())),
                _ => pairs.push((full_key, plain_scalar(v))),
            }
        }
    }
}

fn plain_scalar(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => format_number(n),
        Value::Object(_) | Value::Array(_) => embedded_json(value),
    }
}

fn quote_logfmt_value(value: &str) -> String {
    if value.is_empty() {
        return String::new();
    }
    if !value.chars().any(|c| {
        matches!(
            c,
            ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b' | '\u{a0}' | '=' | '"' | '\\'
        )
    }) {
        return value.to_string();
    }
    let escaped = value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
        .replace('\x0c', "\\f")
        .replace('\x0b', "\\v");
    format!("\"{}\"", escaped)
}

/// A container inside a Plain array (or a YAML scalar position) is written as
/// compact JSON with sorted keys. Its number leaves take the canonical number
/// form, the same text the value prints as a scalar, so a nested `1.0` reads
/// `1` and a decoded `1e5` reads `100000` in every SDK rather than in each
/// runtime's own JSON spelling.
fn embedded_json(value: &Value) -> String {
    let mut out = String::new();
    write_embedded_json(value, &mut out);
    out
}

fn write_embedded_json(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            out.push('{');
            for (index, key) in sorted_value_keys(map).iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_json_string(key, out);
                out.push(':');
                write_embedded_json(&map[key], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_embedded_json(item, out);
            }
            out.push(']');
        }
        Value::String(text) => write_json_string(text, out),
        Value::Number(number) => out.push_str(&format_number(number)),
        Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
        Value::Null => out.push_str("null"),
    }
}

fn write_json_string(text: &str, out: &mut String) {
    // Serializing a `str` cannot fail; the fallback keeps this infallible.
    out.push_str(&serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_string()));
}

fn sorted_value_keys(map: &serde_json::Map<String, Value>) -> Vec<String> {
    let mut keys: Vec<String> = map.keys().cloned().collect();
    keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
    keys
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::redaction::{RedactionPolicy, Redactor};
    use serde_json::json;

    fn plain(value: &Value, policy: RedactionPolicy) -> String {
        render(
            value,
            OutputFormat::Plain,
            &OutputOptions {
                redaction: Redactor::new().policy(policy),
                style: PlainStyle::Readable,
            },
        )
    }

    // ── `_secret` stripping follows redaction ──────────

    #[test]
    fn plain_strips_secret_suffix_once_the_value_is_redacted() {
        assert_eq!(
            plain(
                &json!({"api_key_secret": "sk-live-xxx"}),
                RedactionPolicy::All
            ),
            "api_key=***"
        );
    }

    #[test]
    fn plain_keeps_secret_suffix_when_redaction_is_off() {
        // Stripping here would hand a live credential to a reader under a name
        // that no longer says it is one.
        assert_eq!(
            plain(
                &json!({"api_key_secret": "sk-live-xxx"}),
                RedactionPolicy::Off
            ),
            "api_key_secret=sk-live-xxx"
        );
        assert_eq!(
            plain(
                &json!({"API_KEY_SECRET": "sk-live-xxx"}),
                RedactionPolicy::Off
            ),
            "API_KEY_SECRET=sk-live-xxx"
        );
    }

    #[test]
    fn plain_keeps_secret_suffix_outside_trace_under_trace_only() {
        assert_eq!(
            plain(
                &json!({
                    "api_key_secret": "sk-live-xxx",
                    "trace": {"request_secret": "top-secret"}
                }),
                RedactionPolicy::TraceOnly
            ),
            "api_key_secret=sk-live-xxx trace.request=***"
        );
    }

    #[test]
    fn plain_keeps_secret_suffix_on_an_unredacted_subtree() {
        assert_eq!(
            plain(
                &json!({"db_secret": {"password": "hunter2"}}),
                RedactionPolicy::Off
            ),
            "db_secret.password=hunter2"
        );
        assert_eq!(
            plain(
                &json!({"db_secret": {"password": "hunter2"}}),
                RedactionPolicy::All
            ),
            "db=***"
        );
    }

    #[test]
    fn plain_unstripped_secret_key_does_not_collide_with_its_stem() {
        // Keeping the suffix also means no collision to fall back from: both
        // fields keep their own name and value.
        assert_eq!(
            plain(
                &json!({"api_key": "public", "api_key_secret": "sk-live-xxx"}),
                RedactionPolicy::Off
            ),
            "api_key=public api_key_secret=sk-live-xxx"
        );
    }
}